package com.gree.mall.manager.logic.workorder;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
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.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.manage.WebsitPurchaseVO;
import com.gree.mall.manager.bean.workorder.*;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.base.BaseEnum;
import com.gree.mall.manager.enums.material.OrderUseTypeEnum;
import com.gree.mall.manager.enums.workorder.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class SettleOrderLogic {
    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final PgSettleOrderService pgSettleOrderService;
    private final PgSettlePoolService pgSettlePoolService;
    private final PgSettlePoolWorkerService pgSettlePoolWorkerService;
    private final PgSettlePoolItemService pgSettlePoolItemService;
    private final PgOrderSettleNormService pgOrderSettleNormService;
    private final PgOrderWorkerService pgOrderWorkerService;
    private final PgOrderSettleWorkerService pgOrderSettleWorkerService;
    private final PgOrderBaseService pgOrderBaseService;
    private final PgOrderProductService pgOrderProductService;

    public IPage<SettleOrderVO> list(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, SettleOrderVO.class, adminUser);

        return commonMapper.settleOrderList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getAdminWebsitIds());

    }

    @Transactional
    public void pool(SettleOrderBean bean, AdminUserCom adminUser) {
        if (StringUtils.isBlank(bean.getMonth())) {
            throw new RemoteServiceException("月份不能为空");
        }

        if (Objects.isNull(bean.getStarDate()) || Objects.isNull(bean.getEndDate())) {
            throw new RemoteServiceException("请选择结算范围");
        }

        List<PgSettleOrder> orders = pgSettleOrderService.lambdaQuery()
                .eq(PgSettleOrder::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(PgSettleOrder::getPoolStatus, PoolStatusEnum.NO.getKey())
                .between(PgSettleOrder::getCreateTime, bean.getStarDate(), bean.getEndDate())
                .list();

        this.commonPoolHandle(orders, bean, adminUser);
    }

    private void commonPoolHandle(List<PgSettleOrder> orders, SettleOrderBean bean, AdminUserCom adminUser) {
        if (CollectionUtil.isEmpty(orders)) {
            throw new RemoteServiceException("结算范围记录条数为0，请检查");
        }

        List<PgSettleOrder> updateList = new ArrayList<>();
        // 按网点分组
        Map<String, List<PgSettleOrder>> websitMap = orders.stream()
                .collect(Collectors.groupingBy(PgSettleOrder::getWebsitId));

        Set<String> websitSet = orders.stream().map(PgSettleOrder::getWebsitId).collect(Collectors.toSet());

        for (String websitId : websitSet) {
            if (websitMap.containsKey(websitId)) {
                // 按网点师傅执行汇总
                List<PgSettleOrder> pgSettleOrders = websitMap.get(websitId);
                Map<String, List<PgSettleOrder>> workerMap = pgSettleOrders.stream().collect(Collectors.groupingBy(PgSettleOrder::getWorkerId));

                PgSettlePool pool = new PgSettlePool();
                pool.setId(IdWorker.getIdStr())
                        .setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId())
                        .setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName())
                        .setWebsitId(websitId)
                        .setWebsitName(pgSettleOrders.get(0).getWebsitName())
                        .setWorkerNum(workerMap.values().size())
                        .setTotalAmount(BigDecimal.ZERO)
                        .setMonth(bean.getMonth())
                        .setPoolCreateBy(adminUser.getNickName())
                        .setPoolCreateTime(DateUtil.date());

                List<PgSettlePoolWorker> workerList = new ArrayList<>();
                List<PgSettlePoolItem> items = new ArrayList<>();
                for (Map.Entry<String, List<PgSettleOrder>> worker : workerMap.entrySet()) {
                    List<PgSettleOrder> workerOrderList = worker.getValue();

                    PgSettlePoolWorker poolWorker = new PgSettlePoolWorker();
                    poolWorker.setPoolId(pool.getId())
                            .setMonth(pool.getMonth())
                            .setCompanyWechatId(pool.getCompanyWechatId())
                            .setCompanyWechatName(pool.getCompanyWechatName())
                            .setWebsitId(pool.getWebsitId())
                            .setWebsitName(pool.getWebsitName())
                            .setWorkerId(workerOrderList.get(0).getWorkerId())
                            .setWorkerName(workerOrderList.get(0).getWorkerName())
                            .setWorkerMobile(workerOrderList.get(0).getWorkerMobile())
                            .setWorkerIdcard(workerOrderList.get(0).getWorkerIdcard())
                            .setPoolCreateBy(pool.getPoolCreateBy())
                            .setPoolCreateTime(pool.getPoolCreateTime())
                            .setTotalAmount(BigDecimal.ZERO);
                    BigDecimal totalAmount = BigDecimal.ZERO;
                    for (PgSettleOrder order : workerOrderList) {
                        PgSettlePoolItem item = new PgSettlePoolItem();
                        item.setCompanyWechatId(pool.getCompanyWechatId())
                                .setPoolId(pool.getId())
                                .setOrderId(order.getId());
                        totalAmount = totalAmount.add(order.getSettleAmount());
                        items.add(item);
                        // 更新结算单汇总信息
                        order.setPoolStatus(PoolStatusEnum.YES.getKey())
                                .setPoolId(pool.getId())
                                .setPoolBy(pool.getPoolCreateBy())
                                .setPoolTime(pool.getPoolCreateTime());
                        updateList.add(order);
                    }

                    // 师傅结算总金额
                    poolWorker.setTotalAmount(totalAmount);
                    // 汇总账单结算金额
                    pool.setTotalAmount(pool.getTotalAmount().add(totalAmount));
                    workerList.add(poolWorker);
                }

                pool.insert();
                pgSettlePoolWorkerService.saveBatch(workerList);
                pgSettlePoolItemService.saveBatch(items);
            }
        }
        pgSettleOrderService.saveOrUpdateBatch(updateList);

        // 师傅结算费用更新汇总状态
        List<PgOrderSettleWorker> settleWorkers = pgOrderSettleWorkerService.lambdaQuery()
                .in(PgOrderSettleWorker::getSettleOrderId, updateList.stream()
                        .map(PgSettleOrder::getId)
                        .collect(Collectors.toList()))
                .list();

        Map<String, PgSettleOrder> orderMap = updateList.stream()
                .collect(Collectors.toMap(PgSettleOrder::getId, Function.identity()));

        for (PgOrderSettleWorker settleWorker : settleWorkers) {
            PgSettleOrder order = orderMap.get(settleWorker.getSettleOrderId());
            if (Objects.isNull(order)) {
                throw new RemoteServiceException("未匹配到" + settleWorker.getSettleOrderId() + "结算单的师傅信息");
            }
            settleWorker.setPoolStatus(PoolStatusEnum.YES.getKey())
                    .setPoolId(order.getPoolId());
        }

        pgOrderSettleWorkerService.saveOrUpdateBatch(settleWorkers);
    }

    @Transactional
    public void batchPool(SettleOrderBean bean, AdminUserCom adminUser) {
        List<PgSettleOrder> orders = pgSettleOrderService.lambdaQuery()
                .eq(PgSettleOrder::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(PgSettleOrder::getPoolStatus, PoolStatusEnum.NO.getKey())
                .in(PgSettleOrder::getId, bean.getIds())
                .list();

        // 当前月份
        String yearMonth = DateUtil.format(DateUtil.date(), "yyyy-MM");
        bean.setMonth(yearMonth);

        this.commonPoolHandle(orders, bean, adminUser);
    }

    @Transactional
    public void batchConfirm(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        DateTime curTime = DateUtil.date();
        pgSettlePoolService.lambdaUpdate()
                .set(PgSettlePool::getPoolUpdateBy, adminUser.getNickName())
                .set(PgSettlePool::getPoolUpdateTime, curTime)
                .set(PgSettlePool::getStatus, SettlePoolStatusEnum.YES.getKey())
                .in(PgSettlePool::getId, ids)
                .eq(PgSettlePool::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(PgSettlePool::getStatus, SettlePoolStatusEnum.NO.getKey())
                .update();

        pgSettlePoolWorkerService.lambdaUpdate()
                .set(PgSettlePoolWorker::getPoolUpdateBy, adminUser.getNickName())
                .set(PgSettlePoolWorker::getPoolUpdateTime, curTime)
                .set(PgSettlePoolWorker::getStatus, SettlePoolStatusEnum.YES.getKey())
                .in(PgSettlePoolWorker::getPoolId, ids)
                .eq(PgSettlePoolWorker::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(PgSettlePoolWorker::getStatus, SettlePoolStatusEnum.NO.getKey())
                .update();

    }

    @Transactional
    public void batchCancel(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        DateTime curTime = DateUtil.date();
        pgSettlePoolService.lambdaUpdate()
                .set(PgSettlePool::getPoolUpdateBy, adminUser.getNickName())
                .set(PgSettlePool::getPoolUpdateTime, curTime)
                .set(PgSettlePool::getStatus, SettlePoolStatusEnum.NOT.getKey())
                .in(PgSettlePool::getId, ids)
                .eq(PgSettlePool::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(PgSettlePool::getStatus, SettlePoolStatusEnum.NO.getKey())
                .update();

        pgSettlePoolWorkerService.lambdaUpdate()
                .set(PgSettlePoolWorker::getPoolUpdateBy, adminUser.getNickName())
                .set(PgSettlePoolWorker::getPoolUpdateTime, curTime)
                .set(PgSettlePoolWorker::getStatus, SettlePoolStatusEnum.NOT.getKey())
                .in(PgSettlePoolWorker::getPoolId, ids)
                .eq(PgSettlePoolWorker::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(PgSettlePoolWorker::getStatus, SettlePoolStatusEnum.NO.getKey())
                .update();

        // 结算单变更未汇总状态
        pgSettleOrderService.lambdaUpdate()
                .set(PgSettleOrder::getLastCancelBy, adminUser.getNickName())
                .set(PgSettleOrder::getLastCancelTime, curTime)
                .set(PgSettleOrder::getPoolStatus, PoolStatusEnum.NO.getKey())
                .set(PgSettleOrder::getPoolTime, null)
                .set(PgSettleOrder::getPoolId, "")
                .in(PgSettleOrder::getPoolId, ids)
                .eq(PgSettleOrder::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(PgSettleOrder::getPoolStatus, PoolStatusEnum.YES.getKey())
                .update();

        // 师傅结算费用更新汇总状态
        pgOrderSettleWorkerService.lambdaUpdate()
                .set(PgOrderSettleWorker::getPoolStatus, PoolStatusEnum.NO.getKey())
                .set(PgOrderSettleWorker::getPoolId, "")
                .in(PgOrderSettleWorker::getPoolId, ids)
                .update();
    }

    /**
     * 批量明细驳回
     * @param bean
     */
    @Transactional
    public void batchItemCancel(PoolSettleItemBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<PgSettlePoolItem> poolItems = pgSettlePoolItemService.lambdaQuery()
                .eq(PgSettlePoolItem::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(PgSettlePoolItem::getPoolId, bean.getPoolId())
                .in(PgSettlePoolItem::getOrderId, bean.getIds())
                .list();

        if (CollectionUtil.isEmpty(poolItems)) {
            throw new RemoteServiceException("账单明细不存在");
        }

        PgSettlePool settlePool = pgSettlePoolService.getById(poolItems.get(0).getPoolId());

        if (!settlePool.getStatus().equals(SettlePoolStatusEnum.NO.getKey())) {
            throw new RemoteServiceException("账单结算状态非\"未发放\", 驳回失败");
        }

        List<String> orderList = poolItems.stream().map(PgSettlePoolItem::getOrderId).collect(Collectors.toList());

        // 删除明细
        pgSettlePoolItemService.removeByIds(poolItems.stream().map(PgSettlePoolItem::getId).collect(Collectors.toList()));

        // 清空账单师傅记录
        pgSettlePoolWorkerService.lambdaUpdate()
                .eq(PgSettlePoolWorker::getPoolId, settlePool.getId())
                .remove();

        // 结算单变更未汇总状态
        pgSettleOrderService.lambdaUpdate()
                .set(PgSettleOrder::getLastCancelBy, adminUser.getNickName())
                .set(PgSettleOrder::getLastCancelTime, DateUtil.date())
                .set(PgSettleOrder::getPoolStatus, PoolStatusEnum.NO.getKey())
                .set(PgSettleOrder::getPoolId, "")
                .set(PgSettleOrder::getPoolBy, "")
                .set(PgSettleOrder::getPoolTime, null)
                .in(PgSettleOrder::getId, orderList)
                .eq(PgSettleOrder::getPoolStatus, PoolStatusEnum.YES.getKey())
                .update();

        // 师傅结算费用更新汇总状态
        pgOrderSettleWorkerService.lambdaUpdate()
                .set(PgOrderSettleWorker::getPoolStatus, PoolStatusEnum.NO.getKey())
                .set(PgOrderSettleWorker::getPoolId, "")
                .in(PgOrderSettleWorker::getSettleOrderId, orderList)
                .update();

        // 查出结算单重新计算
        List<PgSettleOrder> settleOrders = pgSettleOrderService.lambdaQuery()
                .eq(PgSettleOrder::getPoolId, settlePool.getId())
                .eq(PgSettleOrder::getPoolStatus, PoolStatusEnum.YES.getKey())
                .list();

        // 重新计算结算账单内容

        if (CollectionUtil.isNotEmpty(settleOrders)) {
            // 按网点师傅执行汇总
            Map<String, List<PgSettleOrder>> workerMap = settleOrders.stream().collect(Collectors.groupingBy(PgSettleOrder::getWorkerId));

            settlePool.setWorkerNum(workerMap.values().size())
                    .setTotalAmount(BigDecimal.ZERO);

            List<PgSettlePoolWorker> workerList = new ArrayList<>();
            for (Map.Entry<String, List<PgSettleOrder>> worker : workerMap.entrySet()) {
                List<PgSettleOrder> workerOrderList = worker.getValue();

                PgSettlePoolWorker poolWorker = new PgSettlePoolWorker();
                poolWorker.setPoolId(settlePool.getId())
                        .setMonth(settlePool.getMonth())
                        .setCompanyWechatId(settlePool.getCompanyWechatId())
                        .setCompanyWechatName(settlePool.getCompanyWechatName())
                        .setWebsitId(settlePool.getWebsitId())
                        .setWebsitName(settlePool.getWebsitName())
                        .setWorkerId(workerOrderList.get(0).getWorkerId())
                        .setWorkerName(workerOrderList.get(0).getWorkerName())
                        .setWorkerMobile(workerOrderList.get(0).getWorkerMobile())
                        .setWorkerIdcard(workerOrderList.get(0).getWorkerIdcard())
                        .setTotalAmount(BigDecimal.ZERO);
                BigDecimal totalAmount = BigDecimal.ZERO;

                for (PgSettleOrder order : workerOrderList) {
                    totalAmount = totalAmount.add(order.getSettleAmount());
                }

                // 师傅结算总金额
                poolWorker.setTotalAmount(totalAmount);
                // 汇总账单结算金额
                settlePool.setTotalAmount(settlePool.getTotalAmount().add(totalAmount));
                workerList.add(poolWorker);
            }
            // 汇总人数
            settlePool.setWorkerNum(workerList.size());
            settlePool.updateById();
            pgSettlePoolWorkerService.saveBatch(workerList);
        } else {
            settlePool.setTotalAmount(BigDecimal.ZERO)
                    .setWorkerNum(0)
                    .updateById();
        }
    }

    public IPage<SettlePoolVO> poolList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, WebsitPurchaseVO.class, adminUser);


        return commonMapper.settlePoolList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getAdminWebsitIds());

    }

    public List<SettlePoolWorkerVO> poolDetailList(String id, String workerName, String mobile, String idcard,
                                                   String orderBaseId, String customerName, String customerMobile,
                                                   String orderSmallType, String settleOrderType) {
        List<SettlePoolWorkerVO> list = commonMapper.poolDetailList(id, workerName, mobile, idcard,
                orderBaseId, customerName, customerMobile, orderSmallType, settleOrderType);
        return list;
    }

    public ExcelData exportPoolDetail(String id) {
        List<SettlePoolWorkerVO> orderList = commonMapper.poolDetailList(id, null, null, null, null, null, null, null, null);
        List<List<Object>> rows = new ArrayList<>();
        String[] titles = new String[] {
                "账单编号", "月份", "商户名称", "网点名称", "工程师信息", "联系电话", "身份证", "结算金额（元）", "发放状态", "汇总人",
                "汇总时间", "发放人", "发放时间", "工单编号", "客户名称", "客户电话", "详细地址", "工单状态", "工单创建时间", "师傅完工时间",
                "工单类型", "品牌", "内部来源", "工单来源", "大类名称", "小类名称", "机型名称", "工单数量", "结算单类型", "安装功率",
                "安装结算标准", "维修质保类型", "维修上门费", "维修费用结算比例", "维修结算费用", "其它费用类型", "其它费用规格", "其它费用单价",
                "奖罚单考核项目", "奖罚单考核类型", "结算数量", "结算金额", "备注"
        };

        Map<String, List<SettlePoolWorkerVO>> workerMap = orderList.stream().collect(Collectors.groupingBy(SettlePoolWorkerVO::getWorkerId));

        for (Map.Entry<String, List<SettlePoolWorkerVO>> entry : workerMap.entrySet()) {
            List<SettlePoolWorkerVO> value = entry.getValue();
            for (int i = 0; i < value.size(); i++) {
                SettlePoolWorkerVO order = value.get(i);
                List<Object> row = new ArrayList<>();
                if (i == 0) {
                    row.add(order.getPoolId());
                    row.add(order.getMonth());
                    row.add(order.getCompanyWechatName());
                    row.add(order.getWebsitName());
                    row.add(order.getWorkerName());
                    row.add(order.getWorkerMobile());
                    row.add(order.getWorkerIdcard());
                    row.add(order.getTotalAmount());
                    if (StringUtils.isNotBlank(order.getStatus())) {
                        row.add(Objects.requireNonNull(BaseEnum.keyToEnum(SettlePoolStatusEnum.class, order.getStatus())).getRemark());
                    } else {
                        row.add("");
                    }
                    row.add(order.getPoolCreateBy());
                    row.add(DateUtil.formatDateTime(order.getPoolCreateTime()));
                    row.add(order.getPoolUpdateBy());
                    row.add(DateUtil.formatDateTime(order.getPoolCreateTime()));
                } else {
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                }
                row.add(order.getOrderBaseId());
                row.add(order.getCustomerName());
                row.add(order.getCustomerMobile());
                row.add(order.getCustomerAddress());
                if (StringUtils.isNotBlank(order.getOrderStatus())) {
                    row.add(Objects.requireNonNull(BaseEnum.keyToEnum(OrderBaseStatusEnum.class, order.getOrderStatus())).getRemark());
                } else {
                    row.add("");
                }
                row.add(Objects.nonNull(order.getOrderCreateTime()) ? DateUtil.formatDateTime(order.getOrderCreateTime()) : "");
                row.add(Objects.nonNull(order.getWorkerEndTime()) ? DateUtil.formatDateTime(order.getWorkerEndTime()) : "");
                row.add(order.getOrderSmallTypeText());
                row.add(order.getBrand());
                row.add(order.getOrderSource());
                row.add(order.getOrderChannel());
                row.add(order.getParentCategoryName());
                row.add(order.getCategoryName());
                row.add(order.getGoodsName());
                row.add(order.getOrderNum());
                if (StringUtils.isNotBlank(order.getSettleOrderType())) {
                    row.add(Objects.requireNonNull(BaseEnum.keyToEnum(SettleNormTypeEnum.class, order.getSettleOrderType())).getRemark());
                } else {
                    row.add("");
                }

                row.add(order.getInstallLabel());
                row.add(order.getInstallNormAmount());
                if (StringUtils.isNotBlank(order.getRepairLabel())) {
                    row.add(Objects.requireNonNull(BaseEnum.keyToEnum(OrderUseTypeEnum.class, order.getRepairLabel())).getRemark());
                } else {
                    row.add("");
                }

                row.add(order.getRepairAmount());
                row.add(order.getRepairRate());
                row.add(order.getRepairSettleAmount());
                row.add(order.getOtherType());
                row.add(order.getOtherLabel());
                row.add(order.getOtherPrice());
                row.add(order.getExamineProject());
                if (StringUtils.isNotBlank(order.getExamineType())) {
                    row.add(Objects.requireNonNull(BaseEnum.keyToEnum(ExamineProjectTypeEnum.class, order.getExamineType())).getRemark());
                } else {
                    row.add("");
                }
                row.add(order.getSettleNum());
                row.add(order.getSettleAmount());
                row.add(order.getRemark());

                rows.add(row);
            }
        }


        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        return excelData;
    }

    /**
     * 完工插入结算费用明细
     * @param orderBase
     * @param orderProductList
     */
    public void insertSettleOrderMethod(PgOrderBase orderBase, List<PgOrderProduct> orderProductList) {
        if (CollectionUtil.isNotEmpty(orderProductList)) {
            List<PgOrderWorker> workers = pgOrderWorkerService.lambdaQuery()
                    .eq(PgOrderWorker::getOrderBaseId, orderBase.getId())
                    .list();

            List<PgOrderSettleWorker> orderWorkerList = new ArrayList<>();

            List<PgOrderSettleNorm> normList = new ArrayList<>();
            for (PgOrderProduct product : orderProductList) {
                PgOrderSettleNorm norm = new PgOrderSettleNorm();
                norm.setId(IdWorker.getIdStr())
                        .setOrderBaseId(orderBase.getId())
                        .setPgOrderProductId(product.getId())
                        .setCompanyWechatId(orderBase.getCompanyWechatId())
                        .setCompanyWechatName(orderBase.getCompanyWechatName())
                        .setWebsitId(orderBase.getWebsitId())
                        .setWebsitName(orderBase.getWebsitName())
                        .setOrderType(orderBase.getOrderType())
                        .setOrderTypeText(orderBase.getOrderTypeText())
                        .setChannelId(orderBase.getOrderChannelId())
                        .setChannelText(orderBase.getOrderChannelText())
                        .setType(orderBase.getOrderSmallType())
                        .setTypeName(orderBase.getOrderSmallTypeText())
                        .setOrderNum(product.getNum())
                        .setSettleNum(product.getNum())
                        .setGoodsId(product.getProductId())
                        .setGoodsName(product.getProductName())
                        .setMainId(product.getMainId())
                        .setMainName(product.getMainName())
                        .setSmallId(product.getSmallId())
                        .setSmallName(product.getSmallName())
                        .setOrderChannelId(orderBase.getOrderChannelId())
                        .setOrderChannelText(orderBase.getOrderChannelText())
//                        .setParentCategoryId(product.getMainId())
//                        .setParentCategoryName(product.getMainName())
//                        .setCategoryId(product.getSmallId())
//                        .setCategoryName(product.getSmallName())
                        .setBrandId(product.getBrandId())
                        .setBrand(product.getBrandName())
                        .setSettleNormType(orderBase.getOrderType());

                PgOrderSettleNorm otherNorm = new PgOrderSettleNorm();
                otherNorm.setId(IdWorker.getIdStr())
                        .setOrderBaseId(orderBase.getId())
                        .setPgOrderProductId(product.getId())
                        .setCompanyWechatId(orderBase.getCompanyWechatId())
                        .setCompanyWechatName(orderBase.getCompanyWechatName())
                        .setWebsitId(orderBase.getWebsitId())
                        .setWebsitName(orderBase.getWebsitName())
                        .setOrderNum(product.getNum())
                        .setSettleNum(product.getNum())
                        .setGoodsId(product.getProductId())
                        .setGoodsName(product.getProductName())
                        .setMainId(product.getMainId())
                        .setMainName(product.getMainName())
                        .setSmallId(product.getSmallId())
                        .setSmallName(product.getSmallName())
                        .setBrandId(product.getBrandId())
                        .setBrand(product.getBrandName())
                        .setSettleNormType(SettleNormTypeEnum.OTHER.getKey());

                normList.add(norm);
                normList.add(otherNorm);

                for (PgOrderWorker worker : workers) {
                    PgOrderSettleWorker settleWorker = new PgOrderSettleWorker();
                    settleWorker.setId(IdWorker.getIdStr())
                            .setOrderBaseId(orderBase.getId())
                            .setOrderSettleNormId(norm.getId())
                            .setWorkerId(worker.getWorkerId())
                            .setWorkerName(worker.getWorkerName())
                            .setWorkerMobile(worker.getWorkerMobile())
                            .setWorkerIdcard(worker.getWorkerIdcard())
                            .setSettleNormType(norm.getSettleNormType());

                    PgOrderSettleWorker settleOtherWorker = new PgOrderSettleWorker();
                    settleOtherWorker.setId(IdWorker.getIdStr())
                            .setOrderBaseId(orderBase.getId())
                            .setOrderSettleNormId(otherNorm.getId())
                            .setWorkerId(worker.getWorkerId())
                            .setWorkerName(worker.getWorkerName())
                            .setWorkerMobile(worker.getWorkerMobile())
                            .setWorkerIdcard(worker.getWorkerIdcard())
                            .setSettleNormType(otherNorm.getSettleNormType());

                    orderWorkerList.add(settleWorker);
                    orderWorkerList.add(settleOtherWorker);
                }
            }

            pgOrderSettleNormService.saveBatch(normList);
            pgOrderSettleWorkerService.saveBatch(orderWorkerList);
        }
    }

    /**
     * 已完工待结算时驳回工单清空已生成结算费用
     * @param orderBaseId
     */
    public void clearSettleOrderFee(String orderBaseId) {
        pgOrderSettleNormService.lambdaUpdate()
                .eq(PgOrderSettleNorm::getOrderBaseId, orderBaseId)
                .remove();
        pgOrderSettleWorkerService.lambdaUpdate()
                .eq(PgOrderSettleWorker::getOrderBaseId, orderBaseId)
                .remove();
    }

    @Transactional
    public void ywg(List<String> ids) {
        List<PgOrderBase> orderBases = pgOrderBaseService.lambdaQuery()
                .in(PgOrderBase::getId, ids)
                .eq(PgOrderBase::getOrderStatus, OrderBaseStatusEnum.YWG.getKey())
                .list();

        if (CollectionUtil.isNotEmpty(orderBases)) {
            for (PgOrderBase orderBase : orderBases) {
                List<PgOrderProduct> orderProducts = pgOrderProductService.lambdaQuery()
                        .eq(PgOrderProduct::getOrderBaseId, orderBase.getId())
                        .list();

                pgOrderSettleNormService.lambdaUpdate()
                        .eq(PgOrderSettleNorm::getOrderBaseId, orderBase.getId())
                        .remove();
                pgOrderSettleWorkerService.lambdaUpdate()
                        .eq(PgOrderSettleWorker::getOrderBaseId, orderBase.getId())
                        .remove();
                this.insertSettleOrderMethod(orderBase, orderProducts);
            }
        }
    }
}
