package com.sifang.modules.changes.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.dao.CrmMaterialInformationChangeApplyDao;
import com.sifang.modules.changes.dao.CrmMaterialInformationChangeApplyDetailDao;
import com.sifang.modules.changes.dao.CustomerEntryChangeRecordDao;
import com.sifang.modules.changes.entity.CrmMaterialInformationChangeApply;
import com.sifang.modules.changes.entity.CrmMaterialInformationChangeApplyDetail;
import com.sifang.modules.changes.vo.AnyProductMaterialChangeVo;
import com.sifang.modules.changes.vo.MaterialAuditVo;
import com.sifang.modules.changes.vo.MaterialInfoVo;
import com.sifang.modules.changes.vo.MaterialInformationChangeVo;
import com.sifang.modules.customer.Service.CustomerEntryMsgService;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.Service.GuangFaManagemnetService;
import com.sifang.modules.customer.Service.YueXiuProjectOperatingService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.CrmCustomerEntryProjectDao;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationDao;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CrmCustomerIncomingApplication;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.factory.BrandFactInfo;
import com.sifang.modules.flowable.constants.ItemConstants;
import com.sifang.modules.flowable.dao.ItemManageDao;
import com.sifang.modules.flowable.dao.ItemTaskDetailDao;
import com.sifang.modules.flowable.entity.ItemManage;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.partner.service.GuangfaOperatingService;
import com.sifang.modules.sunshine.SystemSetting.dao.PlanMaterialEntryDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlanMaterialEntry;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectInfoSettingService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.entity.CrmSupplyMaterialType;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyBarcodeDao;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyBarcode;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.taskdispatch.dao.CrmReviewDispatchDao;
import com.sifang.modules.taskdispatch.service.CrmPriorReviewSettingService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CrmMaterialInformationChangeApplyService extends BaseService {

    @Autowired
    private CrmMaterialInformationChangeApplyDao applyDao;
    @Autowired
    private CustomerEntryDao customerEntryDao;
    @Autowired
    private CrmMaterialInformationChangeApplyDetailDao detailDao;
    @Autowired
    private CrmSupplyBarcodeDao barcodeDao;
    @Autowired
    private PlanMaterialEntryDao planMaterialEntryDao;
    @Autowired
    private CustomerEntryService customerEntryService;
    @Autowired
    private ProjectInfoSettingService projectService;
    @Autowired
    private CustomerEntryMsgService entryMsgService;

    @Autowired
    private ItemManageDao itemManageDao;
    @Autowired
    private CrmReviewDispatchDao reviewDispatchDao;

    @Autowired
    private ItemTaskDetailDao itemTaskDetailDao;

    @Autowired
    private GuangFaManagemnetService guangFaManagemnetService;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    GuangfaOperatingService guangfaOperatingService;

    @Autowired
    private YueXiuProjectOperatingService yueXiuProjectOperatingService;

    @Autowired
    private CustomerEntryChangeRecordDao customerEntryChangeRecordDao;

    @Autowired
    private CrmCustomerEntryProjectDao customerEntryProjectDao;

    @Autowired
    private CrmPriorReviewSettingService crmPriorReviewSettingService;
    public CrmMaterialInformationChangeApply selectById(String id){
        return applyDao.get(id);
    }

    /**
     * 获取列表数据
     */
    public String getPageData(LayuiPage page, Map<String, String> map, Operator operator) {
        logger.info("getMaterialInformationChangeApplyPageData, map={}", map);
        page.setData(applyDao.findPageData(page, map, operator));
        page.setCount(applyDao.findPageCount(map, operator));
        return page.renderJson();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result addMaterialInformationChange(MaterialInformationChangeVo materialVo) {
        // 校验参数
        // 1.获取电站信息
        String entryId = materialVo.getEntryId();
        if (StringUtil.isBlank(entryId)) {
            return Result.fail("缺少电站参数");
        }
        CustomerEntry entry = customerEntryDao.get(entryId);
        if (entry == null) {
            return Result.fail("未查询到电站信息");
        }
        // 2.查询是否存在流程中的申请单
        String msg = CrmUtils.checkExistApply(entry.getStatus(), entryId);
        if (StringUtils.isNotBlank(msg)){
            return Result.fail(msg);
        }
        if (customerEntryChangeRecordDao.getIfHaveMaterialChange(entry.getId()) > 0) {
            return Result.fail("该电站有待资方审核的变更记录，请审核后再提交");
        }
        //3.判断变更后的条码是否重复
        List<String> newNbqSnList = new ArrayList<>();
        List<String> newBarcodeList = new ArrayList<>();
        List<CrmMaterialInformationChangeApplyDetail> nbqDetails = materialVo.getNbqDetails();
        List<CrmMaterialInformationChangeApplyDetail> zjDetails = materialVo.getZjDetails();
        int index = 1;
        boolean flag = true;//判断是否有变更的数据
        for (CrmMaterialInformationChangeApplyDetail nbqDetail : nbqDetails) {
            String newNbqSn = nbqDetail.getNewNbqSn();
            if (StringUtils.isNotBlank(newNbqSn)){
                flag = false;
                if (newNbqSnList.contains(newNbqSn)){
                    throw new BusinessException("第"+index+"行变更后的逆变器sn码重复");
                }
                newNbqSnList.add(newNbqSn);
            }
            if (StringUtils.isNotBlank(nbqDetail.getNewSn())){
                flag = false;
            }
            if (StringUtils.isNotBlank(nbqDetail.getNewYzCode())){
                flag = false;
            }
            index++;
        }
        int i = 1;
        for (CrmMaterialInformationChangeApplyDetail zjDetail : zjDetails) {
            String newBarcode = zjDetail.getNewBarcode();
            if (StringUtils.isNotBlank(newBarcode)){
                flag=false;
                if (newBarcodeList.contains(newBarcode)){
                    throw new BusinessException("第"+i+"行变更后的物料条码重复");
                }
                newBarcodeList.add(newBarcode);
            }
            i++;
        }
        if (flag){
            throw new BusinessException("没有变更的数据，不可提交变更");
        }
        Date now = new Date();
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        // 创建申请单
        CrmMaterialInformationChangeApply changeApply = applyDao.createOne(materialVo.getChangeReason(), entry, operator, now);
        //生成明细
        for (CrmMaterialInformationChangeApplyDetail zjDetail : zjDetails) {
            detailDao.createApplyDetail(changeApply.getId(),zjDetail,"1");
        }
        for (CrmMaterialInformationChangeApplyDetail nbqDetail : nbqDetails) {
            detailDao.createApplyDetail(changeApply.getId(),nbqDetail,"2");
        }
        //所有的变更审核 要走待办事项审批流程，默认审批人为原审核人员  物料信息变更审核 查询的是安装验收/物料信息变更审核人
        //获取拼接标题名称
        String stationName = CrmUtils.getStationName(entry);
        ItemManage itemManage=itemManageDao.addItemChange(FormUtils.ENTRY_CHANGE_WLXXBG,entryId,changeApply.getId(),"物料信息变更("+ stationName+"-"+entry.getPowerStationCode()+")-"+ DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,user.getUserName());
        //获取最近一次 安装验收/物料信息变更审核人
        String userId=itemManageDao.getLastAuditUserId("93,99",entryId);
        if(StringUtil.isNotBlank(userId)){
//            itemManage.setAssignAuditUserId(userId);
            itemManage.setPreferUserId(userId);
        }
        itemManageDao.save(itemManage);
        entryMsgService.saveCustomerEntryMsg(Operator.of(user), entry.getId(), CustomerEntryConstants.ENTRY_ADD_CHANGE
                , String.format("第%d次提交电站物料信息变更申请", changeApply.getChangeTime()), null);
        //大代理商优先审核
        String groupName = "安装审核";
        crmPriorReviewSettingService.traderPriorityReview(entry.getCreateTraderId(),itemManage.getId(),groupName);
        return Result.ok();
    }
@Transactional(rollbackFor = Exception.class)
    public Result addMaterialInformationChangeHR(AnyProductMaterialChangeVo materialVo) {
        // 校验参数
        // 1.获取电站信息
        String entryId = materialVo.getEntryId();
        if (StringUtil.isBlank(entryId)) {
            return Result.fail("缺少电站参数");
        }
        CustomerEntry entry = customerEntryDao.get(entryId);
        if (entry == null) {
            return Result.fail("未查询到电站信息");
        }
        // 2.查询是否存在流程中的申请单
        String msg = CrmUtils.checkExistApply(entry.getStatus(), entryId);
        if (StringUtils.isNotBlank(msg)){
            return Result.fail(msg);
        }
        if (customerEntryChangeRecordDao.getIfHaveMaterialChange(entry.getId()) > 0) {
            return Result.fail("该电站有待资方审核的变更记录，请审核后再提交");
        }
        //3.判断变更后的条码是否重复
        List<String> newNbqSnList = new ArrayList<>();
        List<String> newBarcodeList = new ArrayList<>();
        boolean flag = true;//判断是否有变更的数据
        List<MaterialInfoVo> materialList = materialVo.getMaterialList();
        for (MaterialInfoVo materialInfoVo : materialList) {
            String projectId = materialInfoVo.getProjectId();
            String roofType = customerEntryProjectDao.getRoofTypeByProjectId(entryId, projectId);
            List<CrmMaterialInformationChangeApplyDetail> nbqDetails = materialInfoVo.getNbqDetails();
            List<CrmMaterialInformationChangeApplyDetail> zjDetails = materialInfoVo.getZjDetails();
            int index = 1;
            for (CrmMaterialInformationChangeApplyDetail nbqDetail : nbqDetails) {
                String newNbqSn = nbqDetail.getNewNbqSn();
                if (StringUtils.isNotBlank(newNbqSn)){
                    flag = false;
                    if (newNbqSnList.contains(newNbqSn)){
                        throw new BusinessException(roofType+"第"+index+"行变更后的逆变器sn码重复");
                    }
                    newNbqSnList.add(newNbqSn);
                }
                if (StringUtils.isNotBlank(nbqDetail.getNewSn())){
                    flag = false;
                }
                if (StringUtils.isNotBlank(nbqDetail.getNewYzCode())){
                    flag = false;
                }
                index++;
            }
            int i = 1;
            for (CrmMaterialInformationChangeApplyDetail zjDetail : zjDetails) {
                String newBarcode = zjDetail.getNewBarcode();
                if (StringUtils.isNotBlank(newBarcode)){
                    flag=false;
                    if (newBarcodeList.contains(newBarcode)){
                        throw new BusinessException(roofType+"第"+i+"行变更后的物料条码重复");
                    }
                    newBarcodeList.add(newBarcode);
                }
                i++;
            }
        }
        if (flag){
            throw new BusinessException("没有变更的数据，不可提交变更");
        }
        Date now = new Date();
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        // 创建申请单
        CrmMaterialInformationChangeApply changeApply = applyDao.createOne(materialVo.getChangeReason(), entry, operator, now);
        for (MaterialInfoVo materialInfoVo : materialList) {
            //生成明细
            for (CrmMaterialInformationChangeApplyDetail zjDetail : materialInfoVo.getZjDetails()) {
                detailDao.createApplyDetail(changeApply.getId(),zjDetail,"1",materialInfoVo.getProjectId());
            }
            for (CrmMaterialInformationChangeApplyDetail nbqDetail : materialInfoVo.getNbqDetails()) {
                detailDao.createApplyDetail(changeApply.getId(),nbqDetail,"2",materialInfoVo.getProjectId());
            }
        }
        //所有的变更审核 要走待办事项审批流程，默认审批人为原审核人员  物料信息变更审核 查询的是安装验收/物料信息变更审核人
        //获取拼接标题名称
        String stationName = CrmUtils.getStationName(entry);
        ItemManage itemManage=itemManageDao.addItemChange(FormUtils.ENTRY_CHANGE_WLXXBG,entryId,changeApply.getId(),"物料信息变更("+ stationName+"-"+entry.getPowerStationCode()+")-"+ DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,user.getUserName());
        //获取最近一次 安装验收/物料信息变更审核人
        String userId=itemManageDao.getLastAuditUserId("93,99",entryId);
        if(StringUtil.isNotBlank(userId)){
//            itemManage.setAssignAuditUserId(userId);
            itemManage.setPreferUserId(userId);
        }
        itemManageDao.save(itemManage);
        entryMsgService.saveCustomerEntryMsg(Operator.of(user), entry.getId(), CustomerEntryConstants.ENTRY_ADD_CHANGE
                , String.format("第%d次提交电站物料信息变更申请", changeApply.getChangeTime()), null);
        //大代理商优先审核
        String groupName = "安装审核";
        crmPriorReviewSettingService.traderPriorityReview(entry.getCreateTraderId(),itemManage.getId(),groupName);
        return Result.ok();
    }

    /**
     * 审核驳回
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result temp(MaterialAuditVo materialAuditVo) {
        CrmMaterialInformationChangeApply apply = applyDao.get(materialAuditVo.getId());
        if (!"0".equals(apply.getStatus())) {
            return Result.fail("状态已改变,刷新后重试");
        }
        apply.setAuditRemarks(materialAuditVo.getAuditRemark());
        applyDao.save(apply);

        return Result.ok();
    }

    /**
     * 审核驳回
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result refuse(MaterialAuditVo materialAuditVo) {
        CrmMaterialInformationChangeApply apply = applyDao.get(materialAuditVo.getId());
        if (!"0".equals(apply.getStatus())) {
            return Result.fail("状态已改变,刷新后重试");
        }
        User user = UserUtils.getUser();
        Date now = new Date();
        apply.setStatus("2");
        apply.setUniqueKey(IdGen.uuid());
        apply.setAuditName(CrmUtils.getUserXM(user));
        apply.setAuditBy(user.getId());
        apply.setAuditTime(now);
        apply.setAuditRemarks(materialAuditVo.getAuditRemark());
        applyDao.save(apply);

        //处理待办任务
        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(apply.getId(),FormUtils.ENTRY_CHANGE_WLXXBG);
        if (itemManage != null) {
            Operator operator=Operator.of(user);
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_WLXXBG,itemManage.getApplicationId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_BACK, now, operator, "物料信息变更");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(now);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
        String msg = (StringUtil.isNotBlank(materialAuditVo.getAuditRemark()) ? ","+ materialAuditVo.getAuditRemark() : "");
        String content = String.format("第%d次电站物料信息变更申请，审核驳回" + msg, apply.getChangeTime());
        entryMsgService.saveCustomerEntryMsg(Operator.of(user), apply.getEntryId(), CustomerEntryConstants.ENTRY_CHANGE_REFUSE
                , content, null);
        return Result.ok();
    }

    /**
     * 审核通过
     */
    @Transactional(rollbackFor = Exception.class)
    public Result pass(MaterialAuditVo materialAuditVo) {
        Result result = new Result();
        CrmMaterialInformationChangeApply apply = applyDao.get(materialAuditVo.getId());
        if (!"0".equals(apply.getStatus())) {
            return Result.fail("状态已改变,刷新后重试");
        }
        User user = UserUtils.getUser();
        apply.setStatus("1");
        apply.setUniqueKey(IdGen.uuid());
        apply.setAuditName(CrmUtils.getUserXM(user));
        apply.setAuditBy(user.getId());
        apply.setAuditTime(new Date());
        apply.setAuditRemarks(materialAuditVo.getAuditRemark());
        applyDao.save(apply);
        //判断是否接入逆变器平台
        String jlStationId = customerEntryService.getJlStationId("01", apply.getEntryId());// 锦浪电站id

        //固德威电站id
        String gdwStationId = customerEntryService.getJlStationId("02", apply.getEntryId());
        boolean gwJrFlag = StringUtil.isNotBlank(gdwStationId); // 固德威接入标记
        //爱士惟电站id
        String aswStationId = customerEntryService.getJlStationId("03", apply.getEntryId());
        //获取电站信息
        CustomerEntry entry = customerEntryDao.get(apply.getEntryId());
        // 系统存的Wp 需要转化成kWp
        BigDecimal actualCapacity = entry.getActualCapacity().divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP);
        // 详细地址
        String address = entry.getProvince() + entry.getCity() + entry.getArea() + entry.getAddress();
        String azTime = (entry.getInstallTime() != null ? DateUtils.formatDate(entry.getInstallTime(),"yyyy-MM-dd HH:mm:ss") : "");
        String stationName = StringUtil.getStationName(entry.getTenantName(),entry.getPowerStationCode()); // 业主姓名+电站编码
        //变更详情
        List<Record> records = detailDao.findMaterialDetailsByApplyId(apply.getId());
        List<Record> zjList = records.stream().filter(record -> "1".equals(record.getStr("type"))).collect(Collectors.toList());
        List<Record> nbqList = records.stream().filter(record -> "2".equals(record.getStr("type"))).collect(Collectors.toList());
        //组件
        for (Record record : zjList) {
            String barcode = record.getStr("barcode");
            String newBarcode = record.getStr("new_barcode");
            if (StringUtils.isNotBlank(newBarcode)){
                //变更前
                CrmSupplyBarcode oneByBarcode = barcodeDao.findOneByBarcode(barcode);
                oneByBarcode.setBarcodeStatus("2");
                barcodeDao.save(oneByBarcode);
                //变更后
                CrmSupplyBarcode byBarcode = barcodeDao.findOneByBarcode(newBarcode);
                byBarcode.setBarcodeStatus("1");
                barcodeDao.save(byBarcode);
                //电站已使用物料
                CrmPlanMaterialEntry planMaterialEntry = planMaterialEntryDao.findByEntryIdMaterial(apply.getEntryId(), record.getStr("material_id"), barcode);
                planMaterialEntry.setBarcode(newBarcode);
                planMaterialEntryDao.save(planMaterialEntry);
            }
        }
        //逆变器
        boolean needChange = false; // 锦浪逆变器是否有变更
        String ginlangSn = ""; // 需要调整后的锦浪SN
        List<Map<String,String>> aisweiList=new ArrayList<>(); // 爱士惟
        for (Record record : nbqList) {
            String nbqSn = record.getStr("nbq_sn");
            String newNbqSn = record.getStr("new_nbq_sn");
            String newSn = record.getStr("new_sn");
            String newYzCode = record.getStr("new_yz_code");
            String yzCode = record.getStr("yz_code");
            String materialName = record.getStr("material_name");
            String materialBrand = record.getStr("material_brand");
            BrandFactInfo info = BrandFactInfo.externalOf(materialBrand);
            //修改条码使用状态
            if (StringUtils.isNotBlank(newNbqSn)){
                //变更前
                CrmSupplyBarcode oneByBarcode = barcodeDao.findOneByBarcode(nbqSn);
                oneByBarcode.setBarcodeStatus("2");
                barcodeDao.save(oneByBarcode);
                //变更后
                CrmSupplyBarcode byBarcode = barcodeDao.findOneByBarcode(newNbqSn);
                byBarcode.setBarcodeStatus("1");
                barcodeDao.save(byBarcode);
            }
            //电站已使用物料
            CrmPlanMaterialEntry planMaterialEntry = planMaterialEntryDao.findByEntryIdMaterial(apply.getEntryId(), record.getStr("material_id"), nbqSn);
            //通讯棒sn变更时，如果电站未接入逆变器平台需要全部同步新增电站。
            if (info == BrandFactInfo.Jinlang && StringUtil.isBlank(jlStationId)) {
                if (StringUtils.isNotBlank(newSn)){
                    needChange = true;
                    ginlangSn = ginlangSn + newSn + ",";
                }
                else {
                    ginlangSn = ginlangSn + planMaterialEntry.getSn() + ",";
                }
            }
            //逆变器sn码和通讯棒sn变更时，如果电站已经接入逆变器平台需要重新推送变更后的数据到逆变器平台。
            //通讯棒sn码
            if (StringUtils.isNotBlank(newSn)){
                String oldSn = planMaterialEntry.getSn();
                planMaterialEntry.setSn(newSn);
                if (StringUtil.isNotBlank(jlStationId)){
                    //同步逆变器平台
                    if(info == BrandFactInfo.Jinlang){
                        try {
                            customerEntryService.editCollectorGinLang(apply.getEntryId(), oldSn,
                                    newSn, jlStationId,entry.getPartnerId());
                        }catch (Exception e) {
                            String reqStr = oldSn +"," + newSn + "," + jlStationId;
                            customerEntryService.saveSysRecord(apply.getEntryId(),"物料信息变更 锦浪 更换采集器失败",
                                    reqStr, e.getMessage(), "1");
                        }
                    }
                }
            }
            //逆变器sn码
            if (StringUtils.isNotBlank(newNbqSn)){
                planMaterialEntry.setNbqSn(newNbqSn);
                planMaterialEntry.setBarcode(newNbqSn);
                if (gwJrFlag){
                    //同步逆变器平台 如果原先未接入 则本次不会同步
                    //锦浪设备 不进行逆变器变更
                    //固德威需要变更
                    if(info == BrandFactInfo.GoodW){
                        try {
                            //删除设备
                            customerEntryService.removeInverterGoodW(apply.getEntryId(),gdwStationId, nbqSn,entry.getPartnerId());
                            //新增设备
                            if (StringUtils.isNotBlank(newYzCode)) {
                                customerEntryService.addInverterGoodW(apply.getEntryId(), materialName, newNbqSn, newYzCode,entry.getPartnerId());
                            } else {
                                customerEntryService.addInverterGoodW(apply.getEntryId(), materialName, newNbqSn, yzCode,entry.getPartnerId());
                            }
                        }catch (Exception e) {
                            customerEntryService.saveSysRecord(apply.getEntryId(),"物料信息变更 固德威 删除变更前的电站接入记录 失败",
                                    nbqSn+newYzCode, e.getMessage(), "1");
                        }
                    }
                }
            }
            //验证码
            if ((info == BrandFactInfo.GoodW || info == BrandFactInfo.Aiswei ) && StringUtils.isNotBlank(newYzCode)){
                planMaterialEntry.setYzCode(newYzCode);
            }
            if (info == BrandFactInfo.Aiswei){
                Map<String,String> map=new HashMap();
                map.put("psno",planMaterialEntry.getSn());//采集器 SN码
                map.put("registno",planMaterialEntry.getYzCode());
                aisweiList.add(map);
            }
            planMaterialEntryDao.save(planMaterialEntry);
        }

        // 新增新的锦浪电站接入记录
        if (needChange && StringUtil.isNotBlank(ginlangSn)) {
            ginlangSn = ginlangSn.substring(0,ginlangSn.length()-1);
            try {
                customerEntryService.addCollectorGinLang(apply.getEntryId(), ginlangSn, entry.getMobile(), entry.getTraderTel(),
                        azTime, entry.getEpcPrice().toPlainString(), entry.getProvince(), entry.getCity(), address,
                        stationName, actualCapacity.toPlainString(),entry.getPartnerId());
            }catch (Exception e) {
                customerEntryService.saveSysRecord(apply.getEntryId(),"物料信息变更 锦浪逆变器 新增新的电站接入记录 失败",
                        ginlangSn, e.getMessage(), "1");
            }
        }

        // 新增新的爱士惟电站接入记录
        if (!aisweiList.isEmpty() && StringUtil.isBlank(aswStationId)) {
            customerEntryService.insertAiswei(entry, aisweiList);
        }

        CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());
        //广发
        if (PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
            if (application != null ) {
                if ("30".equals(entry.getNextApplyStatus())){
                    //物料信息变更接口
                    guangFaManagemnetService.materialInfoUpdate(entry,apply,application.getInputPieceId() );
                }else if ("20".equals(entry.getNextApplyStatus())){
                    //重新推送
                    guangfaOperatingService.accessProjectApplyTwo(entry,application);
                }
            }
        }else if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
            //越秀
            if ("APPROVED".equals(entry.getNextApplyStatus())){
                //退回完工
                yueXiuProjectOperatingService.returnIncomingToCompletion(entry.getId(),"物料信息变更，退回完工");
                //重新推送进件信息
                yueXiuProjectOperatingService.againPushIncoming(entry,"twoIncoming");
            }
        }

        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(apply.getId(),FormUtils.ENTRY_CHANGE_WLXXBG);
        if (itemManage != null) {
            Operator operator=Operator.of(user);
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_WLXXBG,itemManage.getApplicationId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_OK, apply.getAuditTime(), operator, "物料信息变更");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(apply.getAuditTime());
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
        String msg = (StringUtil.isNotBlank(materialAuditVo.getAuditRemark()) ? ","+ materialAuditVo.getAuditRemark() : "");
        String content = String.format("第%d次电站物料信息变更申请，审核通过" + msg, apply.getChangeTime());
        entryMsgService.saveCustomerEntryMsg(Operator.of(user), apply.getEntryId(), CustomerEntryConstants.ENTRY_CHANGE_PASS
                , content, null);
        result.setCode("200");
        result.setData(entry.getId());
        return result;
    }

    /**
     * 审核通过（华融多产品）
     */
    @Transactional(rollbackFor = Exception.class)
    public Result passHR(MaterialAuditVo materialAuditVo) {
        Result result = new Result();
        CrmMaterialInformationChangeApply apply = applyDao.get(materialAuditVo.getId());
        if (!"0".equals(apply.getStatus())) {
            return Result.fail("状态已改变,刷新后重试");
        }
        User user = UserUtils.getUser();
        apply.setStatus("1");
        apply.setUniqueKey(IdGen.uuid());
        apply.setAuditName(CrmUtils.getUserXM(user));
        apply.setAuditBy(user.getId());
        apply.setAuditTime(new Date());
        apply.setAuditRemarks(materialAuditVo.getAuditRemark());
        applyDao.save(apply);
        //判断是否接入逆变器平台
        String jlStationId = customerEntryService.getJlStationId("01", apply.getEntryId());// 锦浪电站id

        //固德威电站id
        String gdwStationId = customerEntryService.getJlStationId("02", apply.getEntryId());
        boolean gwJrFlag = StringUtil.isNotBlank(gdwStationId); // 固德威接入标记
        //爱士惟电站id
        String aswStationId = customerEntryService.getJlStationId("03", apply.getEntryId());
        //获取电站信息
        CustomerEntry entry = customerEntryDao.get(apply.getEntryId());
        // 系统存的Wp 需要转化成kWp
        BigDecimal actualCapacity = entry.getActualCapacity().divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP);
        // 详细地址
        String address = entry.getProvince() + entry.getCity() + entry.getArea() + entry.getAddress();
        String azTime = (entry.getInstallTime() != null ? DateUtils.formatDate(entry.getInstallTime(),"yyyy-MM-dd HH:mm:ss") : "");
        String stationName = StringUtil.getStationName(entry.getTenantName(),entry.getPowerStationCode()); // 业主姓名+电站编码
        //变更详情
        List<Record> records = detailDao.findMaterialDetailsByApplyId(apply.getId());
        List<Record> projectList = projectService.getEntryProjectByEntryId(entry.getId());
        for (Record project : projectList) {
            String projectId = project.getStr("projectId");
            List<Record> materialList = records.stream().filter(r -> projectId.equals(r.getStr("project_id"))).collect(Collectors.toList());
            List<Record> zjList = materialList.stream().filter(record -> "1".equals(record.getStr("type"))).collect(Collectors.toList());
            List<Record> nbqList = materialList.stream().filter(record -> "2".equals(record.getStr("type"))).collect(Collectors.toList());
            //组件
            for (Record record : zjList) {
                String barcode = record.getStr("barcode");
                String newBarcode = record.getStr("new_barcode");
                if (StringUtils.isNotBlank(newBarcode)){
                    //变更前
                    CrmSupplyBarcode oneByBarcode = barcodeDao.findOneByBarcode(barcode);
                    oneByBarcode.setBarcodeStatus("2");
                    barcodeDao.save(oneByBarcode);
                    //变更后
                    CrmSupplyBarcode byBarcode = barcodeDao.findOneByBarcode(newBarcode);
                    byBarcode.setBarcodeStatus("1");
                    barcodeDao.save(byBarcode);
                    //电站已使用物料
                    CrmPlanMaterialEntry planMaterialEntry = planMaterialEntryDao.findByEntryIdMaterial(apply.getEntryId(), record.getStr("material_id"), barcode,projectId);
                    planMaterialEntry.setBarcode(newBarcode);
                    planMaterialEntryDao.save(planMaterialEntry);
                }
            }
            //逆变器
            boolean needChange = false; // 锦浪逆变器是否有变更
            String ginlangSn = ""; // 需要调整后的锦浪SN
            List<Map<String,String>> aisweiList=new ArrayList<>(); // 爱士惟
            for (Record record : nbqList) {
                String nbqSn = record.getStr("nbq_sn");
                String newNbqSn = record.getStr("new_nbq_sn");
                String newSn = record.getStr("new_sn");
                String newYzCode = record.getStr("new_yz_code");
                String yzCode = record.getStr("yz_code");
                String materialName = record.getStr("material_name");
                String materialBrand = record.getStr("material_brand");
                BrandFactInfo info = BrandFactInfo.externalOf(materialBrand);
                //修改条码使用状态
                if (StringUtils.isNotBlank(newNbqSn)){
                    //变更前
                    CrmSupplyBarcode oneByBarcode = barcodeDao.findOneByBarcode(nbqSn);
                    oneByBarcode.setBarcodeStatus("2");
                    barcodeDao.save(oneByBarcode);
                    //变更后
                    CrmSupplyBarcode byBarcode = barcodeDao.findOneByBarcode(newNbqSn);
                    byBarcode.setBarcodeStatus("1");
                    barcodeDao.save(byBarcode);
                }
                //电站已使用物料
                CrmPlanMaterialEntry planMaterialEntry = planMaterialEntryDao.findByEntryIdMaterial(apply.getEntryId(), record.getStr("material_id"), nbqSn,projectId);
                //通讯棒sn变更时，如果电站未接入逆变器平台需要全部同步新增电站。
                if (info == BrandFactInfo.Jinlang && StringUtil.isBlank(jlStationId)) {
                    if (StringUtils.isNotBlank(newSn)){
                        needChange = true;
                        ginlangSn = ginlangSn + newSn + ",";
                    }
                    else {
                        ginlangSn = ginlangSn + planMaterialEntry.getSn() + ",";
                    }
                }
                //逆变器sn码和通讯棒sn变更时，如果电站已经接入逆变器平台需要重新推送变更后的数据到逆变器平台。
                //通讯棒sn码
                if (StringUtils.isNotBlank(newSn)){
                    String oldSn = planMaterialEntry.getSn();
                    planMaterialEntry.setSn(newSn);
                    if (StringUtil.isNotBlank(jlStationId)){
                        //同步逆变器平台
                        if(info == BrandFactInfo.Jinlang){
                            try {
                                customerEntryService.editCollectorGinLang(apply.getEntryId(), oldSn,
                                        newSn, jlStationId,entry.getPartnerId());
                            }catch (Exception e) {
                                String reqStr = oldSn +"," + newSn + "," + jlStationId;
                                customerEntryService.saveSysRecord(apply.getEntryId(),"物料信息变更 锦浪 更换采集器失败",
                                        reqStr, e.getMessage(), "1");
                            }
                        }
                    }
                }
                //逆变器sn码
                if (StringUtils.isNotBlank(newNbqSn)){
                    planMaterialEntry.setNbqSn(newNbqSn);
                    planMaterialEntry.setBarcode(newNbqSn);
                    if (gwJrFlag){
                        //同步逆变器平台 如果原先未接入 则本次不会同步
                        //锦浪设备 不进行逆变器变更
                        //固德威需要变更
                        if(info == BrandFactInfo.GoodW){
                            try {
                                //删除设备
                                customerEntryService.removeInverterGoodW(apply.getEntryId(),gdwStationId, nbqSn,entry.getPartnerId());
                                //新增设备
                                if (StringUtils.isNotBlank(newYzCode)) {
                                    customerEntryService.addInverterGoodW(apply.getEntryId(), materialName, newNbqSn, newYzCode,entry.getPartnerId());
                                } else {
                                    customerEntryService.addInverterGoodW(apply.getEntryId(), materialName, newNbqSn, yzCode,entry.getPartnerId());
                                }
                            }catch (Exception e) {
                                customerEntryService.saveSysRecord(apply.getEntryId(),"物料信息变更 固德威 删除变更前的电站接入记录 失败",
                                        nbqSn+newYzCode, e.getMessage(), "1");
                            }
                        }
                    }
                }
                //验证码
                if (( info == BrandFactInfo.GoodW || info == BrandFactInfo.Aiswei ) && StringUtils.isNotBlank(newYzCode)){
                    planMaterialEntry.setYzCode(newYzCode);
                }
                if (info == BrandFactInfo.Aiswei){
                    Map<String,String> map=new HashMap();
                    map.put("psno",planMaterialEntry.getSn());//采集器 SN码
                    map.put("registno",planMaterialEntry.getYzCode());
                    aisweiList.add(map);
                }
                planMaterialEntryDao.save(planMaterialEntry);
            }

            // 新增新的锦浪电站接入记录
            if (needChange && StringUtil.isNotBlank(ginlangSn)) {
                ginlangSn = ginlangSn.substring(0,ginlangSn.length()-1);
                try {
                    customerEntryService.addCollectorGinLang(apply.getEntryId(), ginlangSn, entry.getMobile(), entry.getTraderTel(),
                            azTime, entry.getEpcPrice().toPlainString(), entry.getProvince(), entry.getCity(), address,
                            stationName, actualCapacity.toPlainString(),entry.getPartnerId());
                }catch (Exception e) {
                    customerEntryService.saveSysRecord(apply.getEntryId(),"物料信息变更 锦浪逆变器 新增新的电站接入记录 失败",
                            ginlangSn, e.getMessage(), "1");
                }
            }

            // 新增新的爱士惟电站接入记录
            if (!aisweiList.isEmpty() && StringUtil.isBlank(aswStationId)) {
                customerEntryService.insertAiswei(entry, aisweiList);
            }
        }
        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(apply.getId(),FormUtils.ENTRY_CHANGE_WLXXBG);
        if (itemManage != null) {
            Operator operator=Operator.of(user);
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_WLXXBG,itemManage.getApplicationId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_OK, apply.getAuditTime(), operator, "物料信息变更");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(apply.getAuditTime());
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
        String msg = (StringUtil.isNotBlank(materialAuditVo.getAuditRemark()) ? ","+ materialAuditVo.getAuditRemark() : "");
        String content = String.format("第%d次电站物料信息变更申请，审核通过" + msg, apply.getChangeTime());
        entryMsgService.saveCustomerEntryMsg(Operator.of(user), apply.getEntryId(), CustomerEntryConstants.ENTRY_CHANGE_PASS
                , content, null);
        result.setCode("200");
        result.setData(entry.getId());
        return result;
    }

    public List<Record> getChangeBarCode(String materialCode, String newBarcode) {
        List<Record> list = barcodeDao.findBarcodesByBraCode(materialCode, newBarcode);
        return list;
    }
    @Transactional(rollbackFor = Exception.class)
    public Result cancel(String id) {
        CrmMaterialInformationChangeApply apply = applyDao.get(id);
        if (!"0".equals(apply.getStatus())) {
            return Result.fail("状态已改变,刷新后重试");
        }
        User user = UserUtils.getUser();
        apply.setStatus("3");
        apply.setUniqueKey(IdGen.uuid());
        apply.setAuditName(CrmUtils.getUserXM(user));
        apply.setAuditBy(user.getId());
        applyDao.save(apply);

        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(apply.getId(),FormUtils.ENTRY_CHANGE_WLXXBG);
        if(itemManage !=null){
            itemManage.setStatus(ItemConstants.ITEM_STATUS_CANCEL);
            itemManage.setEndTime(new Date());
            itemManageDao.save(itemManage);
        }
        String content = String.format("第%d次电站物料信息变更申请，撤回", apply.getChangeTime());
        entryMsgService.saveCustomerEntryMsg(Operator.of(user), apply.getEntryId(), CustomerEntryConstants.ENTRY_CHANGE_CANCEL
                , content, null);
        return Result.ok();
    }
}
