package com.gree.mall.miniapp.logic.material;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.bean.PayDetail;
import com.gree.mall.miniapp.bean.material.*;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.commonmapper.MaterialMapper;
import com.gree.mall.miniapp.constant.SybConstants;
import com.gree.mall.miniapp.enums.IsYesNoEnum;
import com.gree.mall.miniapp.enums.OrderInfoSourceEnum;
import com.gree.mall.miniapp.enums.PayOrderTypeEnum;
import com.gree.mall.miniapp.enums.PayTypeEnum;
import com.gree.mall.miniapp.enums.es.ESGoodsStatusEnum;
import com.gree.mall.miniapp.enums.material.WebsitGoodsTypeEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.helper.ResponseHelper;
import com.gree.mall.miniapp.logic.common.AllInPayLogic;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.common.outside.WechatLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import com.gree.mall.miniapp.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WebsitSalesLogic {

    @Value("${share.mall.appid}")
    private String mallAppid;

    @Resource
    MaterialMapper materialMapper;
    @Resource
    CommonLogic commonLogic;
    @Resource
    WebsitSalesService websitSalesService;
    @Resource
    WebsitSalesItemService websitSalesItemService;
    @Resource
    WebsitSalesPayOrderService websitSalesPayOrderService;
    @Resource
    WebsitShoppingCartService websitShoppingCartService;
    @Resource
    WebsitGoodsService websitGoodsService;
    @Resource
    WebsitGoodsPriceService websitGoodsPriceService;
    @Resource
    WebsitGoodsCategoryService websitGoodsCategoryService;
    @Resource
    WechatLogic wechatLogic;
    @Resource
    AllInPayLogic allInPayLogic;
    @Resource
    AdminWebsitPayConfigService adminWebsitPayConfigService;
    @Resource
    WebsitSalesPayMapService websitSalesPayMapService;
    @Resource
    MaterialConfigService materialConfigService;
    @Resource
    WorkerGoodsRelaService workerGoodsRelaService;
    @Resource
    WorkerGoodsService workerGoodsService;

    public IPage<SalesOrderBean> buyList(String flag, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        IPage<SalesOrderBean> page = materialMapper.buyList(new Page<>(pageNum, pageSize), wechat.getCurrentCompanyWechatId(), wechat.getUser().getWorkerNumber(), flag);
        return page;
    }

    public SalesOrderBean detail(HttpServletRequest request, String salesId) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        WebsitSales sales = websitSalesService.lambdaQuery()
                .eq(WebsitSales::getWorkerId, wechat.getUser().getWorkerNumber())
                .eq(WebsitSales::getSalesId, salesId)
                .one();
        if (Objects.isNull(sales)) {
            throw new RemoteServiceException("详情不存在");
        }

        SalesOrderBean bean = new SalesOrderBean();
        BeanUtils.copyProperties(sales, bean);

        List<WebsitSalesItem> items = websitSalesItemService.lambdaQuery()
                .eq(WebsitSalesItem::getSalesId, sales.getSalesId())
                .list();
        bean.setItems(items);

        WebsitSalesPayOrder order = websitSalesPayOrderService.lambdaQuery()
                .eq(WebsitSalesPayOrder::getOrderId, sales.getSalesId())
                .eq(WebsitSalesPayOrder::getGoodsType, WebsitGoodsTypeEnum.M.toString())
                .eq(WebsitSalesPayOrder::getPayFlag, IsYesNoEnum.YES.getKey())
                .last("limit 1")
                .one();

        if (Objects.nonNull(order)) {
            bean.setWebsitSalesPayOrder(order);
        }

        return bean;
    }

    public void cancel(HttpServletRequest request, String salesId) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        websitSalesService.lambdaUpdate()
                .set(WebsitSales::getFlag, "CANCEL")
                .eq(WebsitSales::getWorkerId, currentCompanyWechat.getUser().getWorkerNumber())
                .eq(WebsitSales::getSalesId, salesId)
                .in(WebsitSales::getFlag, "SAVE", "SUBMIT")
                .update();
    }

    public PayDetail pay(HttpServletRequest request, String salesId,Boolean miniPay,String openId) {
        String ip = IpUtil.getIpAddr(request);
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        WebsitSales sales = websitSalesService.lambdaQuery()
                .eq(WebsitSales::getSalesId, salesId)
                .eq(WebsitSales::getWorkerId, wechat.getUser().getWorkerNumber())
                .eq(WebsitSales::getFlag, "SUBMIT")
                .one();
        if (Objects.isNull(sales)) {
            throw new RemoteServiceException(salesId + "订单号不存在，无法发起支付");
        }

        if ( miniPay != null && miniPay) {
            websitSalesService.lambdaUpdate()
                    .eq(WebsitSales::getSalesId, salesId)
                    .set(WebsitSales::getSource, OrderInfoSourceEnum.A.getRemark())
                    .update();
        }else {
            websitSalesService.lambdaUpdate()
                    .eq(WebsitSales::getSalesId, salesId)
                    .set(WebsitSales::getSource, OrderInfoSourceEnum.B.getRemark())
                    .update();
        }
        return wechatLogic.payment(salesId, sales.getTotalAmount(),miniPay != null && miniPay?openId:wechat.getUser().getOpenId(), "N", ip, sales.getCompanyWechatId(),miniPay);
    }

    public List<WebsitSalesCategoryVO> existStockCategory(HttpServletRequest request, String websitId) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        return materialMapper.existStockCategory(wechat.getCompanyWechatId(), websitId);
    }

    public List<WebsitSalesGoodsVO> existStockGoods(HttpServletRequest request, String websitId, String categoryId, String type, String goodsName) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        List<WebsitSalesGoodsVO> goodsList = new ArrayList<>();
        if (type.equals(WebsitGoodsTypeEnum.M.toString())) {
            goodsList = materialMapper.existStockGoods(wechat.getCurrentCompanyWechatId(), websitId, type, categoryId, goodsName);
        } else {
            goodsList = materialMapper.notStockGoods(wechat.getCurrentCompanyWechatId(), websitId, type, categoryId, goodsName);
            if (CollectionUtil.isNotEmpty(goodsList)) {
                final MaterialConfig config = materialConfigService.lambdaQuery()
                        .eq(MaterialConfig::getCompanyWechatId, wechat.getUser().getCompanyWechatId())
                        .one();
                // 市场价乘于倍率
                for (WebsitSalesGoodsVO vo : goodsList) {
                    BigDecimal afterPrice;
                    switch (vo.getPartType()) {
                        case "空调":
                            afterPrice = vo.getPrice().multiply(config.getPriceRate1());
                            break;
                        case "冰箱":
                            afterPrice = vo.getPrice().multiply(config.getPriceRate2());
                            break;
                        case "生活电器":
                            afterPrice = vo.getPrice().multiply(config.getPriceRate3());
                            break;
                        default:
                            throw new RemoteServiceException("未找到对应配件类型倍率");
                    }
                    vo.setPrice(afterPrice);
                }
            }
        }


        return goodsList;
    }

    public MyDataCountBean count(HttpServletRequest request) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        MyDataCountBean bean = new MyDataCountBean();
        bean.setWaitPayCount(websitSalesService.lambdaQuery()
                .eq(WebsitSales::getWorkerId, wechat.getUser().getWorkerNumber())
                .eq(WebsitSales::getFlag, "SUBMIT")
                .count());
        bean.setEndPayCount(websitSalesService.lambdaQuery()
                .eq(WebsitSales::getWorkerId, wechat.getUser().getWorkerNumber())
                .eq(WebsitSales::getFlag, "PAY_NOT_TAKE")
                .count());
        bean.setEndCount(websitSalesService.lambdaQuery()
                .eq(WebsitSales::getWorkerId, wechat.getUser().getWorkerNumber())
                .eq(WebsitSales::getFlag, "PAY_TAKE")
                .count());
        bean.setSaveCount(websitSalesService.lambdaQuery()
                .eq(WebsitSales::getWorkerId, wechat.getUser().getWorkerNumber())
                .eq(WebsitSales::getFlag, "SAVE")
                .count());

        return bean;
    }

    public List<WebsitShoppingCartList> queryShoppingCart(String workerId, String websitId, String goodsType) {
        List<WebsitShoppingCartList> shoppingCartLists = materialMapper.queryShoppingCartList(workerId, websitId, goodsType);
        return shoppingCartLists;
    }

    @Transactional(rollbackFor = Exception.class)
    public List<WebsitShoppingCartList> addShoppingCart(WebsitShoppingCartBean shoppingCartBean, HttpServletRequest request) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        String websitId = shoppingCartBean.getWebsitId().trim();
        //先清空
        this.clearShoppingCart(wechat.getUserId(), websitId, shoppingCartBean.getGoodsType());

        List<WebsitBuyGood> websitBuyGoods = shoppingCartBean.getWebsitBuyGoods();
        if(websitBuyGoods == null || websitBuyGoods.size() == 0){
            return new ArrayList<>();
        }
        long count = websitBuyGoods.stream().filter(v -> v.getNum().compareTo(new BigDecimal("0")) <= 0).count();
        if(count > 0){
            throw new RemoteServiceException("请求失败存在数量小于0的请求数据");
        }
        if(!this.checkDist(websitBuyGoods)){
            throw new RemoteServiceException("有重复数据请重新请求");
        }

        List<WebsitGoods> goodsList = websitGoodsService.lambdaQuery()
                .eq(WebsitGoods::getCompanyWechatId, wechat.getCurrentCompanyWechatId())
                .in(WebsitGoods::getGoodsId, websitBuyGoods.stream()
                        .map(WebsitBuyGood::getGoodsId)
                        .collect(Collectors.toList()))
                .list();

        List<WebsitGoodsPrice> priceList = websitGoodsPriceService.lambdaQuery()
                .eq(WebsitGoodsPrice::getCompanyWechatId, wechat.getCurrentCompanyWechatId())
                .eq(WebsitGoodsPrice::getWebsitId, shoppingCartBean.getWebsitId())
                .in(WebsitGoodsPrice::getGoodsId, websitBuyGoods.stream()
                        .map(WebsitBuyGood::getGoodsId)
                        .collect(Collectors.toList()))
                .list();

        List<WebsitGoodsCategory> categoryList = websitGoodsCategoryService.lambdaQuery()
                .eq(WebsitGoodsCategory::getCompanyWechatId, wechat.getCurrentCompanyWechatId())
                .in(WebsitGoodsCategory::getCategoryId, goodsList.stream()
                        .map(WebsitGoods::getGoodsCategoryId)
                        .collect(Collectors.toList()))
                .list();

        Map<String, WebsitGoods> goodsMap = goodsList.stream()
                .collect(Collectors.toMap(WebsitGoods::getGoodsId, Function.identity(), (key1, key2) -> key2));

        Map<String, WebsitGoodsPrice> priceMap = priceList.stream()
                .collect(Collectors.toMap(WebsitGoodsPrice::getGoodsId, Function.identity(), (key1, key2) -> key2));

        Map<String, WebsitGoodsCategory> categoryMap = categoryList.stream()
                .collect(Collectors.toMap(WebsitGoodsCategory::getCategoryId, Function.identity(), (key1, key2) -> key2));

        // 增加
        List<WebsitShoppingCart> shoppingCarts = new ArrayList<>();

        for(WebsitBuyGood websitBuyGood : websitBuyGoods){
            WebsitGoods goods = goodsMap.get(websitBuyGood.getGoodsId());
            WebsitGoodsPrice price = priceMap.get(websitBuyGood.getGoodsId());
            WebsitGoodsCategory category = categoryMap.get(goods.getGoodsCategoryId());
            WebsitShoppingCart shoppingCart = new WebsitShoppingCart();
            shoppingCart.setWorkerId(wechat.getUserId());
            shoppingCart.setWorkerName(wechat.getUser().getNickName());
            shoppingCart.setWorkerWebsitId(shoppingCartBean.getWorkerWebsitId());
            shoppingCart.setWorkerWebsitName(shoppingCartBean.getWorkerWebsitName());
            shoppingCart.setWebsitId(shoppingCartBean.getWebsitId());
            shoppingCart.setWebsitName(shoppingCartBean.getWebsitName());
            shoppingCart.setCompanyWechatId(wechat.getCurrentCompanyWechatId());
            shoppingCart.setGoodsId(goods.getGoodsId());
            shoppingCart.setGoodsName(goods.getGoodsName());
            shoppingCart.setGoodsType(goods.getGoodsType());
            shoppingCart.setSalesQty(websitBuyGood.getNum());
            if (shoppingCartBean.getGoodsType().equals("M")) {
                shoppingCart.setPrice(price.getPrice());
            } else {
                shoppingCart.setPrice(goods.getMarketPrice());
            }
            shoppingCart.setSaleAmount(websitBuyGood.getNum().multiply(shoppingCart.getPrice()));
            shoppingCart.setParentCategoryId(goods.getParentCategoryId());
            shoppingCart.setGoodsCategoryId(goods.getGoodsCategoryId());
            if (Objects.nonNull(category)) {
                shoppingCart.setParentCategoryName(category.getParentCategoryName());
                shoppingCart.setGoodsCategoryName(category.getCategoryName());
            }
            shoppingCart.setBrand(goods.getBrandRelaName());
            shoppingCart.setProductCategory(goods.getProductRelaName());
            shoppingCart.setGoodsSalesConvertQty(goods.getGoodsSalesConvertQty());
            shoppingCart.setConvertBitScale(goods.getConvertBitScale());
            shoppingCart.setManageWorkerStock(goods.getManageWorkerStock());
            shoppingCart.setGoodsSalesUnit(goods.getGoodsSalesUnit());
            shoppingCart.setGoodsStockUnit(goods.getGoodsStockUnit());
            shoppingCart.setGoodsSpecification(goods.getGoodsSpecification());

            this.goodsConditionHandle(shoppingCart, goods);

            shoppingCart.setCreateTime(DateUtil.date());

            shoppingCarts.add(shoppingCart);
        }
        websitShoppingCartService.saveBatch(shoppingCarts);

        return this.queryShoppingCart(wechat.getUserId(), websitId, shoppingCartBean.getGoodsType());
    }

    private void goodsConditionHandle(WebsitShoppingCart shoppingCart, WebsitGoods goods) {
        // 商品类型为配件时单价要先乘倍率
        if (shoppingCart.getGoodsType().equals(WebsitGoodsTypeEnum.P.toString())) {
            final MaterialConfig config = materialConfigService.lambdaQuery()
                    .eq(MaterialConfig::getCompanyWechatId, goods.getCompanyWechatId())
                    .one();
            BigDecimal afterPrice;
            switch (goods.getPartType()) {
                case "空调":
                    afterPrice = goods.getMarketPrice().multiply(config.getPriceRate1());
                    break;
                case "冰箱":
                    afterPrice = goods.getMarketPrice().multiply(config.getPriceRate2());
                    break;
                case "生活电器":
                    afterPrice = goods.getMarketPrice().multiply(config.getPriceRate3());
                    break;
                default:
                    throw new RemoteServiceException("未找到对应配件类型倍率");
            }
            shoppingCart.setPrice(afterPrice);
            shoppingCart.setOrigPartsPrice(goods.getMarketPrice());
        }

        BigDecimal convertQty = shoppingCart.getSalesQty().divide(goods.getGoodsSalesConvertQty(), 1, BigDecimal.ROUND_UP);
        BigDecimal totalSaleValue = shoppingCart.getSalesQty().multiply(shoppingCart.getPrice());
        BigDecimal convertPrice = totalSaleValue.divide(convertQty, 2, BigDecimal.ROUND_DOWN);

        if (shoppingCart.getGoodsType().equals(WebsitGoodsTypeEnum.P.toString()) || goods.getGoodsSalesConvertQty().compareTo(BigDecimal.ONE) == 0) {
            convertQty = shoppingCart.getSalesQty();
            convertPrice = shoppingCart.getPrice();
            shoppingCart.setSaleAmount(totalSaleValue);
        }

        // 类型为辅材时注入师傅辅材id
        if (shoppingCart.getGoodsType().equals(WebsitGoodsTypeEnum.M.toString())
                && (StringUtils.isBlank(shoppingCart.getManageWorkerStock()) || shoppingCart.getManageWorkerStock().equals(IsYesNoEnum.YES.getKey()))) {
            final WorkerGoodsRela goodsRela = workerGoodsRelaService.lambdaQuery()
                    .eq(WorkerGoodsRela::getCompanyWechatId, goods.getCompanyWechatId())
                    .eq(WorkerGoodsRela::getWebsitGoodsId, goods.getGoodsId())
                    .one();
            if (Objects.nonNull(goodsRela)) {
                shoppingCart.setWorkerGoodsId(goodsRela.getWorkerGoodsId())
                        .setWorkerGoodsName(goodsRela.getWorkerGoodsName());
            }
        }

        shoppingCart.setConvertQty(convertQty)
                .setConvertPrice(convertPrice);
    }

    public void clearShoppingCart(String workerId, String websitId, String goodsType) {
        websitShoppingCartService.lambdaUpdate()
                .eq(WebsitShoppingCart::getWorkerId, workerId)
                .eq(WebsitShoppingCart::getWebsitId, websitId)
                .eq(WebsitShoppingCart::getGoodsType, goodsType)
                .remove();
    }

    /**
     * 判断是否重复
     */
    public Boolean checkDist(List<WebsitBuyGood> websitBuyGoods){

        Set<String> set = new HashSet<>();
        for(WebsitBuyGood websitBuyGood : websitBuyGoods){
            set.add(websitBuyGood.getGoodsId());
        }
        if(set.size() != websitBuyGoods.size()){
            return false;
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public String add(String websitId, String goodsType, String remark, HttpServletRequest request) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);

        if (StringUtils.isBlank(wechat.getUser().getMobile())) {
            throw new RemoteServiceException(ResponseHelper.ResponseCode_NOT_PHONE, "未发现手机号, 不能提交订单");
        }

        List<WebsitShoppingCartList> shoppingCartLists = this.queryShoppingCart(wechat.getUserId(), websitId, goodsType);

        //订单
        WebsitSales sales = new WebsitSales();

        // 检查是否有支付配置
//        final Integer payConfigCount = adminWebsitPayConfigService.lambdaQuery()
//                .eq(AdminWebsitPayConfig::getCompanyWechatId, wechat.getCompanyWechatId())
//                .eq(AdminWebsitPayConfig::getWebsitId, websitId)
//                .eq(AdminWebsitPayConfig::getType, goodsType)
//                .eq(AdminWebsitPayConfig::getStatus, true)
//                .count();
//
//        if (payConfigCount == 0) {
//            throw new RemoteServiceException("未配置线上收款");
//        }

        sales.setTotalAmount(BigDecimal.ZERO);

        //订单详情
        List<WebsitSalesItem> orderDetails = new ArrayList<>();

        String salesId = commonLogic.generateNo("X" + goodsType, "SalesOrder" + goodsType, 15);
        //新增订单详情
        for (WebsitShoppingCartList bean : shoppingCartLists) {
            WebsitSalesItem detail = new WebsitSalesItem();
            detail.setSalesId(salesId);
            detail.setCompanyWechatId(bean.getCompanyWechatId());
            detail.setGoodsType(bean.getGoodsType());
            detail.setWebsitId(bean.getWebsitId());
            detail.setWebsitName(bean.getWebsitName());
            detail.setGoodsId(bean.getGoodsId());
            detail.setGoodsName(bean.getGoodsName());
            detail.setSalesQty(bean.getSalesQty());
            detail.setPrice(bean.getPrice());
            detail.setSaleAmount(bean.getSaleAmount());
            detail.setGoodsSalesUnit(bean.getGoodsSalesUnit());
            detail.setGoodsStockUnit(bean.getGoodsStockUnit());
            detail.setGoodsSpecification(bean.getGoodsSpecification());
            detail.setPayType(detail.getPayType());
            detail.setParentCategoryId(bean.getParentCategoryId());
            detail.setParentCategoryName(bean.getParentCategoryName());
            detail.setGoodsCategoryId(bean.getGoodsCategoryId());
            detail.setGoodsCategoryName(bean.getGoodsCategoryName());
            detail.setBrand(bean.getBrand());
            detail.setProductCategory(bean.getProductCategory());
            detail.setGoodsSalesConvertQty(bean.getGoodsSalesConvertQty());
            detail.setConvertBitScale(bean.getConvertBitScale());
            detail.setManageWorkerStock(bean.getManageWorkerStock());
            detail.setConvertQty(bean.getConvertQty());
            detail.setConvertPrice(bean.getConvertPrice());

            if (bean.getGoodsType().equals(WebsitGoodsTypeEnum.M.toString())) {
                final WorkerGoods workerGoods = workerGoodsService.getById(bean.getWorkerGoodsId());
                detail.setWorkerGoodsId(workerGoods.getStatus().equals(ESGoodsStatusEnum.ON.getKey()) ? bean.getWorkerGoodsId() : null);
                detail.setWorkerGoodsName(workerGoods.getStatus().equals(ESGoodsStatusEnum.ON.getKey()) ? bean.getWorkerGoodsName() : null);
            }

            detail.setOrigPartsPrice(bean.getOrigPartsPrice());

            orderDetails.add(detail);

            sales.setCompanyWechatId(bean.getCompanyWechatId());
            sales.setCompanyWechatName(wechat.getCurrentCompanyName());
            sales.setWebsitId(bean.getWebsitId());
            sales.setWebsitName(bean.getWebsitName());
            sales.setGoodsType(bean.getGoodsType());
            sales.setWorkerId(wechat.getUser().getWorkerNumber());
            sales.setWorkerName(bean.getWorkerName());
            sales.setWorkerWebsitId(bean.getWorkerWebsitId());
            sales.setWorkerWebsitName(bean.getWorkerWebsitName());

            sales.setTotalAmount(sales.getTotalAmount().add(bean.getSaleAmount()));

        }

        sales.setSalesId(salesId);
        sales.setIdentity(wechat.getUser().getIdCard());
        sales.setWorkerMobile(wechat.getUser().getMobile());
        sales.setSalesTime(DateUtil.date());
        sales.setOrderSource("ONLINE");
//        sales.setFlag("SUBMIT");
        sales.setFlag("SAVE");
        sales.setRemark(remark);
        sales.setCreateBy(wechat.getUser().getNickName());
        sales.setCreateTime(sales.getSalesTime());
        sales.setUpdateBy(wechat.getUser().getNickName());
        sales.setUpdateTime(sales.getSalesTime());
        sales.setSubmitBy(wechat.getUser().getNickName());
        sales.setSubmitTime(sales.getSalesTime());

        websitSalesItemService.saveBatch(orderDetails);

        sales.insert();

        //清除购物车
        this.clearShoppingCart(sales.getWorkerId(), sales.getWebsitId(), sales.getGoodsType());

        return salesId;
    }

    public List<AdminWebsitPayConfig> getPayConfig(String websitId, String goodsType, HttpServletRequest request) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat(request);
        return adminWebsitPayConfigService.lambdaQuery()
                .eq(AdminWebsitPayConfig::getCompanyWechatId, wechat.getCompanyWechatId())
                .eq(AdminWebsitPayConfig::getWebsitId, websitId)
                .eq(AdminWebsitPayConfig::getType, goodsType)
                .eq(AdminWebsitPayConfig::getStatus, true)
                .list();
    }

    @Transactional
    public WebsitSalesPayMapBean saveSheetPayMap(WebsitSalesPayMapBean sheetPayMap) {
        if (StringUtils.isBlank(sheetPayMap.getSalesId())) {
            throw new RemoteServiceException("订单号不能为空");
        }
        if (StringUtils.isBlank(sheetPayMap.getPayConfigId())) {
            throw new RemoteServiceException("支付配置不能为空");
        }

        // 获取支付记录
        List<WebsitSalesPayOrder> payList = websitSalesPayOrderService.lambdaQuery()
                .eq(WebsitSalesPayOrder::getOrderId, sheetPayMap.getSalesId())
                .orderByAsc(WebsitSalesPayOrder::getId)
                .list();
        // 判断是否存在一个或以上支付记录
        if (CollectionUtil.isNotEmpty(payList)) {
            WebsitSalesPayOrder salesPayList = payList.get(payList.size() - 1);
            // 判断是否支付
            if (salesPayList.getPayFlag().equals(IsYesNoEnum.YES.getKey())) {
                throw new RemoteServiceException(salesPayList.getOrderId() + " 订单已支付，请刷新界面！");
            }
        }

        sheetPayMap.setId(IdWorker.getIdStr());
        sheetPayMap.setAppid(mallAppid);
        sheetPayMap.setAppOrderId(sheetPayMap.getId());
        websitSalesPayMapService.save(sheetPayMap);

        return sheetPayMap;
    }

    /**
     * 生成支付记录
     * @param key
     * @param openid
     * @param salesId
     * @param payType
     * @param frontUrl
     * @return
     */
    public PayDetail generatePayRecord(String key, String openid, String salesId, String payType, String frontUrl) {
        CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat();
        PayDetail payDetail = null;
        AdminWebsitPayConfig payConfig = null;
        WebsitSales sales = null;
        if (SybConstants.PAY_TYPE_W06.equals(payType)) {
            final WebsitSalesPayMap payMap = websitSalesPayMapService.getById(key);

            payConfig = adminWebsitPayConfigService.getById(payMap.getPayConfigId());

            sales = websitSalesService.getById(payMap.getSalesId());
        } else if (SybConstants.PAY_TYPE_W02.equals(payType)) {
            openid = wechat.getUser().getOpenId();
            payConfig = adminWebsitPayConfigService.getById(key);

            sales = websitSalesService.getById(salesId);
        }
        if (Objects.nonNull(sales)) {
            WebsitSalesPayOrder payOrder = new WebsitSalesPayOrder();
            payOrder.setId(IdWorker.getIdStr())
                    .setCompanyWechatId(sales.getCompanyWechatId())
                    .setCompanyWechatName(sales.getCompanyWechatName())
                    .setGoodsType(sales.getGoodsType())
                    .setWebsitId(sales.getWebsitId())
                    .setWebsitName(sales.getWebsitName())
                    .setOrderId(sales.getSalesId())
                    .setOutTradeNo(payOrder.getId())
                    .setOpenid(openid)
                    .setPayType(PayTypeEnum.ALLINPAY.getKey())
                    .setOrderCreateTime(sales.getCreateTime())
                    .setPayValue(sales.getTotalAmount())
                    .setOrgId(payConfig.getOrgId())
                    .setMchNo(payConfig.getMchNo())
                    .setAppid(payConfig.getAppid())
                    .setOrderType(PayOrderTypeEnum.S.getKey())
                    .setRunTime(DateUtil.offsetSecond(DateUtil.date(), 10))
                    .setOrderSource(sales.getGoodsType().equals(WebsitGoodsTypeEnum.M.toString()) ? "M_SALES" : "P_SALES")
                    .setIsDeliver(false)
                    .setSource(payType.equals(SybConstants.PAY_TYPE_W06) ? "小程序" : "公众号");


            // 请求通联得到结果
            Map<String, String> resMap = allInPayLogic.serviceUnifiedOrder(payOrder, payType, frontUrl);

            if (!resMap.get("trxstatus").equals("0000")) {
                throw new RemoteServiceException("通联统一支付接口执行失败：" + resMap.get("errmsg"));
            }

            payOrder.setOrderNo(resMap.get("trxid"))
                    .insert();

            payDetail = new PayDetail();
            payDetail.setCodeUrl(resMap.get("payinfo"));
            payDetail.setId(payOrder.getId());
            log.info("通联支付payDetail:{}", JSONObject.toJSONString(payDetail));
        }

        return payDetail;
    }
}
