package com.gree.mall.manager.logic.material.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
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.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.stock.WebsitStockDTO;
import com.gree.mall.manager.bean.material.stock.WorkerStockDTO;
import com.gree.mall.manager.bean.material.worker.*;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.enums.IsEnum;
import com.gree.mall.manager.enums.base.BaseEnum;
import com.gree.mall.manager.enums.material.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.material.stock.MaterialGoodsStockLogic;
import com.gree.mall.manager.logic.material.worker.OldRefundManageInnerLogic;
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 io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class WorkerOldRefundManageLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final SysDictCompanyService sysDictCompanyService;
    private final WebsitPartsOldRefundManageService websitPartsOldRefundManageService;
    private final WebsitPartsSettlementRecordService websitPartsSettlementRecordService;
    private final OldRefundManageInnerLogic oldRefundManageInnerLogic;
    private final WebsitPartsOldRefundManageItemService websitPartsOldRefundManageItemService;
    private final WebsitPartsOldRefundManageRecordService websitPartsOldRefundManageRecordService;
    private final WebsitPartsRefundRecordService websitPartsRefundRecordService;
    private final WorkerStockAccService workerStockAccService;
    private final MaterialGoodsStockLogic materialGoodsStockLogic;
    private final StorageService storageService;
    private final WorkerOrderItemService workerOrderItemService;

    public IPage<OldRefundManageVO> pageList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, OldRefundManageVO.class, adminUser);

        return materialMapper.oldRefundManagePage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public OldRefundManageBean detail(String applyNo) {
        WebsitPartsOldRefundManage partsOldRefundManage = websitPartsOldRefundManageService.getById(applyNo);
        if (Objects.isNull(partsOldRefundManage)) {
            throw new RemoteServiceException("单据不存在");
        }
        List<WebsitPartsOldRefundManageItem> partsOldRefundManageItems = websitPartsOldRefundManageItemService.lambdaQuery()
                .eq(WebsitPartsOldRefundManageItem::getApplyNo, applyNo)
                .list();

        OldRefundManageBean oldRefundManageBean = new OldRefundManageBean();
        BeanUtils.copyProperties(partsOldRefundManage, oldRefundManageBean);


        List<OldRefundManageItemBean> oldRefundManageItemBeanList = BeanUtil.copyToList(partsOldRefundManageItems, OldRefundManageItemBean.class);

        // 查询执行记录
        List<WebsitPartsOldRefundManageRecord> partsOldRefundManageRecords = websitPartsOldRefundManageRecordService.lambdaQuery()
                .eq(WebsitPartsOldRefundManageRecord::getApplyNo, partsOldRefundManage.getApplyNo())
                .list();

        List<OldRefundManageRecordBean> oldRefundManageRecordBeans = BeanUtil.copyToList(partsOldRefundManageRecords, OldRefundManageRecordBean.class);

        oldRefundManageBean.setPartsOldRefundManageRecordList(oldRefundManageRecordBeans);
        oldRefundManageBean.setOldRefundManageItemBeanList(oldRefundManageItemBeanList);

        return oldRefundManageBean;
    }

    @Transactional
    public void refund(String applyNo, String flag, String examineRemark) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPartsOldRefundManage partsOldRefundManage = websitPartsOldRefundManageService.getById(applyNo);
        if (Objects.isNull(partsOldRefundManage)) {
            throw new RemoteServiceException("申请单号不存在");
        }
        if (PartsRepairFlagEnum.OUTSIDE.getKey().equals(partsOldRefundManage.getRepairFlag())) {
            throw new RemoteServiceException("申请单号不存在");
        }
        // 保内 flag=已返还
        if (PartsRepairFlagEnum.INNER.getKey().equals(partsOldRefundManage.getRepairFlag())) {
            if (!partsOldRefundManage.getFlag().equals(PartsOrderFlagEnum.AGREE.getKey())) {
                throw new RemoteServiceException(applyNo + "单据状态："
                        + BaseEnum.keyToValue(PartsOrderFlagEnum.class, partsOldRefundManage.getFlag()) + "，失败");
            }
            if (!(PartsOrderFlagEnum.REFUNDED.getKey() + "|" + PartsOrderFlagEnum.NOTREFUND.getKey()).contains(flag)) {
                throw new RemoteServiceException("状态不正确");
            }
        }

        String refType = PartsRefTypeEnum.OLD_REFUND.getRemark();

        DateTime curDate = DateUtil.date();
        partsOldRefundManage.setExamineRemark(examineRemark)
                .setFlag(flag)
                .setExamineBy(adminUser.getNickName())
                .setExamineTime(curDate)
                .setRefundedBy(adminUser.getNickName())
                .setRefundedTime(curDate);

        // 更新
        partsOldRefundManage.updateById();

        List<WebsitPartsOldRefundManageItem> partsOldRefundManageItems = websitPartsOldRefundManageItemService.lambdaQuery()
                .eq(WebsitPartsOldRefundManageItem::getApplyNo, partsOldRefundManage.getApplyNo())
                .list();

        // 已返还的处理
        if (flag.equals(PartsOrderFlagEnum.REFUNDED.getKey())) {
            // 减师傅临占旧件库存
            List<WorkerStockDTO> workerStockDTOList = oldRefundManageInnerLogic.createWorkerStockDTO(partsOldRefundManage, partsOldRefundManageItems,
                    refType, PartsAttrEnum.TEMP_OLD.getKey(), null, flag);
            materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);

            // 网点旧件库存增加
            List<WebsitStockDTO> shopStockDTOList = this.createWebsitStockDTO(partsOldRefundManage, partsOldRefundManageItems);
            materialGoodsStockLogic.handleWebsitStock(shopStockDTOList);

            List<WebsitPartsOldRefundManageRecord> partsNewRefundManageRecords = websitPartsOldRefundManageRecordService.lambdaQuery()
                    .eq(WebsitPartsOldRefundManageRecord::getApplyNo, partsOldRefundManage.getApplyNo())
                    .list();
            List<WebsitPartsRefundRecord> partsRefundRecordList = this.createRefundRecord(partsOldRefundManage, partsNewRefundManageRecords, refType);
            if (CollectionUtil.isNotEmpty(partsRefundRecordList))
                websitPartsRefundRecordService.saveBatch(partsRefundRecordList);
        } else {
            // 加师傅旧件库存
            List<WorkerStockDTO> workerStockDTOList = oldRefundManageInnerLogic.createWorkerStockDTO(partsOldRefundManage, partsOldRefundManageItems,
                    refType, PartsAttrEnum.TEMP_OLD.getKey(), PartsAttrEnum.OLD.getKey(), flag);
            materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);
        }
    }

    private List<WebsitPartsRefundRecord> createRefundRecord(WebsitPartsOldRefundManage partsOldRefundManage, List<WebsitPartsOldRefundManageRecord> partsNewRefundManageRecords, String refType) {
        List<WebsitPartsRefundRecord> partsRefundRecordList = new ArrayList<>();
        for (WebsitPartsOldRefundManageRecord partsOldRefundManageRecord : partsNewRefundManageRecords) {
            if (Objects.isNull(partsOldRefundManageRecord.getRefundAmountMode())
                    || partsOldRefundManageRecord.getRefundAmountMode().equals(PayTypeEnum.CASH.toString())) {
                continue;
            }
            WebsitPartsRefundRecord partsRefundRecord = new WebsitPartsRefundRecord();
            partsRefundRecord.setRefundNo(IdWorker.getIdStr())
                    .setCompanyWechatId(partsOldRefundManage.getCompanyWechatId())
                    .setCompanyWechatName(partsOldRefundManage.getCompanyWechatName())
                    .setRecordId(partsOldRefundManageRecord.getId())
                    .setWebsitId(partsOldRefundManage.getReceiveWebsitId())
                    .setWebsitName(partsOldRefundManage.getReceiveWebsitName())
                    .setPartsWebsitId(partsOldRefundManage.getReceivePartsWebsitId())
                    .setIdentity(partsOldRefundManage.getIdentity())
                    .setWorkerId(partsOldRefundManage.getWorkerId())
                    .setWorkerName(partsOldRefundManage.getWorkerName())
                    .setSalesId(partsOldRefundManageRecord.getSalesId())
                    .setSalesItemId(partsOldRefundManageRecord.getSalesItemId())
                    .setRef(partsOldRefundManage.getApplyNo())
                    .setRefType(refType)
                    .setPartsNumber(partsOldRefundManageRecord.getPartsNumber())
                    .setPartsName(partsOldRefundManageRecord.getPartsName())
                    .setRefundAmount(partsOldRefundManageRecord.getRefundAmount())
                    .setRefundState(PartsRefundStateEnum.WAIT.getKey())
                    .setIsExec(IsEnum.N.getValue())
                    .setCreateTime(DateUtil.date());
            partsRefundRecordList.add(partsRefundRecord);
        }
        return partsRefundRecordList;
    }

    /**
     * 保外新件转销售审核
     * @param applyNo
     * @param isDisc
     * @param examineRemark
     */
    @Transactional
    public void examine(String applyNo, Boolean isDisc, String examineRemark) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPartsOldRefundManage partsOldRefundManage = websitPartsOldRefundManageService.getById(applyNo);
        if (Objects.isNull(partsOldRefundManage)) {
            throw new RemoteServiceException("申请单号不存在");
        }
        if (PartsRepairFlagEnum.INNER.toString().equals(partsOldRefundManage.getRepairFlag())) {
            throw new RemoteServiceException("申请单号不存在");
        }

        String refType = PartsRefTypeEnum.OUTSIDE_TO_SALES.getRemark();
        String flag = isDisc ? PartsOrderFlagEnum.AGREE.getKey() : PartsOrderFlagEnum.WAIT_REVIEW.getKey();

        DateTime curDate = DateUtil.date();
        partsOldRefundManage.setExamineRemark(examineRemark)
                .setIsDisc(isDisc)
                .setFlag(flag)
                .setExamineBy(adminUser.getNickName())
                .setExamineTime(curDate);

        // 更新
        partsOldRefundManage.updateById();

        List<WebsitPartsOldRefundManageItem> partsOldRefundManageItems = websitPartsOldRefundManageItemService.lambdaQuery()
                .eq(WebsitPartsOldRefundManageItem::getApplyNo, partsOldRefundManage.getApplyNo())
                .list();

        // 已审批的处理
        if (flag.equals(PartsOrderFlagEnum.AGREE.getKey())) {
            // 减师傅临占旧件库存
            List<WorkerStockDTO> workerStockDTOList = oldRefundManageInnerLogic.createWorkerStockDTO(partsOldRefundManage, partsOldRefundManageItems,
                    refType, PartsAttrEnum.TEMP_OLD.getKey(), null, flag);
            materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);

            List<WebsitPartsOldRefundManageRecord> partsNewRefundManageRecords = websitPartsOldRefundManageRecordService.lambdaQuery()
                    .eq(WebsitPartsOldRefundManageRecord::getApplyNo, partsOldRefundManage.getApplyNo())
                    .list();
            List<WebsitPartsRefundRecord> partsRefundRecordList = this.createRefundRecord(partsOldRefundManage, partsNewRefundManageRecords, refType);
            if (CollectionUtil.isNotEmpty(partsRefundRecordList))
                websitPartsRefundRecordService.saveBatch(partsRefundRecordList);
        }
    }

    /**
     * 保外新件转销售复核
     * @param applyNo
     * @param reviewResult
     * @param reviewRemark
     */
    @Transactional(rollbackFor = Exception.class)
    public void review(String applyNo, Boolean reviewResult, String reviewRemark) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPartsOldRefundManage partsOldRefundManage = websitPartsOldRefundManageService.getById(applyNo);
        if (Objects.isNull(partsOldRefundManage)) {
            throw new RemoteServiceException("申请单号不存在");
        }
        if (PartsRepairFlagEnum.INNER.getKey().equals(partsOldRefundManage.getRepairFlag())) {
            throw new RemoteServiceException("申请单号不存在");
        }

        String refType = PartsRefTypeEnum.OUTSIDE_TO_SALES.getRemark();
        String flag = PartsOrderFlagEnum.REVIEWED.getKey();

        DateTime curDate = DateUtil.date();
        partsOldRefundManage.setReviewRemark(reviewRemark)
                .setReviewResult(reviewResult)
                .setFlag(flag)
                .setReviewBy(adminUser.getNickName())
                .setReviewTime(curDate);

        // 更新
        partsOldRefundManage.updateById();

        List<WebsitPartsOldRefundManageItem> partsOldRefundManageItems = websitPartsOldRefundManageItemService.lambdaQuery()
                .eq(WebsitPartsOldRefundManageItem::getApplyNo, partsOldRefundManage.getApplyNo())
                .list();

        // 已复核的处理
        // 减师傅临占旧件库存
        List<WorkerStockDTO> workerStockDTOList = oldRefundManageInnerLogic.createWorkerStockDTO(partsOldRefundManage, partsOldRefundManageItems,
                refType, PartsAttrEnum.TEMP_OLD.getKey(), null, flag);

        materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);

        if (reviewResult) {
            List<WebsitPartsOldRefundManageRecord> partsNewRefundManageRecords = websitPartsOldRefundManageRecordService.lambdaQuery()
                    .eq(WebsitPartsOldRefundManageRecord::getApplyNo, partsOldRefundManage.getApplyNo())
                    .list();
            List<WebsitPartsRefundRecord> partsRefundRecordList = this.createRefundRecord(partsOldRefundManage, partsNewRefundManageRecords, refType);
            if (CollectionUtil.isNotEmpty(partsRefundRecordList))
                websitPartsRefundRecordService.saveBatch(partsRefundRecordList);
        }
    }

    /**
     * 保内结算状态导入
     * @param inputStream
     * @return
     * @throws RemoteServiceException
     */
    public String importInnerSettlement(InputStream inputStream) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //读取excel数据
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("序号", "no");
        reader.addHeaderAlias("派工序号", "pgId");
        reader.addHeaderAlias("自编号码", "workNumber");
        reader.addHeaderAlias("工单状态", "workState");
        reader.addHeaderAlias("新结算单位号", "newSettlementUnitNo");
        reader.addHeaderAlias("旧结算单位号", "oldSettlementUnitNo");
        reader.addHeaderAlias("结算单位名", "settlementUnitName");
        reader.addHeaderAlias("维修类型", "repairType");
        reader.addHeaderAlias("内外机", "outInnerMachine");
        reader.addHeaderAlias("机器条码", "outMachineBarcode");
        reader.addHeaderAlias("外机型", "outMachineType");
        reader.addHeaderAlias("外机型描述", "outMachineDescr");
        reader.addHeaderAlias("内机条码", "innerMachineBarcode");
        reader.addHeaderAlias("内机型", "innerMachineType");
        reader.addHeaderAlias("内机型描述", "innerMachineDescr");
        reader.addHeaderAlias("用户姓名", "customerName");
        reader.addHeaderAlias("区号", "areaNo");
        reader.addHeaderAlias("移动电话", "mobile");
        reader.addHeaderAlias("电话号码", "tel");
        reader.addHeaderAlias("省份", "province");
        reader.addHeaderAlias("市县", "city");
        reader.addHeaderAlias("区县", "area");
        reader.addHeaderAlias("用户地址", "customerAddress");
        reader.addHeaderAlias("GPS定位", "GPSPosition");
        reader.addHeaderAlias("邮政编码", "mailNumber");
        reader.addHeaderAlias("销售单位号", "salesUnitNo");
        reader.addHeaderAlias("销售单位", "salesUnitName");
        reader.addHeaderAlias("发票编号", "invoiceNumber");
        reader.addHeaderAlias("购买日期", "buyDate");
        reader.addHeaderAlias("安装日期", "installDate");
        reader.addHeaderAlias("报修日期", "applyDate");
        reader.addHeaderAlias("修复日期", "repairDate");
        reader.addHeaderAlias("维修工ID", "repairWorkerId");
        reader.addHeaderAlias("维修工姓名", "repairWorkerName");
        reader.addHeaderAlias("维修师傅", "repairWorker");
        reader.addHeaderAlias("维修工电话", "repairMobile");
        reader.addHeaderAlias("维修费用", "repairAmount");
        reader.addHeaderAlias("交通费", "trafficAmount");
        reader.addHeaderAlias("住宿费用", "hotelAmount");
        reader.addHeaderAlias("吊装费用", "hoistAmount");
        reader.addHeaderAlias("其他费用", "otherAmount");
        reader.addHeaderAlias("总费用", "totalAmount");
        reader.addHeaderAlias("结算单批号", "settlementBatchNo");
        reader.addHeaderAlias("安装网点号", "installWebsiteNumber");
        reader.addHeaderAlias("安装网点名", "installWebsiteName");
        reader.addHeaderAlias("新维修单位号", "newRepairUnitNo");
        reader.addHeaderAlias("旧维修单位号", "oldRepairUnitNo");
        reader.addHeaderAlias("维修单位名", "repairUnitName");
        reader.addHeaderAlias("故障现象", "bugDescr");
        reader.addHeaderAlias("故障分析", "bugReason");
        reader.addHeaderAlias("维修内容", "repairRemark");
        reader.addHeaderAlias("备注", "remark");
        reader.addHeaderAlias("转结算时间", "settlementTime");

        List<WebsitPartsSettlementRecord> partsSettlementRecords = reader.readAll(WebsitPartsSettlementRecord.class);
        DateTime curDate = DateUtil.date();
        if (CollectionUtil.isEmpty(partsSettlementRecords)) {
            throw new RemoteServiceException("导入数据不能空");
        }
        for (WebsitPartsSettlementRecord settlementRecord : partsSettlementRecords) {
            settlementRecord.setCompanyWechatId(adminUser.getCompanyWechatId())
                    .setCompanyWechatName(adminUser.getCompanyName());
            if (StringUtils.isBlank(settlementRecord.getPgId()) || StringUtils.isBlank(settlementRecord.getWorkState()) ) {
                throw new RemoteServiceException("导入的序号" + settlementRecord.getNo() + "数据异常，导入中止");
            }
            settlementRecord.setImportBy(adminUser.getNickName())
                    .setImportTime(curDate);
        }
        List<SysDictCompany> sysDictCompanyList = sysDictCompanyService.lambdaQuery()
                .eq(SysDictCompany::getDictType, "PARTS_INNER_SETTLEMENT_WORK_STATE")
                .list();
        if (CollectionUtil.isEmpty(sysDictCompanyList))
            throw new RemoteServiceException("未配置保内结算工单状态");

        List<String> workStateList = sysDictCompanyList.stream()
                .map(SysDictCompany::getDictValue)
                .collect(Collectors.toList());

        StringBuilder msg = new StringBuilder();
        String repairFlag = PartsRepairFlagEnum.INNER.getKey();
        Map<String, WebsitPartsSettlementRecord> settlementRecordMap = partsSettlementRecords.stream()
                .collect(Collectors.toMap(v -> v.getPgId().trim(), Function.identity(), (key1, key2) -> key2));
        // 过滤出要结算的派工序号 "待总部审批,待总部日审,待退旧件,已转结算待汇总,已汇总"
        List<String> pgIds = partsSettlementRecords.stream()
                .filter(v -> workStateList.contains(v.getWorkState().trim()))
                .map(v -> v.getPgId().trim())
                .collect(Collectors.toList());
        // 截取指定数量后分段查询
        List<List<String>> splitList = CollUtil.split(pgIds, 500);
        List<WebsitPartsOldRefundManage> updateList = new ArrayList<>();
        for (List<String> pgIdList : splitList) {
            final List<WebsitPartsOldRefundManage> partsOldRefundManageList = websitPartsOldRefundManageService.lambdaQuery()
                    .eq(WebsitPartsOldRefundManage::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .in(WebsitPartsOldRefundManage::getPgId, pgIdList)
                    .eq(WebsitPartsOldRefundManage::getRepairFlag, repairFlag)
                    .eq(WebsitPartsOldRefundManage::getSettlementState, false)
                    .list();
            if(CollectionUtil.isNotEmpty(partsOldRefundManageList)) {
                for (WebsitPartsOldRefundManage partsOldRefundManage : partsOldRefundManageList) {
                    WebsitPartsSettlementRecord settlementRecord = settlementRecordMap.get(partsOldRefundManage.getPgId());
                    if (Objects.nonNull(settlementRecord)) {
                        oldRefundManageInnerLogic.submit(partsOldRefundManage);
                        updateList.add(partsOldRefundManage);
                    }
                }
            }
            if(CollectionUtil.isNotEmpty(updateList)) {
                msg.append("成功导入处理 ").append(updateList.size()).append(" 条;");
            }
        }

        for (WebsitPartsSettlementRecord partsSettlementRecord : partsSettlementRecords) {
            partsSettlementRecord.setPgId(partsSettlementRecord.getPgId().trim());
        }
        websitPartsSettlementRecordService.saveOrUpdateBatch(partsSettlementRecords);
        return msg.toString();
    }

    public String importOutsideSettlement(List<Object> objects) throws Exception {
        if(Collections.isEmpty(objects)) {
            throw new RemoteServiceException("导入数据不能为空");
        }
        AdminUserCom adminUser = commonLogic.getAdminUser();
        StringBuilder msg = new StringBuilder();
        LinkedHashSet<String> pgIds = new LinkedHashSet<>();
        for (Object data : objects) {
            List<String> row = (List<String>) data;
            pgIds.add(row.get(0));
        }

        String repairFlag = PartsRepairFlagEnum.OUTSIDE.toString();
        // 截取指定数量后分段查询
        List<List<String>> splitList = CollUtil.split(pgIds, 500);
        for (List<String> pgIdList : splitList) {
            final List<WebsitPartsOldRefundManage> partsOldRefundManageList = websitPartsOldRefundManageService.lambdaQuery()
                    .eq(WebsitPartsOldRefundManage::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .in(WebsitPartsOldRefundManage::getPgId, pgIdList)
                    .eq(WebsitPartsOldRefundManage::getRepairFlag, repairFlag)
                    .list();
            if(!Collections.isEmpty(partsOldRefundManageList)) {
                final Map<String, List<WebsitPartsOldRefundManage>> partsOldRefundManageMap =
                        Collections.isEmpty(partsOldRefundManageList) ? null :
                                partsOldRefundManageList.stream().collect(Collectors.groupingBy(WebsitPartsOldRefundManage::getPgId));
                List<WebsitPartsOldRefundManage> updateList = new ArrayList<>();
//                List<String> errorList = new ArrayList<>();
                for (Object object : objects) {
                    List<String> row = (List<String>) object;
                    if (Objects.nonNull(partsOldRefundManageMap)
                            && partsOldRefundManageMap.containsKey(row.get(0))
                            && CollectionUtil.isNotEmpty(partsOldRefundManageMap.get(row.get(0)))) {
                        List<WebsitPartsOldRefundManage> oldRefundList = partsOldRefundManageMap.get(row.get(0));
                        for (WebsitPartsOldRefundManage oldRefund : oldRefundList) {
                            if (Objects.isNull(oldRefund.getSettlementState())
                                    || !oldRefund.getSettlementState()) {
                                oldRefundManageInnerLogic.submit(oldRefund);
                                updateList.add(oldRefund);
                            }
//                            else {
//                                errorList.add(row.get(0) + "已结算，无需重复导入");
//                            }
                        }
                    }
//                    else {
//                        errorList.add("没有找到该工单派工id" + row.get(0));
//                    }
                }
                if(!Collections.isEmpty(updateList)) {
                    msg.append("成功导入处理 "+updateList.size()+" 条;");
                }
//                if(!Collections.isEmpty(errorList)) {
//                    msg.append("导入失败"+errorList.size()+"条, 异常信息: "+JSONObject.toJSONString(errorList));
//                }
            }
        }

        return msg.toString();
    }


    @Transactional
    public void transferFlag(String applyNo) {
        WebsitPartsOldRefundManage refundManage = websitPartsOldRefundManageService.getById(applyNo);
        if (!refundManage.getFlag().equals(PartsOrderFlagEnum.SAVE.getKey())) {
            throw new RemoteServiceException("非保存状态，转换失败");
        }

        final List<WebsitPartsOldRefundManageItem> items = websitPartsOldRefundManageItemService.lambdaQuery()
                .eq(WebsitPartsOldRefundManageItem::getApplyNo, applyNo)
                .list();

        List<WebsitPartsOldRefundManageRecord> records = websitPartsOldRefundManageRecordService.lambdaQuery()
                .eq(WebsitPartsOldRefundManageRecord::getApplyNo, applyNo)
                .list();
        // 取反
        String refType = PartsRepairFlagEnum.INNER.getKey().equals(refundManage.getRepairFlag()) ?
                PartsRefTypeEnum.OUTSIDE_TO_SALES.getRemark() :
                PartsRefTypeEnum.OLD_REFUND.getRemark();

        // 取反
        String repairFlag = PartsRepairFlagEnum.INNER.getKey().equals(refundManage.getRepairFlag()) ?
                PartsRepairFlagEnum.OUTSIDE.getKey() :
                PartsRepairFlagEnum.INNER.getKey();

        workerStockAccService.lambdaUpdate()
                .set(WorkerStockAcc::getRefType, refType)
                .eq(WorkerStockAcc::getRef, applyNo)
                .eq(WorkerStockAcc::getCompanyWechatId, refundManage.getCompanyWechatId())
                .in(WorkerStockAcc::getPartsAttr, PartsAttrEnum.NEW.getKey(), PartsAttrEnum.OLD.getKey())
                .update();

        PartsRefundRecordDTO dto = new PartsRefundRecordDTO();

        BigDecimal totalRefundAmount = BigDecimal.ZERO;

        for (WebsitPartsOldRefundManageRecord record : records) {
            BigDecimal amount = repairFlag.equals(PartsRepairFlagEnum.INNER.toString()) ?
                    record.getSalesPrice().multiply(record.getQty()) :
                    dto.computeDiffAmount(record.getSalesPrice(), record.getSecondPrice(), record.getQty());
            websitPartsOldRefundManageRecordService.lambdaUpdate()
                    .set(WebsitPartsOldRefundManageRecord::getRefundAmount, amount)
                    .set(WebsitPartsOldRefundManageRecord::getRepairFlag, repairFlag)
                    .eq(WebsitPartsOldRefundManageRecord::getId, record.getId())
                    .update();
            totalRefundAmount = totalRefundAmount.add(amount);
        }

        websitPartsOldRefundManageService.lambdaUpdate()
                .set(WebsitPartsOldRefundManage::getRepairFlag, repairFlag)
                .set(WebsitPartsOldRefundManage::getRefundAmount, totalRefundAmount)
                .eq(WebsitPartsOldRefundManage::getApplyNo, applyNo)
                .update();

        workerOrderItemService.lambdaUpdate()
                .set(WorkerOrderItem::getRepairFlag, repairFlag)
                .in(WorkerOrderItem::getId, items.stream()
                        .map(WebsitPartsOldRefundManageItem::getWorkerOrderItemId)
                        .collect(Collectors.toList()))
                .update();

    }

    private List<WebsitStockDTO> createWebsitStockDTO(WebsitPartsOldRefundManage partsOldRefundManage, List<WebsitPartsOldRefundManageItem> partsOldRefundManageItems) {
        final Storage storage = storageService.lambdaQuery()
                .eq(Storage::getCompanyWechatId, partsOldRefundManage.getCompanyWechatId())
                .eq(Storage::getWebsitId, partsOldRefundManage.getReceiveWebsitId())
                .eq(Storage::getIsDefault, true)
                .one();
        List<WebsitStockDTO> shopStockDTOList = new ArrayList<>();
        for (WebsitPartsOldRefundManageItem partsOldRefundManageItem : partsOldRefundManageItems) {
            WebsitStockDTO sendShopStockDTO = new WebsitStockDTO();
            sendShopStockDTO.setCompanyWechatId(partsOldRefundManage.getCompanyWechatId());
            sendShopStockDTO.setCompanyWechatName(partsOldRefundManage.getCompanyWechatName());
            sendShopStockDTO.setWebsitId(partsOldRefundManage.getReceiveWebsitId());
            sendShopStockDTO.setWebsitName(partsOldRefundManage.getReceiveWebsitName());
            sendShopStockDTO.setSdate(partsOldRefundManage.getRefundedTime());
            sendShopStockDTO.setPartsWebsitId(partsOldRefundManage.getReceivePartsWebsitId());
            sendShopStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
            sendShopStockDTO.setGoodsId(partsOldRefundManageItem.getNewPartsNumber());
            sendShopStockDTO.setGoodsName(partsOldRefundManageItem.getNewPartsName());
            sendShopStockDTO.setPrice(BigDecimal.ZERO);
            sendShopStockDTO.setMaterialGroupName(partsOldRefundManageItem.getNewMaterialGroupName());
            sendShopStockDTO.setGoodsStockUnit(partsOldRefundManageItem.getNewUnitName());
            sendShopStockDTO.setVoucherNo(partsOldRefundManage.getApplyNo());
            sendShopStockDTO.setApplyNo(partsOldRefundManage.getApplyNo());
            sendShopStockDTO.setRef(partsOldRefundManage.getApplyNo());
            sendShopStockDTO.setRefType(PartsRefTypeEnum.OLD_REFUND.getRemark());
            sendShopStockDTO.setPartsAttr(PartsAttrEnum.OLD.getKey());
            sendShopStockDTO.setChangeQty(partsOldRefundManageItem.getQty());
            sendShopStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
            sendShopStockDTO.setRemark(partsOldRefundManageItem.getRemark());
            sendShopStockDTO.setOperateBy(partsOldRefundManage.getRefundedBy());
            sendShopStockDTO.setOperateTime(partsOldRefundManage.getRefundedTime());
            sendShopStockDTO.setStorageId(storage.getStorageId());
            shopStockDTOList.add(sendShopStockDTO);
        }
        return shopStockDTOList;
    }
}
