package org.jeecg.api.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.api.bean.PageBean;
import org.jeecg.api.service.AppletIndexService;
import org.jeecg.api.service.AppletInfoService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.commonAddOrder.entity.CommonAddOrder;
import org.jeecg.modules.commonAddOrder.service.ICommonAddOrderService;
import org.jeecg.modules.commonAddress.entity.CommonAddress;
import org.jeecg.modules.commonAddress.service.ICommonAddressService;
import org.jeecg.modules.commonBanner.entity.CommonBanner;
import org.jeecg.modules.commonBanner.service.ICommonBannerService;
import org.jeecg.modules.commonCity.service.ICommonCityService;
import org.jeecg.modules.commonIconImage.entity.CommonIconImage;
import org.jeecg.modules.commonIconImage.service.ICommonIconImageService;
import org.jeecg.modules.commonMoneyLog.entity.CommonMoneyLog;
import org.jeecg.modules.commonMoneyLog.service.ICommonMoneyLogService;
import org.jeecg.modules.commonOrder.entity.CommonOrder;
import org.jeecg.modules.commonOrder.service.ICommonOrderService;
import org.jeecg.modules.commonShop.entity.CommonShop;
import org.jeecg.modules.commonShop.service.ICommonShopService;
import org.jeecg.modules.commonShopClass.entity.CommonShopClass;
import org.jeecg.modules.commonShopClass.service.ICommonShopClassService;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.pay.MpWxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.integration.IntegrationGraphEndpoint;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AppletIndexServiceImpl implements AppletIndexService {


    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    @Resource
    private ICommonBannerService commonBannerService;
    @Resource
    private ICommonIconImageService commonIconImageService;
    @Resource
    private ICommonShopService commonShopService;
    @Resource
    private ICommonShopClassService commonShopClassService;
    @Resource
    private ICommonAddOrderService commonAddOrderService;
    @Resource
    private ICommonAddressService commonAddressService;
    @Resource
    private ICommonOrderService commonOrderService;
    @Resource
    private ICommonMoneyLogService commonMoneyLogService;
    @Resource
    private ICommonCityService commonCityService;
    //支付接口
    @Autowired
    private MpWxPayService mpWxPayService;

        //获取首页banner
    @Override
    public Result<?> getBanner(){
        List<CommonBanner> list = commonBannerService.list();
        return Result.OK("首页banner",list);
    }


    //获取金刚区icon
    @Override
    public Result<?> getIcon(){
        List<CommonIconImage> list = commonIconImageService.list();
        return Result.OK("金刚区icon",list);
    }

    //获取分类
    @Override
    public Result<?> getClassify(){
        List<CommonShopClass> list = commonShopClassService
                .lambdaQuery()
                .eq(CommonShopClass::getPid,0)
                .list();
        list.forEach(item->{
            item.setChildren(commonShopClassService
                    .lambdaQuery()
                    .eq(CommonShopClass::getPid,item.getId())
                    .list());
        });
        return Result.OK("建材分类",list);
    }

    //获取城市
    @Override
    public Result<?> getCity(){
        return Result.OK("城市",commonCityService.list());
    }

    //获取建材商品信息列表带分页搜索
    @Override
    public Result<?> getProductList(String cityId,String shopIconId, String shopClassId, PageBean pageBean){
        Page<CommonShop> page = new Page<CommonShop>(pageBean.getPageNo(), pageBean.getPageSize());
            page = commonShopService.lambdaQuery()
                    .like(StringUtils.isNotBlank(pageBean.getTitle()),CommonShop::getName,pageBean.getTitle())
                    .eq(StringUtils.isNotBlank(shopIconId),CommonShop::getShopCion,shopIconId)
                    .like(StringUtils.isNotBlank(shopClassId),CommonShop::getShopClass,shopClassId)
                    .eq(StringUtils.isNotBlank(cityId),CommonShop::getCityId,cityId)
                    .eq(CommonShop::getIsOpen,"Y")
                    .page(page);
        return Result.OK("建材商品信息列表",page);
    }


    //获取商品信息详情
    @Override
    public Result<?> getProductDetail(String productId){
        CommonShop commonShop = commonShopService.getById(productId);
        return Result.OK("商品信息详情",commonShop);
    }


    //根据用户登录信息获取当前是否有快捷下单订单
    @Override
    public Result<?> getOrderInfo(String token){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        List<CommonAddOrder> list = commonAddOrderService.lambdaQuery()
                .eq(CommonAddOrder::getUserId, hanHaiMember.getId())
                .eq(CommonAddOrder::getStatus, "1")
                .eq(CommonAddOrder::getIsPay, "N")
                .orderByDesc(CommonAddOrder::getCreateTime)
                .list();
        //如果有数据返回数据，循环赋值
        List<CommonAddOrder> listNew  = new ArrayList<>();
        if (list.size()>0){
            for (CommonAddOrder commonAddOrder : list) {
                //获取商品标识
                String[] shopIdSplit = commonAddOrder.getShopId().split(",");
                //创建一个集合
                List<CommonShop> list1 = new ArrayList<>();
                for (String shopId : shopIdSplit) {
                    //获取商品信息
                    CommonShop commonShop = commonShopService.getById(shopId);
                    //加入集合
                    list1.add(commonShop);
                }
                commonAddOrder.setCommonShop(list1);
                listNew.add(commonAddOrder);
            }
        }
        return Result.OK("快捷订单查询成功",listNew);
    }



    //快捷下单-拍照下单/语音下单
    @Override
    public Result<?> addOrder(String token, CommonAddOrder commonAddOrder){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        commonAddOrder.setUserId(hanHaiMember.getId());
        commonAddOrder.setStatus("0");
        commonAddOrder.setIsPay("N");
        commonAddOrder.setCreateTime(new Date());
        commonAddOrderService.save(commonAddOrder);
        return Result.OK("快捷下单成功");
    }

    //取消快捷订单
    @Override
    public Result<?> cancelOrder(String token,String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        CommonAddOrder commonAddOrder = commonAddOrderService.getById(orderId);
        //存在则删除
        if (commonAddOrder!=null){
            commonAddOrderService.removeById(orderId);
        }
        return Result.OK("取消快捷订单成功");
    }

    //创建订单
    @Override
    public Result<?> createOrder(String token,Integer payType,String productId,String addressId,Integer orderNum){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        CommonShop commonShop = commonShopService.getById(productId);
        if (commonShop==null){
            return Result.error("商品信息不存在");
        }
        CommonAddress commonAddress = commonAddressService.getById(addressId);
        if (commonAddress==null){
            return Result.error("地址信息不存在");
        }
        //根据类型创建订单payType=0余额支付,1、微信支付
        if (payType==0){
            if (hanHaiMember.getMoney().compareTo(commonShop.getPrice())==-1){
                return Result.error("余额不足");
            }
            if (commonShop.getNum()==0){
                return Result.error("库存不足");
            }

            Integer num = commonShop.getNum();
            //转换位int类型
            int numInt = Integer.parseInt(num.toString());
            int i = numInt-1;
            //转换位Integer类型
            commonShop.setNum(Integer.valueOf(i));

            commonShopService.updateById(commonShop);

            //创建订单
            CommonOrder commonOrder = new CommonOrder();
            commonOrder.setStatus("0");
            commonOrder.setUserId(hanHaiMember.getId());
            commonOrder.setImage(commonShop.getImage());
            commonOrder.setTitle(commonShop.getName());
            commonOrder.setName(commonAddress.getName());
            commonOrder.setPhone(commonAddress.getPhone());
            commonOrder.setPrice(commonShop.getPrice());
            commonOrder.setCreateTime(new Date());
            commonOrder.setAddress(commonAddress.getAddress());
            commonOrder.setAddressDetail(commonAddress.getAddressDetails());
            commonOrder.setOneMoney(commonShop.getOneMoney());
            commonOrder.setTwoMoney(commonShop.getTwoMoney());
            commonOrderService.save(commonOrder);

            return  Result.OK("余额支付成功",commonOrder);
        }else{
            //微信支付
            if (commonShop.getNum()==0){
                return Result.error("库存不足");
            }
            Integer num = commonShop.getNum();
            //转换位int类型
            int numInt = Integer.parseInt(num.toString());
            int i = numInt-1;
            //转换位Integer类型
            commonShop.setNum(Integer.valueOf(i));
            commonShopService.updateById(commonShop);




            //创建订单
            CommonOrder commonOrder = new CommonOrder();
            commonOrder.setStatus("0");
            commonOrder.setUserId(hanHaiMember.getId());
            commonOrder.setImage(commonShop.getImage());
            commonOrder.setTitle(commonShop.getName());
            commonOrder.setName(commonAddress.getName());
            commonOrder.setPhone(commonAddress.getPhone());
            commonOrder.setPrice(commonShop.getPrice());
            commonOrder.setCreateTime(new Date());
            commonOrder.setAddress(commonAddress.getAddress());
            commonOrder.setAddressDetail(commonAddress.getAddressDetails());
            commonOrder.setOneMoney(commonShop.getOneMoney());
            commonOrder.setTwoMoney(commonShop.getTwoMoney());
            commonOrderService.save(commonOrder);

            BigDecimal payPrice = commonOrder.getPrice();

            //吊起微信支付
            String s = payPrice.multiply(new BigDecimal(100)).toString();
            int i1 = Double.valueOf(s).intValue();
            Object appOrder = mpWxPayService.createOrder(
                    "购买"+commonOrder.getTitle(),
                    "127.0.0.1",
                    commonOrder.getId(),
                    i1,
                    commonOrder.getId(),
                    hanHaiMember.getAppletOpenid(),
                    commonOrder.toString());

            return Result.OK("支付成功",appOrder);
        }
    }


    //立即支付
    @Override
    public Result<?> payOrder(String token,Integer type,String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        if (type==0){
            CommonOrder commonOrder = commonOrderService.getById(orderId);
            if (commonOrder.getStatus().equals("0")){
                if (hanHaiMember.getMoney().compareTo(commonOrder.getPrice())==-1){
                    return Result.error("余额不足");
                }
            }
            if (commonOrder.getStatus().equals("0")){
                commonOrder.setStatus("1");
                commonOrderService.updateById(commonOrder);
                HanHaiMember hanHaiMember1 = hanHaiMemberService.getById(hanHaiMember.getId());
                hanHaiMember1.setMoney(hanHaiMember1.getMoney().subtract(commonOrder.getPrice()));
                hanHaiMemberService.updateById(hanHaiMember1);
                CommonMoneyLog commonMoneyLog = new CommonMoneyLog();
                commonMoneyLog.setCreateTime(new Date());
                commonMoneyLog.setTitle("支付订单");
                commonMoneyLog.setMoney(commonOrder.getPrice());
                commonMoneyLog.setUserId(hanHaiMember.getId());
                commonMoneyLog.setOldMoney(hanHaiMember1.getMoney());
                commonMoneyLog.setType(1);
                commonMoneyLog.setState(0);
                commonMoneyLogService.save(commonMoneyLog);
                return Result.OK("支付成功");

            }
        }else {
            CommonOrder commonOrder = commonOrderService.getById(orderId);
            if (commonOrder.getStatus().equals("0")){
                BigDecimal payPrice = commonOrder.getPrice();

                //吊起微信支付
                String s = payPrice.multiply(new BigDecimal(100)).toString();
                int i1 = Double.valueOf(s).intValue();
                Object appOrder = mpWxPayService.createOrder(
                        "购买"+commonOrder.getTitle(),
                        "127.0.0.1",
                        commonOrder.getId(),
                        i1,
                        commonOrder.getId(),
                        hanHaiMember.getAppletOpenid(),
                        commonOrder.toString());

                return Result.OK("支付成功",appOrder);
            }
        }
        return  Result.error("订单已支付");
    }


    //快捷订单列表数据带分页
    @Override
    public Result<?> getAddOrderPageBean(String token,String state,PageBean pageBean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        Page<CommonAddOrder> page = new Page<CommonAddOrder>(pageBean.getPageNo(), pageBean.getPageSize());
        Page<CommonAddOrder> pageList = commonAddOrderService.lambdaQuery()
                .eq(CommonAddOrder::getUserId,hanHaiMember.getId())
                .eq(StringUtils.isNotBlank(state),CommonAddOrder::getStatus,state)
                .page(page);
        //得到集合
        List<CommonAddOrder> records = pageList.getRecords();
        //创建一个新的集合
        List<CommonAddOrder> commonAddOrders = new ArrayList<>();

        records.forEach(item->{
            if(StringUtils.isNotBlank(item.getShopId())){
                //获取商品标识
                String[] shopIdSplit = item.getShopId().split(",");
                //创建一个集合
                List<CommonShop> list1 = new ArrayList<>();
                for (String shopId : shopIdSplit) {
                    //获取商品信息
                    CommonShop commonShop = commonShopService.getById(shopId);
                    //加入集合
                    list1.add(commonShop);
                }

            }
            commonAddOrders.add(item);

        });
        pageList.setRecords(commonAddOrders);

        return Result.OK("快捷订单信息列表",pageList);
    }


    //查询快捷订单详情
    @Override
    public Result<?> getAddOrderInfo(String token,String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        CommonAddOrder commonAddOrder = commonAddOrderService.getById(orderId);
        //写入商品信息
        //如果有数据返回数据，循环赋值
        //获取商品标识
        String[] shopIdSplit = commonAddOrder.getShopId().split(",");
        //创建一个集合
        List<CommonShop> list1 = new ArrayList<>();
        for (String shopId : shopIdSplit) {
            //获取商品信息
            CommonShop commonShop = commonShopService.getById(shopId);
            //加入集合
            list1.add(commonShop);
        }
        commonAddOrder.setCommonShop(list1);
        if (commonAddOrder.getUserId().equals(hanHaiMember.getId())){
            return Result.OK("快捷订单信息",commonAddOrder);
        }
        return Result.error("订单信息不存在");
    }


}
