package com.dayou.dyoa;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dayou.common.BaseEntity;
import com.dayou.common.PullDownModel;
import com.dayou.dto.MajorSubClientDTO;
import com.dayou.dto.PersonalProductionDTO;
import com.dayou.dto.history.*;
import com.dayou.entity.*;
import com.dayou.enums.MainBusinessEnum;
import com.dayou.enums.ProductionEnum;
import com.dayou.exception.ErrorCode;
import com.dayou.mapper.*;
import com.dayou.service.*;
import com.dayou.service.impl.AssetsServiceImpl;
import com.dayou.service.impl.PersonalProductionServiceImpl;
import com.dayou.service.workflow.IWorkFlowNodeInstanceService;
import com.dayou.utils.DateUtils;
import com.dayou.utils.HttpKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.dayou.common.Constants.*;
import static com.dayou.enums.FinanceInvoiceState.已作废;
import static com.dayou.enums.MainBusinessEnum.*;
import static com.dayou.enums.ProductionEnum.*;
import static com.dayou.enums.workflow.NodeStateEnum.FINISHED;
import static com.dayou.enums.workflow.WorkflowNodeEnum.*;

@DS("dyoa")
@Service
@Slf4j
public class DyoaHistoryServiceImpl implements IDyoaHistoryService{


    private static String COOKIE ;


    private static final String HISTORY_LOGIN_URL = "http://noa.scdayou.com/login?loginName=admin&password=root1234";

    private static final String HISTORY_MAJOR_ORDER_URL = "http://noa.scdayou.com/dyoa/order/pageQuery";

    private static final String HISTORY_ASSETS_ORDER_URL = "http://noa.scdayou.com/dyoa/assets/assets/pageQuery";

    private Map<String,Long> users = new HashMap<>();

    private Map<String,Long> departments = new HashMap<>();

//    private Map<String,Long> realAmounts = new HashMap<>();

//    private Map<String,Long> orderFundIds = new HashMap<>();

//    private Map<String,Long> productionFundIds = new HashMap<>();
//
//    private Map<Long,Long> orderFundIdProdFundIds = new HashMap<>();

    private static final Map<String,String> MAJOR_ORDER_COLUM = new HashMap<>();

    private static final Map<String,String> MAJOR_PRODUCTION_COLUM = new HashMap<>();

    private static final Map<String,String> PERSONAL_ORDER_COLUM = new HashMap<>();

    private static final Map<String,String> REAL_AMOUNT_COLUM = new HashMap<>();

    private static final Map<String,String> REAL_AMOUNT_CLAIM_COLUM = new HashMap<>();

    private static final Map<String,String> ASSETS_ORDER_COLUM = new HashMap<>();

    private static final Map<String,String> ASSETS_PRODUCTION_COLUM = new HashMap<>();

    private static final Map<String,String> FINANCE_INVOICE_COLUM = new HashMap<>();

    private static  Map<String,Long> PG_BUSINESS_TYPE = new HashMap<>();

    private static  Map<String,Long> SC_BUSINESS_TYPE = new HashMap<>();




    @Autowired
    private IUserService userService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private DyoaHistoryMapper dyoaHistoryMapper;

    @Autowired
    private IDyoaRecordService dyoaRecordService;

    @Autowired
    private IFinanceRealFundService financeRealFundService;

    @Autowired
    private IOrderFundService orderFundService;

    @Autowired
    private IProductionFundService productionFundService;

    @Autowired
    private IMajorService majorServiceImpl;


    @Autowired
    private IMajorProductionService majorProductionService;

    @Autowired
    private IPersonalService personalService;

    @Autowired
    private ICustomerCompanyService customerCompanyService;

    @Autowired
    private ICustomerLinkmanService customerLinkmanService;

    @Autowired
    private IAssetsService assetsService;

    @Autowired
    private IFinanceClaimService financeClaimService;

    @Autowired
    private IAssetsService assetsServiceImpl;

    @Autowired
    private IAssetsProductionService assetsProductionService;

    @Autowired
    private IFinanceInvoiceService financeInvoiceService;

    @Autowired
    private IPersonalTargetService personalTargetService;

    @Autowired
    private ICommissionDeclareService commissionDeclareService;

    static {
//        MAJOR_ORDER_COLUM.put("id","id");
        MAJOR_ORDER_COLUM.put("name","name");
        MAJOR_ORDER_COLUM.put("code","orderId");
        MAJOR_ORDER_COLUM.put("sourceType","financial");
        MAJOR_ORDER_COLUM.put("assign","allotType");
        MAJOR_ORDER_COLUM.put("masterName","clientManagerId");
        MAJOR_ORDER_COLUM.put("managerName","principalId");
        MAJOR_ORDER_COLUM.put("masterOrgName","departmentId");
        MAJOR_ORDER_COLUM.put("businessType","businessObjectType");
        MAJOR_ORDER_COLUM.put("businessType2","businessGener");
        MAJOR_ORDER_COLUM.put("spec","specialType");
        MAJOR_ORDER_COLUM.put("evaluateTarget","evaluateAim");
        MAJOR_ORDER_COLUM.put("repeatOrder","entrustAgain");
        MAJOR_ORDER_COLUM.put("fhbq","multipleRemoval");
        MAJOR_ORDER_COLUM.put("oral","informalEvaluate");
        MAJOR_ORDER_COLUM.put("customerType","clienteleType");
        MAJOR_ORDER_COLUM.put("cz","dispenseBenefit");
        MAJOR_ORDER_COLUM.put("locations","nonnative");
        MAJOR_ORDER_COLUM.put("refinance","refinance");
        MAJOR_ORDER_COLUM.put("loanMoney","loanLimit");
        MAJOR_ORDER_COLUM.put("loanLimit","loanPeriod");
        MAJOR_ORDER_COLUM.put("loanProperty","loanNature");
        MAJOR_ORDER_COLUM.put("loanUsage","loanAim");
        MAJOR_ORDER_COLUM.put("loanExpired","loanExpire");
        MAJOR_ORDER_COLUM.put("principal","bailor");
        MAJOR_ORDER_COLUM.put("principalAddress","bailorAddress");
        MAJOR_ORDER_COLUM.put("principalName","bailorContactName");
        MAJOR_ORDER_COLUM.put("principalMobile","bailorContactTel");
        MAJOR_ORDER_COLUM.put("propertyName","owner");
        MAJOR_ORDER_COLUM.put("propertyMobile","ownerTel");
        MAJOR_ORDER_COLUM.put("urgent","urgent");
        MAJOR_ORDER_COLUM.put("terminalType","terminalClienteleType");
        MAJOR_ORDER_COLUM.put("members","members");
        MAJOR_ORDER_COLUM.put("description","remark");
        MAJOR_ORDER_COLUM.put("customerName","clienteleId");
        MAJOR_ORDER_COLUM.put("customerName2","clienteleSubId");
        MAJOR_ORDER_COLUM.put("bankContactName","clienteleContactId");
        MAJOR_ORDER_COLUM.put("terminalName","terminalClienteleId");
        MAJOR_ORDER_COLUM.put("terminalContactName","terminalClienteleContactId");

        //大中型产品字段
        MAJOR_PRODUCTION_COLUM.put("pType","production");
        MAJOR_PRODUCTION_COLUM.put("reportNo","reportNo");
        MAJOR_PRODUCTION_COLUM.put("signEmpNames","signatory");
        MAJOR_PRODUCTION_COLUM.put("name","name");
        MAJOR_PRODUCTION_COLUM.put("principal","clientName");
        MAJOR_PRODUCTION_COLUM.put("principalAddress","clientAddress");
        MAJOR_PRODUCTION_COLUM.put("principalMobile","clientTel");
        MAJOR_PRODUCTION_COLUM.put("propertyName","owner");
        MAJOR_PRODUCTION_COLUM.put("priceDate","valueTiming");
        MAJOR_PRODUCTION_COLUM.put("area","evaluateAcreage");
        MAJOR_PRODUCTION_COLUM.put("money","evaluateAmount");
        MAJOR_PRODUCTION_COLUM.put("xPrice","evaluatePrice");
        MAJOR_PRODUCTION_COLUM.put("specDesc","comment");
        MAJOR_PRODUCTION_COLUM.put("repo","repertoryState");
        MAJOR_PRODUCTION_COLUM.put("yjsInTime","repertoryInTime");
        MAJOR_PRODUCTION_COLUM.put("yjsOutTime","repertoryOutTime");
        MAJOR_PRODUCTION_COLUM.put("bgInTime","repertoryInTime");
        MAJOR_PRODUCTION_COLUM.put("bgOutTime","repertoryOutTime");
        MAJOR_PRODUCTION_COLUM.put("archiveTime","saveFileDate");
        MAJOR_PRODUCTION_COLUM.put("standardPrice","standardAmount");
        MAJOR_PRODUCTION_COLUM.put("confirmTime","deliveryDate");
        MAJOR_PRODUCTION_COLUM.put("deliveryState","delivery");
        MAJOR_PRODUCTION_COLUM.put("printQuantity","printTimes");

        //个贷订单字段
        PERSONAL_ORDER_COLUM.put("orderNo","orderId");
        PERSONAL_ORDER_COLUM.put("locations","location");
        PERSONAL_ORDER_COLUM.put("target","evaluateAim");
        PERSONAL_ORDER_COLUM.put("purpose","purpose");
        PERSONAL_ORDER_COLUM.put("loanMaxMoney","loanLimit");
        PERSONAL_ORDER_COLUM.put("loanMaxYear","loanPeriod");
        PERSONAL_ORDER_COLUM.put("masterName","clientManagerId");
        PERSONAL_ORDER_COLUM.put("principal1","bailorA");
        PERSONAL_ORDER_COLUM.put("principal1Mobile","bailoraTel");
        PERSONAL_ORDER_COLUM.put("principal2","bailorB");
        PERSONAL_ORDER_COLUM.put("principal2Mobile","bailorbTel");
        PERSONAL_ORDER_COLUM.put("description","remark");
        PERSONAL_ORDER_COLUM.put("outerEmpName","outwardStaff");
        PERSONAL_ORDER_COLUM.put("productEmpName","inwardStaff");
        PERSONAL_ORDER_COLUM.put("priceEmpName","pricingStaff");
        PERSONAL_ORDER_COLUM.put("agent","agent");
        PERSONAL_ORDER_COLUM.put("loanProperty","loanNature");
        PERSONAL_ORDER_COLUM.put("loanUsage","loanAim");
        PERSONAL_ORDER_COLUM.put("loanExpired","loanExpire");
        PERSONAL_ORDER_COLUM.put("customerType","clienteleType");
        PERSONAL_ORDER_COLUM.put("customerName","clienteleId");
        PERSONAL_ORDER_COLUM.put("customerName2","clienteleSubId");
        PERSONAL_ORDER_COLUM.put("bankContactName","clienteleContactId");
        PERSONAL_ORDER_COLUM.put("terminalType","terminalClienteleType");
        PERSONAL_ORDER_COLUM.put("terminalName","terminalClienteleId");
        PERSONAL_ORDER_COLUM.put("terminalContactName","terminalClienteleContactId");
        PERSONAL_ORDER_COLUM.put("finished","ifSaveFile");
        PERSONAL_ORDER_COLUM.put("finishTime","saveFileDate");
        PERSONAL_ORDER_COLUM.put("files","credentials");

        //实收款字段
        REAL_AMOUNT_COLUM.put("incomeTime","payDatetime");
        REAL_AMOUNT_COLUM.put("companyName","payer");
        REAL_AMOUNT_COLUM.put("bankName","payerBank");
        REAL_AMOUNT_COLUM.put("bankNo","payerAccount");
        REAL_AMOUNT_COLUM.put("money","amount");
        REAL_AMOUNT_COLUM.put("description","remark");
        REAL_AMOUNT_COLUM.put("creatorName","creatorId");

        //实收款认领记录
        REAL_AMOUNT_CLAIM_COLUM.put("orderId","orderFundId");
        REAL_AMOUNT_CLAIM_COLUM.put("incomeId","realFundId");
        REAL_AMOUNT_CLAIM_COLUM.put("money","claimAmount");
        REAL_AMOUNT_CLAIM_COLUM.put("takeEmpName","claimUserId");
        REAL_AMOUNT_CLAIM_COLUM.put("createdDatetime","claimDatetime");

        //资产订单字段
        ASSETS_ORDER_COLUM.put("masterName","clientManagerId");
        ASSETS_ORDER_COLUM.put("assign","allotType");
        ASSETS_ORDER_COLUM.put("masterOrgName","departmentId");
        ASSETS_ORDER_COLUM.put("code","orderId");
        ASSETS_ORDER_COLUM.put("name","name");
        ASSETS_ORDER_COLUM.put("businessType","assetsBusinessGener");
        ASSETS_ORDER_COLUM.put("managerName","principalId");
        ASSETS_ORDER_COLUM.put("companyName","clienteleSubId");
        ASSETS_ORDER_COLUM.put("principal","bailor");
        ASSETS_ORDER_COLUM.put("principalName","bailorContactName");
        ASSETS_ORDER_COLUM.put("principalMobile","bailorContactTel");
        ASSETS_ORDER_COLUM.put("description","remark");
        ASSETS_ORDER_COLUM.put("customerType","clienteleType");
        ASSETS_ORDER_COLUM.put("customerName","clienteleId");
        ASSETS_ORDER_COLUM.put("bankContactName","clienteleContactId");
        ASSETS_ORDER_COLUM.put("terminalType","terminalClienteleType");
        ASSETS_ORDER_COLUM.put("terminalName","terminalClienteleId");
        ASSETS_ORDER_COLUM.put("terminalContactName","terminalClienteleContactId");
        ASSETS_ORDER_COLUM.put("importantAsset","significantAssetsReorganization");
        ASSETS_ORDER_COLUM.put("stateOwned","stateAssets");
        ASSETS_ORDER_COLUM.put("abroadAsset","foreignAssetsInvolved");
        ASSETS_ORDER_COLUM.put("cz","dispenseBenefit");
        ASSETS_ORDER_COLUM.put("stock","security");
        ASSETS_ORDER_COLUM.put("repeatOrder","entrustAgain");

        //资产产品字段
        ASSETS_PRODUCTION_COLUM.put("principal","clientName");
        ASSETS_PRODUCTION_COLUM.put("principalMobile","clientTel");
        ASSETS_PRODUCTION_COLUM.put("money","evaluateAmount");
        ASSETS_PRODUCTION_COLUM.put("area","evaluateAcreage");
        ASSETS_PRODUCTION_COLUM.put("price","evaluatePrice");
        ASSETS_PRODUCTION_COLUM.put("printQuantity","printCount");
        ASSETS_PRODUCTION_COLUM.put("archiveTime","saveFileDate");
        ASSETS_PRODUCTION_COLUM.put("finished","delivery");
        ASSETS_PRODUCTION_COLUM.put("type","productionType");
        ASSETS_PRODUCTION_COLUM.put("createdDatetime","createProductionDate");

        //财务开票字段
        FINANCE_INVOICE_COLUM.put("orderId","orderFundId");
        FINANCE_INVOICE_COLUM.put("creatorName","applyId");
        FINANCE_INVOICE_COLUM.put("incomeId","realFundId");
        FINANCE_INVOICE_COLUM.put("companyName","title");
        FINANCE_INVOICE_COLUM.put("companyNO","taxNo");
        FINANCE_INVOICE_COLUM.put("bankName","bankName");
        FINANCE_INVOICE_COLUM.put("bankNO","bankAccount");
        FINANCE_INVOICE_COLUM.put("address","bankAddress");
        FINANCE_INVOICE_COLUM.put("invoiceType","type");
        FINANCE_INVOICE_COLUM.put("project","makeItem");
        FINANCE_INVOICE_COLUM.put("planMoney","planAmount");
        FINANCE_INVOICE_COLUM.put("realMoney","realAmount");
        FINANCE_INVOICE_COLUM.put("taxPoint","taxRate");
        FINANCE_INVOICE_COLUM.put("planDate","planMakeDate");
        FINANCE_INVOICE_COLUM.put("realDate","realMakeDate");
        FINANCE_INVOICE_COLUM.put("unit","itemUnit");
        FINANCE_INVOICE_COLUM.put("taxAmount","taxAmount");
        FINANCE_INVOICE_COLUM.put("status","state");
        FINANCE_INVOICE_COLUM.put("reason","reason");
        FINANCE_INVOICE_COLUM.put("description","remark");
        FINANCE_INVOICE_COLUM.put("invoiceEmp","makerId");
        FINANCE_INVOICE_COLUM.put("ticketNo","ticketNo");
    }

    @Autowired
    private ProductionFundMapper productionFundMapper;
    @Autowired
    private DyoaRecordMapper dyoaRecordMapper;
    @Autowired
    private PersonalTargetMapper personalTargetMapper;
    @Autowired
    private IPersonalProductionService personalProductionServiceImpl;


    @Override
    public Page<HisMajorOrder> hisMajorPage(HisOrderParam param) {
        checkCookie();
        pageSet(param);
        Page<HisMajorOrder> page = new Page<>();
        try {
            Map<String, Object> map = removeMapKey(BeanUtil.beanToMap(param));
            String respond = HttpKit.sendPost(HISTORY_MAJOR_ORDER_URL, map,COOKIE);
            JSONObject jsonObject = JSON.parseObject(respond);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray dataArray = data.getJSONArray("data");
            if (CollectionUtil.isNotEmpty(dataArray)){
                List<HisMajorOrder> hisMajorOrders = dataArray.toJavaList(HisMajorOrder.class);
                page.setRecords(hisMajorOrders);
                page.setTotal(Long.valueOf(String.valueOf(data.get("total"))));
            }
        } catch (JSONException e) {
            historySystemLogin();
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"远程连接超时，请刷新页面。");
        } catch (Exception e) {
            log.error("远程调用失败.");
            e.printStackTrace();
        }

        return page;
    }

    @Override
    public String getEverCookie() {
        checkCookie();
        return COOKIE;
    }

    private void checkCookie(){
        if (StrUtil.isBlank(COOKIE)){
            historySystemLogin();
        }
    }
    /**
     * 登录原系统获取COOKIE
     * @return
     */
    private void historySystemLogin(){

        try {
            // 创建HttpClient对象
            HttpClient httpClient = new DefaultHttpClient();

            // 创建HttpGet请求对象
            HttpPost httpPost = new HttpPost(HISTORY_LOGIN_URL);

            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);

            // 获取cookie
            String cookies = Arrays.toString(response.getHeaders("Set-Cookie"));
            if (cookies != null) {
                String pattern = "(JSESSIONID)(.*?)( )";
                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(cookies);
                if (m.find()) {
                    COOKIE =  m.group(0).trim().split(";")[0];
                }
            }

            // 关闭连接
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String, Object> removeMapKey(Map param) {
        Set set = param.keySet();

        for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
            Object obj = (Object) iterator.next();
            Object value = (Object) param.get(obj);
            if (value == null || value.equals("") || value.equals("null") || obj.toString().length() == 0) {
                iterator.remove();
            }else {
                if (value instanceof String){
                    try {
                        String xValue = new String (((String) value).getBytes("ISO8859-1"),"UTF-8");
                        param.put(obj,xValue);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        return param;
    }

    private void pageSet(HisOrderParam param){
        param.setLimit(param.getSize());
        param.setStart((param.getCurrent()-1)*param.getLimit());
    }

    /**
     * 获取老系统资产订单
     * @param param 老系统查询参数
     * @return Page<HisAssetsOrder>
     */
    @Override
    public Page<HisAssetsOrder> hisAssetsPage(HisOrderParam param) {
        checkCookie();
        pageSet(param);
        Page<HisAssetsOrder> page = new Page<>();
        try {
            Map<String, Object> map = removeMapKey(BeanUtil.beanToMap(param));
            String respond = HttpKit.sendPost(HISTORY_ASSETS_ORDER_URL, map,COOKIE);
            JSONObject jsonObject = JSON.parseObject(respond);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray dataArray = data.getJSONArray("data");
            if (CollectionUtil.isNotEmpty(dataArray)){
                List<HisAssetsOrder> hisAssetsOrders = dataArray.toJavaList(HisAssetsOrder.class);
                page.setRecords(hisAssetsOrders);
                page.setTotal(Long.valueOf(String.valueOf(data.get("total"))));
            }
        } catch (JSONException e) {
            historySystemLogin();
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"远程连接超时，请刷新页面。");
        } catch (Exception e) {
            log.error("远程调用失败.");
            e.printStackTrace();
        }

        return page;
    }

    @DSTransactional
    @Override
    public void fetchDyoaMajorOrderProduction() {
        List<String> majorOrderIds = dyoaHistoryMapper.selectDyoaMajorOrderIds();
        majorOrderIds.stream().forEach(x->{
            fetchAboutMajor(x);
        });
    }

    @Override
    public void fetchAboutMajor(String id) {
        try {
            //1. 获取订单信息，插入major表。
            Map<String, Object> dyoaMajorOrder = dyoaHistoryMapper.queryMajorOrder(id);
            Long mbsId = this.doCreateMajorOrder(dyoaMajorOrder);
            //2. 同步产品
            Double shouldAmount = (Double) dyoaMajorOrder.get("needPay");
            String code = (String) dyoaMajorOrder.get("code");
            String name = (String) dyoaMajorOrder.get("name");
            this.doCreateMajorProduction(shouldAmount,id, mbsId,code,name);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @DSTransactional
    @Override
    public void fetchDyoaPersonalOrder(){
        Date max = dyoaRecordService.getMaxOrderTime();
        List<String> personalOrderIds = dyoaHistoryMapper.getNewOrderIds(max);
        personalOrderIds.stream().forEach(x->{
            fetchAboutPersonal(x);
        });
    }




    @DSTransactional
    @Override
    public void fetchRealAmountClaimData() {
        Date max = dyoaRecordService.getMaxClaimDate();
        List<String> claimIds = dyoaHistoryMapper.getNewClaimRecordIds(max);
        claimIds.stream().forEach(x->{
            fetchClaimRecord(x);
        });
        //更新订单实收款金额
        List<OrderFund> orderTotalAmount = financeClaimService.queryOrderTotalAmount();
        orderFundService.updateBatchById(orderTotalAmount);

        //分配认领金额到产品收款表
        List<OrderFund> majorOrderFund = orderTotalAmount.stream().filter(x ->
                (x.getBusinessType().equals(MAJOR_BUSINESS.name())|| x.getBusinessType().equals(ASSET_BUSINESS.name())))
                .collect(Collectors.toList());
        majorOrderFund.stream().forEach(x->{
            List<ProductionFund> prods = productionFundService.list(new LambdaQueryWrapper<ProductionFund>()
                    .eq(ProductionFund::getOrderFundId, x.getId()).select(ProductionFund::getProductionType));
            if (CollectionUtil.isNotEmpty(prods)){
                if (prods.size()>1){
                    List<ProductionFund> noStatement = prods.stream().filter(p -> !p.getProductionType().equals(ProductionEnum.STATEMENT.name())).collect(Collectors.toList());
                    if (noStatement.size()>1){
                        productionFundService.update(new LambdaUpdateWrapper<ProductionFund>()
                                .eq(ProductionFund::getOrderFundId,x.getId())
                                .eq(ProductionFund::getProductionType,ProductionEnum.REPORT.name())
                                .set(ProductionFund::getRealAmount,x.getRealAmount()));
                    }else {
                        productionFundService.update(new LambdaUpdateWrapper<ProductionFund>()
                                .eq(ProductionFund::getOrderFundId,x.getId())
                                .eq(ProductionFund::getProductionType,noStatement.get(0).getProductionType())
                                .set(ProductionFund::getRealAmount,x.getRealAmount()));
                    }
                }else{
                    productionFundService.update(new LambdaUpdateWrapper<ProductionFund>()
                            .eq(ProductionFund::getOrderFundId,x.getId()).set(ProductionFund::getRealAmount,x.getRealAmount()));
                }
            }
        });

    }


    private void fetchClaimRecord(String id) {
        try{
            Map<String, Object> resultMap = dyoaHistoryMapper.getNewClaimRecord(id);
            //需要检查老系统最新的认领记录，同样的认领，是否在新系统已经认领过
            String incomeId = (String) resultMap.get("incomeId");
            Long mbsRealFundId = dyoaRecordService.getMbsRealAmountId(incomeId,REAL_AMOUNT.name());
            //检查实收款总金额
            if (mbsRealFundId!=null){
                BigDecimal notClaimAmount = financeRealFundService.getNotClaimAmount(mbsRealFundId);
                if (notClaimAmount.compareTo(BigDecimal.ZERO)==0){
                    return;
                }
            }
            FinanceClaim financeClaim = new FinanceClaim();
            Class<FinanceClaim> fClass = FinanceClaim.class;
            String dyoaId = (String) resultMap.get("id");
            for (Map.Entry<String, String> entry : REAL_AMOUNT_CLAIM_COLUM.entrySet()){
                Object columValue = resultMap.get(entry.getKey());
                if (columValue!=null){
                    String mbsColum = entry.getValue();
                    Field field = fClass.getDeclaredField(mbsColum);
                    field.setAccessible(true);
                    switch (mbsColum){
                        case "realFundId":
                            Long realAmountMbsId = findRealAmountMbsId((String) columValue);
                            if (realAmountMbsId==null){
                                return;
                            }
                            field.set(financeClaim, realAmountMbsId);break;
                        case "orderFundId":
                            Long orderFundMbsId = findOrderFundId((String) columValue);
                            if (orderFundMbsId==null){
                                return;
                            }
                            field.set(financeClaim, orderFundMbsId);break;
                        case "claimUserId":
                            field.set(financeClaim,getMbsUserId((String) columValue));break;
                        case "claimAmount":
                            field.set(financeClaim, BigDecimal.valueOf((Double) columValue));break;
//                        case "claimDatetime":
//                            LocalDate value = DateUtils.parseLocalDateTime((Date) columValue);
//                            field.set(financeClaim, (Date) columValue);break;
                        default:
                            field.set(financeClaim,columValue);
                    }

                }

            }
            Date createdDatetime = (Date) resultMap.get("createdDatetime");
            financeClaim.setCreated(createdDatetime);
            financeClaimService.save(financeClaim);
            //插入同步记录表
            Long mbsId = financeClaim.getId();
            dyoaRecordService.insert(MainBusinessEnum.REAL_AMOUNT_CLAIM, mbsId, dyoaId,createdDatetime);
        }catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


    @DSTransactional
    @Override
    public void fetchRealAmount() {
        Date max = dyoaRecordService.getMaxRealAmountCreatedTime();
        List<String> newRealAmount = dyoaHistoryMapper.getNewRealAmount(max);
        newRealAmount.stream().forEach(x-> {
            fetchReamAmountDetail(x);
        });
    }

    @DSTransactional
    @Override
    public void fetchFinanceInvoiceRecord(){
        List<String> newInvoice = dyoaHistoryMapper.getNewFinanceInvoice();
        newInvoice.stream().forEach(x-> {
            fetchFinanceInvoiceDetail(x);
        });
    }

    private void fetchFinanceInvoiceDetail(String id) {
        try{
            Map<String,Object> resultMap = dyoaHistoryMapper.getInvoiceInfo(id);
            String dyoaId = (String) resultMap.get("id");
            FinanceInvoice invoice = dyoaRecordService.getMbsIdByDyOAiDForInvoice(dyoaId);
            if (invoice==null){
                invoice = new FinanceInvoice();
                Class<FinanceInvoice> fClass = FinanceInvoice.class;
                for (Map.Entry<String, String> entry : FINANCE_INVOICE_COLUM.entrySet()){
                    Object columValue = resultMap.get(entry.getKey());
                    if (columValue!=null){
                        String mbsColum = entry.getValue();
                        Field field = fClass.getDeclaredField(mbsColum);
                        field.setAccessible(true);
                        switch (mbsColum){
                            case "orderFundId":
                                Long orderFundMbsId = findOrderFundId((String) columValue);
                                if (orderFundMbsId==null){
                                    return;
                                }
                                field.set(invoice, orderFundMbsId);
                                break;
                            case "realFundId":
                                Long realFundId = findRealAmountMbsId((String) columValue);
                                if (realFundId==null){
                                    return;
                                }
                                field.set(invoice, realFundId);
                                break;
                            case "planAmount":
                            case "realAmount":
                            case "taxAmount":
                            case "taxRate":
                                field.set(invoice,BigDecimal.valueOf((Double) columValue));
                                break;
                            case "planMakeDate":
                            case "realMakeDate":
                                Timestamp ts = (Timestamp) columValue;
                                field.set(invoice, DateUtils.dateToLocalDate(new Date(ts.getTime())));
                                break;
                            case "makerId":
                                field.set(invoice,getMbsUserId((String) columValue));
                                break;
                            case "applyId":
                                field.set(invoice,getMbsUserId((String) columValue));
                                break;
                            default:
                                field.set(invoice,columValue);
                        }

                    }

                }
                String orderId = (String) resultMap.get("orderId");
                Long orderFundMbsId = findOrderFundId((String) orderId);
                Long productionFunId = getProductionFundIdByOrderFundId(orderFundMbsId);
                invoice.setProductionFundId(productionFunId);
                Date createdDatetime = (Date) resultMap.get("createdDatetime");
                invoice.setCreated(createdDatetime);
                financeInvoiceService.save(invoice);
                //插入同步记录表
                Long mbsId = invoice.getId();
                dyoaRecordService.insert(MainBusinessEnum.FINANCE_INVOICE, mbsId, dyoaId,createdDatetime);
            }else{
                String status = (String) resultMap.get("status");
                if (StrUtil.isNotBlank(status) && "已作废".equals(status)){
                    invoice.setState("已作废");
                    invoice.setReason((String) resultMap.get("reason"));
                    financeInvoiceService.update(invoice);
                }
                String state = invoice.getState();
                if (StrUtil.isNotBlank(state) && "待开票".equals(state) && StrUtil.isNotBlank(status) && "已开票".equals(status)){
                    invoice.setState("已开票");
                    Timestamp ts = (Timestamp) resultMap.get("realDate");
                    invoice.setRealMakeDate(DateUtils.dateToLocalDate(new Date(ts.getTime())));
                    invoice.setRealAmount(BigDecimal.valueOf((Double) resultMap.get("realMoney")));
                    invoice.setTicketNo((String) resultMap.get("ticketNo"));
                    invoice.setMakerId(getMbsUserId((String) resultMap.get("invoiceEmp")));
                    financeInvoiceService.update(invoice);
                }
            }

        }catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private Long getProductionFundIdByOrderFundId(Long orderFundMbsId) {
        Map<Long, Long> collect = productionFundService.getProductionFundIdByOrderFundId().stream().collect(Collectors.toMap(ProductionFund::getOrderFundId, BaseEntity::getId));
        return collect.get(orderFundMbsId);
    }


    @DSTransactional
    @Override
    public void fetchAssetsOrderProduction() {
        List<String> assetsOrderIds = dyoaHistoryMapper.selectDyoaAssetsOrderIds();
        assetsOrderIds.stream().forEach(x->{
            fetchAboutAssets(x);
        });
    }

    private void fetchAboutAssets(String id) {
        try {
            //1. 获取订单信息，插入assets表。
            Map<String, Object> dyoaAssetsOrder = dyoaHistoryMapper.queryAssetsOrder(id);
            Long mbsId = this.doCreateAssetsOrder(dyoaAssetsOrder);
            //2. 同步产品
            Double shouldAmount = (Double) dyoaAssetsOrder.get("needPay");
            String code = (String) dyoaAssetsOrder.get("code");
            String name = (String) dyoaAssetsOrder.get("name");
            this.doCreateAssetsProduction(shouldAmount,id, mbsId,code,name);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private Long doCreateAssetsOrder(Map<String, Object> dyoaAssetsOrder) throws NoSuchFieldException, IllegalAccessException {
        String dyoaId = (String) dyoaAssetsOrder.get("id");
        String managerName = (String) dyoaAssetsOrder.get("managerName");

        DyoaRecord record = dyoaRecordService.getOne(new LambdaQueryWrapper<DyoaRecord>().eq(DyoaRecord::getMbsType, ASSETS_ORDER.name()).eq(DyoaRecord::getDyoaId, dyoaId));
        if (record != null){
            //更新项目负责人
            Long mbsOrderId = record.getMbsId();
            if (StrUtil.isNotEmpty(managerName)){
                Assets assets = assetsService.getOne(new LambdaQueryWrapper<Assets>().eq(BaseEntity::getId, mbsOrderId).select(BaseEntity::getId, Assets::getPrincipalId));
                if (assets.getPrincipalId()==null){
                    assetsService.update(new LambdaUpdateWrapper<Assets>().set(Assets::getPrincipalId,getMbsUserId(managerName)).eq(BaseEntity::getId, mbsOrderId));
                    log.info("项目负责人被更新 mbsId: {}",mbsOrderId);
                }
            }
            return mbsOrderId;
        }
        Assets assets = new Assets();
        Class<Assets> aClass = Assets.class;
        for (Map.Entry<String, String> entry : ASSETS_ORDER_COLUM.entrySet()){
            Object columValue = dyoaAssetsOrder.get(entry.getKey());
            if (columValue!=null){
                String mbsColum = entry.getValue();
                Field field = aClass.getDeclaredField(mbsColum);
                field.setAccessible(true);
                switch (mbsColum){
                    case "allotType":
                        field.set(assets,(Boolean) columValue?ASSIGN:BY_TURNS);break;
                    case "clientManagerId":
                    case "principalId":
                        field.set(assets,getMbsUserId((String) columValue));break;
                    case "departmentId":
                        field.set(assets,getMbsDepartmentId((String) columValue));break;
                    case "clienteleSubId":
                    case "clienteleId":
                    case "terminalClienteleId":
                        field.set(assets, getCompanyId((String) columValue));break;
                    case "terminalClienteleContactId":
                    case "clienteleContactId":
                        field.set(assets, getCompanyLinkmanId((String) columValue));break;
                    default:
                        field.set(assets,columValue);
                }

            }
        }
        assets.setCreated((Date) dyoaAssetsOrder.get("orderTime"));
        assetsServiceImpl.save(assets);
        //插入同步记录表
        Long mbsId = assets.getId();
        dyoaRecordService.insert(MainBusinessEnum.ASSETS_ORDER, mbsId, dyoaId,null);
        return mbsId;
    }

    private void doCreateAssetsProduction(Double shouldAmount, String id, Long mbsId, String code, String name) throws NoSuchFieldException, IllegalAccessException {
        //创建订单收款记录
        OrderFund orderFund = orderFundService.getOne(new LambdaQueryWrapper<OrderFund>().eq(OrderFund::getBusinessType, ASSET_BUSINESS.name())
                .eq(OrderFund::getBusinessId, mbsId).eq(OrderFund::getOrderId, code));
        if (orderFund==null){
            orderFund = new OrderFund();
            orderFund.setBusinessId(mbsId);
            orderFund.setBusinessType(ASSET_BUSINESS.name());
            orderFund.setOrderId(code);
            orderFund.setOrderName(name);
            orderFund.setShouldAmount(BigDecimal.valueOf(shouldAmount==null?0d:shouldAmount));
            orderFundService.save(orderFund);
        }
        List<HisAssetsProduction> assetsProductions = dyoaHistoryMapper.queryAssetsProduction(id);
        //创建产品收款记录
        if (CollectionUtil.isNotEmpty(assetsProductions)){
            for (HisAssetsProduction production :assetsProductions){
                if (StrUtil.isNotBlank(production.getPId())){
                    AssetsProduction assetsProduction = new AssetsProduction();
                    assetsProduction.setBusinessId(mbsId);
                    for (Map.Entry<String, String> entry : ASSETS_PRODUCTION_COLUM.entrySet()){
                        Field field = HisAssetsProduction.class.getDeclaredField(entry.getKey());
                        field.setAccessible(true);
                        Object value = field.get(production);
                        if (value!=null){
                            String mbsColum = entry.getValue();
                            Field xFiled = AssetsProduction.class.getDeclaredField(mbsColum);
                            xFiled.setAccessible(true);
                            switch (mbsColum){
                                case "productionType":
                                    String productionType = getProductionType((String) value);
                                    xFiled.set(assetsProduction, productionType);
                                    break;
                                case "createProductionDate":
                                    Date ts = (Date) value;
                                    LocalDate value1 = DateUtils.dateToLocalDate(ts);
                                    System.out.println("value1===>" + value1);
                                    if (value1!=null){
                                        xFiled.set(assetsProduction, value1);
                                    }
                                    break;
                                default:
                                    xFiled.set(assetsProduction,value);
                                    break;
                            }
                        }

                    }
                    if (assetsProduction.getProductionType().equals(ProductionEnum.STATEMENT.name())){
                        assetsProduction.setProductionNo(production.getYjsReportNo());
                    }else{
                        assetsProduction.setProductionNo(production.getReportNo());
                    }
                    AssetsProduction mp = assetsProductionService.getOne(new LambdaQueryWrapper<AssetsProduction>().eq(AssetsProduction::getBusinessId, mbsId)
                            .eq(AssetsProduction::getProductionNo, assetsProduction.getProductionNo()).eq(AssetsProduction::getProductionType, assetsProduction.getProductionType()));
                    //插入产品记录
                    if (mp==null){
                        //查询有没有产品号，如果没有就不创建产品和产品收款
                        if (StrUtil.isNotBlank(assetsProduction.getProductionNo())){
                            assetsProductionService.save(assetsProduction);
                            //创建产品收款记录
                            ProductionFund productionFund = new ProductionFund();
                            productionFund.setBusinessId(mbsId);
                            productionFund.setBusinessType(ASSET_BUSINESS.name());
                            productionFund.setProductionNo(assetsProduction.getProductionNo());
                            productionFund.setProductionType(assetsProduction.getProductionType());
                            productionFund.setOrderFundId(orderFund.getId());
                            productionFund.setStandardAmount(production.getStandardPrice());
                            productionFund.setProductionShouldAmount(orderFund.getShouldAmount());
                            productionFundService.save(productionFund);
                        }

                    }
                }
            }
        }

    }


    private void fetchReamAmountDetail(String id){
        try{
            Map<String,Object> resultMap = dyoaHistoryMapper.getRealAmountInfo(id);
            FinanceRealFund realFund = new FinanceRealFund();
            Class<FinanceRealFund> fClass = FinanceRealFund.class;
            String dyoaId = (String) resultMap.get("id");
            for (Map.Entry<String, String> entry : REAL_AMOUNT_COLUM.entrySet()){
                Object columValue = resultMap.get(entry.getKey());
                if (columValue!=null){
                    String mbsColum = entry.getValue();
                    Field field = fClass.getDeclaredField(mbsColum);
                    field.setAccessible(true);
                    switch (mbsColum){
                        case "payDatetime":
                            field.set(realFund,DateUtils.dateToLocalDate((Date) columValue));break;
                        case "creatorId":
                            field.set(realFund,getMbsUserId((String) columValue));break;
                        case "amount":
                            field.set(realFund, BigDecimal.valueOf((Double) columValue));break;
                        default:
                            field.set(realFund,columValue);
                    }

                }
            }
            Date createdDatetime = (Date) resultMap.get("createdDatetime");
            realFund.setCreated(createdDatetime);
            financeRealFundService.save(realFund);
            //插入同步记录表
            Long mbsId = realFund.getId();
            dyoaRecordService.insert(MainBusinessEnum.REAL_AMOUNT, mbsId, dyoaId,createdDatetime);
        }catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    private void fetchAboutPersonal(String dyoaId) {
        Map<String, Object> dyoaPersonalOrder = dyoaHistoryMapper.queryPersonalOrder(dyoaId);
        try {
            DyoaRecord record = dyoaRecordService.getOne(new LambdaQueryWrapper<DyoaRecord>()
                    .eq(DyoaRecord::getDyoaId, dyoaId).eq(DyoaRecord::getMbsType, "PERSONAL_ORDER"));
            Long mbsId = null;
            if (record!=null){
                mbsId = record.getMbsId();
            }else{
                //1.插入personal表
                Personal personal = this.doCreatePersonalOrder(dyoaPersonalOrder);
                //2.创建订单收款记录
                this.doCreatedOrderFund(personal);
                mbsId = personal.getId();
            }
            PersonalTarget target = new PersonalTarget();
            target.setPersonalId(mbsId);
            Object locations = dyoaPersonalOrder.get("locations");
            target.setLocation(locations==null?"": (String) locations);
            Object area = dyoaPersonalOrder.get("area");
            target.setAcreage(area==null?null:BigDecimal.valueOf((Double) area));
            Object money = dyoaPersonalOrder.get("money");
            target.setAmount(money==null?null:BigDecimal.valueOf((Double) money));
            Object price = dyoaPersonalOrder.get("price");
            target.setPrice(price==null?null:BigDecimal.valueOf((Double) price));
            personalTargetService.save(target);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private void doCreatedOrderFund(Personal personal) {
        //创建订单收款记录
        OrderFund orderFund = new OrderFund();
        orderFund.setBusinessId(personal.getId());
        orderFund.setBusinessType(PERSONAL_BUSINESS.name());
        orderFund.setOrderId(personal.getOrderId());
        orderFund.setOrderName(personal.getLocation());
        orderFundService.save(orderFund);
    }

    private Personal doCreatePersonalOrder(Map<String, Object> dyoaPersonalOrder) throws NoSuchFieldException, IllegalAccessException {
        Personal personal = new Personal();
        Class<Personal> mClass = Personal.class;
        String dyoaId = (String) dyoaPersonalOrder.get("id");
        for (Map.Entry<String, String> entry : PERSONAL_ORDER_COLUM.entrySet()){
            Object columValue = dyoaPersonalOrder.get(entry.getKey());
            if (columValue!=null){
                String mbsColum = entry.getValue();
                Field field = mClass.getDeclaredField(mbsColum);
                field.setAccessible(true);
                switch (mbsColum){
                    case "purpose":
                    case "credentials":
                        field.set(personal,covertData((String) columValue,mbsColum));break;
                    case "clientManagerId":
                    case "outwardStaff":
                    case "inwardStaff":
                    case "pricingStaff":
                        field.set(personal,getMbsUserId((String) columValue));break;
                    case "loanLimit":
                        field.set(personal, BigDecimal.valueOf((Double) columValue));break;
                    case "loanPeriod":
                        field.set(personal, BigDecimal.valueOf((Integer) columValue));break;
                    case "clienteleSubId":
                    case "clienteleId":
                        field.set(personal, getCompanyId((String) columValue));break;
                    case "terminalClienteleId":
                        String terminalType = (String) dyoaPersonalOrder.get("terminalType");
                        if ("企业".equals(terminalType)){
                            field.set(personal, getCompanyId((String) columValue));
                        }else {
                            field.set(personal, getCompanyLinkmanId((String) columValue));
                        }
                        break;
                    case "terminalClienteleContactId":
                    case "clienteleContactId":
                        field.set(personal, getCompanyLinkmanId((String) columValue));break;
                    default:
                        field.set(personal,columValue);
                }

            }
        }
        Date createdDatetime = (Date) dyoaPersonalOrder.get("createdDatetime");
        personal.setCreated(createdDatetime);
        personalService.save(personal);
        //插入同步记录表
        Long mbsId = personal.getId();
        dyoaRecordService.insert(MainBusinessEnum.PERSONAL_ORDER, mbsId, dyoaId,createdDatetime);
        return personal;
    }

    private static String covertData(String columValue, String mbsColum) {
        List<String> list = Arrays.asList(columValue.split(","));
        List<String> ret = new ArrayList<>();
        if (mbsColum.equals("purpose")){
            list.stream().forEach(x->{
                if (x.equals("住宅")){
                    ret.add("HOUSE");
                }else if (x.equals("商业")){
                    ret.add("BUSINESS");
                }else if (x.equals("办公")){
                    ret.add("OFFICE");
                }else if (x.equals("工业")){
                    ret.add("INDUSTRIAL");
                }else if (x.equals("其他")){
                    ret.add("OTHER");
                }
            });
        }
        if (mbsColum.equals("credentials")){
            list.stream().forEach(x->{
                if (x.equals("房产证")){
                    ret.add("HOUSE_CERTIFICATE");
                }else if (x.equals("国土证")){
                    ret.add("LAND_CERTIFICATE");
                }else if (x.equals("不动产权证")){
                    ret.add("IMMOVABLE_CERTIFICATE");
                }
            });
        }
        return JSON.toJSONString(ret);
    }

    private Long getCompanyId(String columValue) {
        List<CustomerCompany> list = customerCompanyService.list(new LambdaQueryWrapper<CustomerCompany>().eq(CustomerCompany::getName, columValue)
                .select(BaseEntity::getId));
        if (CollectionUtil.isNotEmpty(list)){
            return list.get(0).getId();
        }
        return null;
    }

    private Long getCompanyLinkmanId(String columValue) {
        List<CustomerLinkman> list = customerLinkmanService.list(new LambdaQueryWrapper<CustomerLinkman>().eq(CustomerLinkman::getName, columValue)
                .select(BaseEntity::getId));
        if (CollectionUtil.isNotEmpty(list)){
            return list.get(0).getId();
        }
        return null;
    }

    private String toJsonString(String columValue) {
        List<String> list = Arrays.asList(columValue.split(","));
        return JSON.toJSONString(list);
    }

    private void doCreateMajorProduction(Double shouldAmount ,String id,Long majorId,String code,String name) throws NoSuchFieldException, IllegalAccessException {

        //创建订单收款记录
        OrderFund orderFund = orderFundService.getOne(new LambdaQueryWrapper<OrderFund>().eq(OrderFund::getBusinessType, MAJOR_BUSINESS.name())
                .eq(OrderFund::getBusinessId, majorId).eq(OrderFund::getOrderId, code));
        if (orderFund==null){
            orderFund = new OrderFund();
            orderFund.setBusinessId(majorId);
            orderFund.setBusinessType(MAJOR_BUSINESS.name());
            orderFund.setOrderId(code);
            orderFund.setOrderName(name);
            orderFund.setShouldAmount(BigDecimal.valueOf(shouldAmount==null?0d:shouldAmount));
            orderFundService.save(orderFund);
        }

        List<HisMajorProduction> majorProductions = dyoaHistoryMapper.queryMajorProduction(id);
        //创建产品收款记录
        if (CollectionUtil.isNotEmpty(majorProductions)){

            for (HisMajorProduction production :majorProductions){
                if (StrUtil.isNotBlank(production.getPId())){
                    MajorProduction majorProduction = new MajorProduction();
                    majorProduction.setMajorId(majorId);
                    for (Map.Entry<String, String> entry : MAJOR_PRODUCTION_COLUM.entrySet()){
                        Field field = HisMajorProduction.class.getDeclaredField(entry.getKey());
                        field.setAccessible(true);
                        Object value = field.get(production);
                        if (value!=null){
                            String mbsColum = entry.getValue();
                            Field xFiled = MajorProduction.class.getDeclaredField(mbsColum);
                            xFiled.setAccessible(true);
                            switch (mbsColum){
                                case "production":
                                    String productionType = getProductionType((String) value);
                                    xFiled.set(majorProduction, productionType);
                                    break;
                                case "delivery":
                                    xFiled.set(majorProduction,production.getConfirmTime()!=null);
                                    break;
                                case "signatory":
                                    xFiled.set(majorProduction,getMbsUserIds((String) value));
                                    break;
                                case "valueTiming":
                                case "saveFileDate":
                                case "deliveryDate":
                                    xFiled.set(majorProduction,DateUtils.dateToLocalDate((Date) value));
                                    break;
                                case "repertoryState":
                                    String repertoryState = (String) value;
                                    xFiled.set(majorProduction,repertoryState.equals("OUT"));
                                    break;
                                default:
                                    xFiled.set(majorProduction,value);
                                    break;
                            }
                        }

                    }
                    MajorProduction mp = majorProductionService.getOne(new LambdaQueryWrapper<MajorProduction>().eq(MajorProduction::getMajorId, majorId)
                            .eq(MajorProduction::getReportNo, majorProduction.getReportNo()).eq(MajorProduction::getProduction, majorProduction.getProduction()));
                    //插入产品记录
                    if (mp==null){
                        //查询有没有产品号，如果没有就不创建产品和产品收款
                        if (StrUtil.isNotBlank(majorProduction.getReportNo())){
                            majorProductionService.save(majorProduction);
                            //创建产品收款记录
                            ProductionFund productionFund = new ProductionFund();
                            productionFund.setBusinessId(majorId);
                            productionFund.setBusinessType(MAJOR_BUSINESS.name());
                            productionFund.setProductionNo(production.getReportNo());
                            productionFund.setProductionType(getProductionType(production.getPType()));
                            productionFund.setOrderFundId(orderFund.getId());
                            productionFund.setStandardAmount(production.getStandardPrice());
                            productionFundService.save(productionFund);
                        }

                    }
                }
            }
        }

    }

    private Long findRealAmountMbsId(String columValue) {

        Map<String, Long> collect = dyoaRecordService.list(new LambdaQueryWrapper<DyoaRecord>().select(DyoaRecord::getMbsId, DyoaRecord::getDyoaId)
                .eq(DyoaRecord::getMbsType, REAL_AMOUNT.name())).stream().collect(Collectors.toMap(DyoaRecord::getDyoaId, DyoaRecord::getMbsId));
        return collect.get(columValue);
    }

    private String getProductionType(String value) {
        if (value.contains(ProductionEnum.REPORT.getMsg())){
            return ProductionEnum.REPORT.name();
        }
        if (value.contains(ProductionEnum.STATEMENT.getMsg())){
            return ProductionEnum.STATEMENT.name();
        }
        return ProductionEnum.LETTER.name();
    }

    private Long doCreateMajorOrder(Map<String,Object> dyMajorOrder) throws NoSuchFieldException, IllegalAccessException {
        String dyoaId = (String) dyMajorOrder.get("id");
        String managerName = (String) dyMajorOrder.get("managerName");

        DyoaRecord record = dyoaRecordService.getOne(new LambdaQueryWrapper<DyoaRecord>().eq(DyoaRecord::getMbsType, MAJOR_ORDER.name()).eq(DyoaRecord::getDyoaId, dyoaId));
        if (record != null){
            //更新项目负责人
            Long mbsOrderId = record.getMbsId();
            if (StrUtil.isNotEmpty(managerName)){
                Major major = majorServiceImpl.getOne(new LambdaQueryWrapper<Major>().eq(BaseEntity::getId, mbsOrderId).select(BaseEntity::getId, Major::getPrincipalId));
                if (major.getPrincipalId()==null){
                    majorServiceImpl.update(new LambdaUpdateWrapper<Major>().set(Major::getPrincipalId,getMbsUserId(managerName)).eq(BaseEntity::getId, mbsOrderId));
                    log.info("项目负责人被更新 mbsId: {}",mbsOrderId);
                }
            }
            return mbsOrderId;
        }
        Major major = new Major();
        Class<Major> mClass = Major.class;
        for (Map.Entry<String, String> entry : MAJOR_ORDER_COLUM.entrySet()){
            Object columValue = dyMajorOrder.get(entry.getKey());
            if (columValue!=null){
                String mbsColum = entry.getValue();
                Field field = mClass.getDeclaredField(mbsColum);

                field.setAccessible(true);
                switch (mbsColum){
                    case "allotType":
                        field.set(major,(Boolean) columValue?ASSIGN:BY_TURNS);break;
                    case "financial":
                        field.set(major,columValue.equals("FINANCE"));break;
                    case "clientManagerId":
                        field.set(major,getMbsUserId((String) columValue));break;
                    case "principalId":
                        field.set(major,getMbsUserId((String) columValue));break;
                    case "departmentId":
                        field.set(major,getMbsDepartmentId((String) columValue));break;
                    case "loanLimit":
                    case "loanPeriod":
                        field.set(major, BigDecimal.valueOf((Double) columValue));break;
                    case "members":
                        field.set(major,getMbsUserIds((String) columValue));break;
                    case "clienteleSubId":
                    case "clienteleId":
                    case "terminalClienteleId":
                        field.set(major, getCompanyId((String) columValue));break;
                    case "terminalClienteleContactId":
                    case "clienteleContactId":
                        field.set(major, getCompanyLinkmanId((String) columValue));break;
                    default:
                        field.set(major,columValue);
                }

            }
        }
        major.setCreated((Date) dyMajorOrder.get("createdDatetime"));
        majorServiceImpl.save(major);
        //插入同步记录表
        Long mbsId = major.getId();
        dyoaRecordService.insert(MainBusinessEnum.MAJOR_ORDER, mbsId, dyoaId,null);
        return mbsId;

    }

    private Long getMbsUserId(String userName){
        if (CollectionUtil.isEmpty(users)){
            List<User> list = userService.list(new LambdaQueryWrapper<User>().select(BaseEntity::getId, User::getName));
            users = list.stream().collect(Collectors.toMap(User::getName, User::getId));
        }

        Long clientManagerId = users.get(userName);
        return clientManagerId==null?1L:clientManagerId;
    }

    private Long getMbsDepartmentId(String departmentName){
        if (CollectionUtil.isEmpty(departments)){
            List<Department> list = departmentService.list(new LambdaQueryWrapper<Department>().select(BaseEntity::getId, Department::getName));
            departments = list.stream().collect(Collectors.toMap(Department::getName, Department::getId));
        }
        if (departmentName.equals("复审部")){
            departmentName = "综合部";
        }
        if (departmentName.equals("土地综合部")){
            departmentName = "土地规划与评估事业部";
        }
        if (departmentName.equals("资产事业部") ||departmentName.equals("事业部")  ){
            departmentName = "资产评估事业部";
        }
        if (departmentName.equals("资产评估1组")){
            departmentName = "资产评估一组";
        }
        if (departmentName.equals("资产评估2组")){
            departmentName = "资产评估二组";
        }
        if (departmentName.equals("资产评估3组")){
            departmentName = "资产评估三组";
        }
        return departments.get(departmentName);
    }

    private String getMbsUserIds(String userNames){
        List<Long> userIds = new ArrayList<>();
        Arrays.asList(userNames.split(",")).forEach(userName -> {
            Long mbsUserId = getMbsUserId(userName.replaceAll(" ",""));
            userIds.add(mbsUserId);
        });
        return JSON.toJSONString(userIds);
    }

    private Long findOrderFundId(String columValue){
        Map<String, Long> collect = dyoaRecordService.selectOrderFundIdByDyoaOrderId().stream().collect(Collectors.toMap(DyoaRecord::getDyoaId, DyoaRecord::getMbsId));
        return collect.get(columValue);
    }

    private Long findProductionFundId(String columValue) {
        Map<String, Long> collect = productionFundService.selectProductionFundIdByDyoaReportNo().stream().collect(Collectors.toMap(ProductionFund::getProductionNo, ProductionFund::getId));
        return collect.get(columValue);
    }

//    private Long getMbsWorkFlows(String flowCode){
//        if (CollectionUtil.isEmpty(workFlows)){
//            List<WorkFlow> list = workFlowService.list(new LambdaQueryWrapper<WorkFlow>().select(BaseEntity::getId, WorkFlow::getCode));
//            workFlows = list.stream().collect(Collectors.toMap(WorkFlow::getCode, WorkFlow::getId));
//        }
//        return workFlows.get(flowCode);
//    }
//
//    private Long getMbsWorkNodes(String nodeName){
//        if (CollectionUtil.isEmpty(majorBusinessNodes)){
//            List<WorkNode> list = workNodeService.list(new LambdaQueryWrapper<WorkNode>().select(BaseEntity::getId, WorkNode::getName)
//                    .eq(WorkNode::getFlowId,getMbsWorkFlows(MAJOR_BUSINESS.name())));
//            majorBusinessNodes = list.stream().collect(Collectors.toMap(WorkNode::getName, WorkNode::getId));
//        }
//        return majorBusinessNodes.get(nodeName);
//    }



//    private Long doCreateMajorInstanceNode(Long businessId,String dyoaNodeName,List<MajorProduction> productions){
//        String businessSubId = null;
//        String businessMinId = null;
//        if (CollectionUtil.isNotEmpty(productions)){
//            List<MajorProduction> statement = productions.stream().filter(x -> x.getProduction().equals(ProductionEnum.STATEMENT.name())).collect(Collectors.toList());
//            if (CollectionUtil.isNotEmpty(statement)){
//                businessSubId = statement.get(0).getReportNo();
//            }
//            List<MajorProduction> report = productions.stream().filter(x -> x.getProduction().equals(ProductionEnum.REPORT.name())).collect(Collectors.toList());
//            if (CollectionUtil.isNotEmpty(report)){
//                businessMinId = report.get(0).getReportNo();
//            }
//            List<MajorProduction> letter = productions.stream().filter(x -> x.getProduction().equals(ProductionEnum.LETTER.name())).collect(Collectors.toList());
//            if (CollectionUtil.isNotEmpty(letter)){
//                businessMinId = letter.get(0).getReportNo();
//            }
//
//        }
//        Long nodeId = getMbsWorkNodes(dyoaNodeName);
//        Long flowId = getMbsWorkFlows(MAJOR_BUSINESS.name());
//        WorkFlowNodeInstance instance = new WorkFlowNodeInstance();
//        instance.setFlowId(flowId);
//        instance.setBusinessId(businessId);
//        instance.setBusinessSubId(businessSubId);
//        instance.setBusinessMinId(businessMinId);
//        instance.setNodeId(nodeId);
//        instance.setBusinessType(MAJOR_BUSINESS.name());
//        instance.setSequence(0);
//        instance.setState(PENDING.name());
//        workFlowNodeInstanceService.add(instance);
//        return instance.getId();
//    }

//    private void doCreateNodeTask(Long instanceNodeId, String dyoaNodeName,String dyoaHandlerName) {
//        Long nodeId = getMbsWorkNodes(dyoaNodeName);
//        WorkNodeTask task = workNodeTaskService.getOne(new LambdaQueryWrapper<WorkNodeTask>().eq(WorkNodeTask::getNodeId, nodeId)
//                .eq(WorkNodeTask::getVersion, LATEST.name()).select(BaseEntity::getId));
//        WorkTaskRecord workTaskRecord = new WorkTaskRecord();
//        workTaskRecord.setInstanceId(instanceNodeId);
//        workTaskRecord.setTaskId(task.getId());
//        workTaskRecord.setHandlerId(getMbsUserId(dyoaHandlerName));
//        workTaskRecordService.save(workTaskRecord);
//    }


    //    public List<MajorProduction> doCreateMajorTarget(String targetType, String id,Long majorId) throws NoSuchFieldException, IllegalAccessException {
//        List<MajorTarget> mts = new ArrayList<>();
//        List<MajorProduction> mps = new ArrayList<>();
//        if ("土地".equals(targetType)){
//           List<HisMajorTarget> majorLandTarget = dyoaHistoryMapper.queryMajorLandTarget(id);
//            Map<String, List<HisMajorTarget>> collect = majorLandTarget.stream()
//                    .collect(Collectors.groupingBy(HisMajorTarget::getTId));
//            for (Map.Entry<String, List<HisMajorTarget>> target : collect.entrySet()){
//                    MajorTarget majorTarget = new MajorTarget();
//                    majorTarget.setTargetType("土地");
//                    majorTarget.setMajorId(majorId);
//                    for (Map.Entry<String, String> entry : MAJOR_TARGET_LAND_COLUM.entrySet()){
//                        Field field = HisMajorTarget.class.getDeclaredField(entry.getKey());
//                        field.setAccessible(true);
//                        Object value = field.get(target.getValue().get(0));
//                        if (value!=null){
//                            String mbsColum = entry.getValue();
//                            Field xFiled = MajorTarget.class.getDeclaredField(mbsColum);
//                            xFiled.setAccessible(true);
//                            switch (mbsColum){
//                                case "principalId":
//                                    xFiled.set(majorTarget,getMbsUserId((String) value));
//                                    break;
//                                case "siteIds":
//                                    xFiled.set(majorTarget,getMbsUserIds((String) value));
//                                    break;
//                                case "evaluateMethods":
//                                    String methods = (String) value;
//                                    xFiled.set(majorTarget,JSON.toJSONString(Arrays.asList(methods.split(","))));
//                                    break;
//                                default:
//                                    xFiled.set(majorTarget,value);
//                            }
//                        }
//                    }
//                    mts.add(majorTarget);
//                    //是否有产品
//                    for (HisMajorTarget production :target.getValue()){
//                        if (StrUtil.isNotBlank(production.getPId())){
//                            MajorProduction majorProduction = new MajorProduction();
//                            majorProduction.setMajorId(majorId);
//                            for (Map.Entry<String, String> entry : MAJOR_PRODUCTION_COLUM.entrySet()){
//                                Field field = HisMajorTarget.class.getDeclaredField(entry.getKey());
//                                field.setAccessible(true);
//                                Object value = field.get(production);
//                                if (value!=null){
//                                    String mbsColum = entry.getValue();
//                                    Field xFiled = MajorProduction.class.getDeclaredField(mbsColum);
//                                    xFiled.setAccessible(true);
//                                    switch (mbsColum){
//                                        case "production":
//                                            String productionType = getProductionType((String) value);
//                                            xFiled.set(majorProduction, productionType);
//                                            if (ProductionEnum.STATEMENT.name().equals(productionType)){
//                                                majorTarget.setStatementNo(production.getReportNo());
//                                            }
//                                            if (ProductionEnum.REPORT.name().equals(productionType)){
//                                                majorTarget.setReportNo(production.getReportNo());
//                                            }
//                                            if (ProductionEnum.LETTER.name().equals(productionType)){
//                                                majorTarget.setLetterNo(production.getReportNo());
//                                            }
//
//                                            break;
//                                        case "delivery":
//                                            xFiled.set(majorProduction,production.getConfirmTime()!=null);
//                                            break;
//                                        case "signatory":
//                                            xFiled.set(majorProduction,getMbsUserIds((String) value));
//                                            break;
//                                        case "valueTiming":
//                                        case "saveFileDate":
//                                        case "deliveryDate":
//                                            xFiled.set(majorProduction,DateUtils.dateToLocalDate((Date) value));
//                                            break;
//                                        case "repertoryState":
//                                            String repertoryState = (String) value;
//                                            xFiled.set(majorProduction,repertoryState.equals("OUT"));
//                                            break;
//                                        default:
//                                            xFiled.set(majorProduction,value);
//                                            break;
//                                    }
//                                }
//                            }
//                            mps.add(majorProduction);
//                        }
//                    }
//
//            }
//
//        }
//        if ("房地产".equals(targetType)){
//            List<HisMajorTarget> majorHouseTarget = dyoaHistoryMapper.queryMajorHouseTarget(id);
//            Map<String, List<HisMajorTarget>> collect = majorHouseTarget.stream()
//                    .collect(Collectors.groupingBy(HisMajorTarget::getTId));
//            for (Map.Entry<String, List<HisMajorTarget>> target : collect.entrySet()){
//                MajorTarget majorTarget = new MajorTarget();
//                majorTarget.setTargetType("房地产");
//                majorTarget.setMajorId(majorId);
//                for (Map.Entry<String, String> entry : MAJOR_TARGET_HOUSE_COLUM.entrySet()){
//                    Field field = HisMajorTarget.class.getDeclaredField(entry.getKey());
//                    field.setAccessible(true);
//                    Object value = field.get(target.getValue().get(0));
//                    if (value!=null){
//                        String mbsColum = entry.getValue();
//                        Field xFiled = MajorTarget.class.getDeclaredField(mbsColum);
//                        xFiled.setAccessible(true);
//                        switch (mbsColum){
//                            case "principalId":
//                                xFiled.set(majorTarget,getMbsUserId((String) value));
//                                break;
//                            case "siteIds":
//                                xFiled.set(majorTarget,getMbsUserIds((String) value));
//                                break;
//                            case "evaluateMethods":
//                            case "housePurpose":
//                                String methods = (String) value;
//                                xFiled.set(majorTarget,JSON.toJSONString(Arrays.asList(methods.split(","))));
//                                break;
//                            default:
//                                xFiled.set(majorTarget,value);
//                        }
//                    }
//                }
//                mts.add(majorTarget);
//                //是否有产品
//                for (HisMajorTarget production :target.getValue()){
//                    if (StrUtil.isNotBlank(production.getPId())){
//                        MajorProduction majorProduction = new MajorProduction();
//                        majorProduction.setMajorId(majorId);
//                        for (Map.Entry<String, String> entry : MAJOR_PRODUCTION_COLUM.entrySet()){
//                            Field field = HisMajorTarget.class.getDeclaredField(entry.getKey());
//                            field.setAccessible(true);
//                            Object value = field.get(production);
//                            if (value!=null){
//                                String mbsColum = entry.getValue();
//                                Field xFiled = MajorProduction.class.getDeclaredField(mbsColum);
//                                xFiled.setAccessible(true);
//                                switch (mbsColum){
//                                    case "production":
//                                        String productionType = getProductionType((String) value);
//                                        xFiled.set(majorProduction, productionType);
//                                        if (ProductionEnum.STATEMENT.name().equals(productionType)){
//                                            majorTarget.setStatementNo(production.getReportNo());
//                                        }
//                                        if (ProductionEnum.REPORT.name().equals(productionType)){
//                                            majorTarget.setReportNo(production.getReportNo());
//                                        }
//                                        if (ProductionEnum.LETTER.name().equals(productionType)){
//                                            majorTarget.setLetterNo(production.getReportNo());
//                                        }
//
//                                        break;
//                                    case "delivery":
//                                        xFiled.set(majorProduction,production.getConfirmTime()!=null);
//                                        break;
//                                    case "signatory":
//                                        xFiled.set(majorProduction,getMbsUserIds((String) value));
//                                        break;
//                                    case "valueTiming":
//                                    case "saveFileDate":
//                                    case "deliveryDate":
//                                        xFiled.set(majorProduction,DateUtils.dateToLocalDate((Date) value));
//                                        break;
//                                    case "repertoryState":
//                                        String repertoryState = (String) value;
//                                        xFiled.set(majorProduction,repertoryState.equals("OUT"));
//                                        break;
//                                    default:
//                                        xFiled.set(majorProduction,value);
//                                        break;
//                                }
//                            }
//                        }
//                        mps.add(majorProduction);
//                    }
//                }
//
//            }
//        }
//        if (CollectionUtil.isNotEmpty(mts)){
//            majorTargetService.saveBatch(mts);
//        }
//        if (CollectionUtil.isNotEmpty(mps)){
//            majorProductionService.saveBatch(mps);
//            //更新报价反馈
//            List<PriceFeedbackDTO> feedbackDTOS = new ArrayList<>();
//            String statementNo = null;
//            for (MajorProduction majorProduction : mps){
//                if (majorProduction.getProduction().equals(ProductionEnum.STATEMENT.name())){
//                    PriceFeedbackDTO feedbackDTO = new PriceFeedbackDTO();
//                    feedbackDTO.setProduction(Arrays.asList(ProductionEnum.STATEMENT));
//                    feedbackDTO.setMajorId(majorId);
//                    feedbackDTO.setPrinting(majorProduction.getPrintTimes());
//                    statementNo = majorProduction.getReportNo();
//                    feedbackDTOS.add(feedbackDTO);
//                }
//                if (majorProduction.getProduction().equals(ProductionEnum.REPORT.name())){
//                    PriceFeedbackDTO feedbackDTO = new PriceFeedbackDTO();
//                    List<ProductionEnum> p = new ArrayList<>();
//                    if (StrUtil.isNotEmpty(statementNo)){
//                        p.add(ProductionEnum.STATEMENT);
//                    }
//                    p.add(ProductionEnum.REPORT);
//                    feedbackDTO.setProduction(p);
//                    feedbackDTO.setMajorId(majorId);
//                    feedbackDTO.setPrinting(majorProduction.getPrintTimes());
//                    feedbackDTO.setReportNo(statementNo);
//                    feedbackDTOS.add(feedbackDTO);
//                }
//                if (majorProduction.getProduction().equals(ProductionEnum.LETTER.name())){
//                    PriceFeedbackDTO feedbackDTO = new PriceFeedbackDTO();
//                    List<ProductionEnum> p = new ArrayList<>();
//                    if (StrUtil.isNotEmpty(statementNo)){
//                        p.add(ProductionEnum.STATEMENT);
//                    }
//                    p.add(ProductionEnum.REPORT);
//                    feedbackDTO.setProduction(p);
//                    feedbackDTO.setMajorId(majorId);
//                    feedbackDTO.setPrinting(majorProduction.getPrintTimes());
//                    feedbackDTO.setReportNo(statementNo);
//                    feedbackDTOS.add(feedbackDTO);
//                }
//            }
//            if (CollectionUtil.isNotEmpty(feedbackDTOS)){
//                majorServiceImpl.update(new LambdaUpdateWrapper<Major>().set(Major::getFeedbackInfo,JSON.toJSONString(feedbackDTOS))
//                        .eq(BaseEntity::getId,majorId));
//            }
//            return mps;
//        }
//        return null;
//    }

    @Autowired
    private OrderFundMapper orderFundMapper;



    @Override
    public Boolean updateMajorProduction() {
        List<HisMajorProduction> allProductionNo = dyoaHistoryMapper.findAllProductionNo();
        for (HisMajorProduction productionNo : allProductionNo){
            List<MajorProduction> list = majorProductionService.list(new LambdaQueryWrapper<MajorProduction>().select(BaseEntity::getId).eq(MajorProduction::getReportNo, productionNo.getReportNo()));
            if (CollectionUtil.isEmpty(list)){
                DyoaRecord record = dyoaRecordService.getOne(new LambdaQueryWrapper<DyoaRecord>().eq(DyoaRecord::getDyoaId, productionNo.getId()).eq(DyoaRecord::getMbsType, "MAJOR_ORDER"));
                if (record != null){
                    MajorProduction majorProduction = new MajorProduction();
                    majorProduction.setReportNo(productionNo.getReportNo());
                    majorProduction.setMajorId(record.getMbsId());
                    if (StrUtil.isNotBlank(productionNo.getPType())){
                        majorProduction.setProduction(getProductionType(productionNo.getPType()));
                    }else {
                        majorProduction.setProduction("REPORT");
                    }
                    majorProduction.setName(productionNo.getName());
                    majorProduction.setClientName(productionNo.getPrincipal());
                    majorProduction.setClientTel(productionNo.getPrincipalMobile());
                    majorProduction.setClientAddress(productionNo.getPrincipalAddress());
                    if (productionNo.getPriceDate()!=null){
                        majorProduction.setValueTiming(DateUtils.dateToLocalDate(productionNo.getPriceDate()));
                    }
                    majorProduction.setEvaluateAcreage(productionNo.getArea());
                    majorProduction.setEvaluateAmount(productionNo.getMoney());
                    majorProduction.setEvaluatePrice(productionNo.getXPrice());
                    majorProduction.setRepertoryInTime(productionNo.getBgInTime());
                    majorProduction.setRepertoryOutTime(productionNo.getBgOutTime());
                    majorProduction.setDelivery(productionNo.getDeliveryState());
                    if (productionNo.getConfirmTime()!=null){
                        majorProduction.setDeliveryDate(DateUtils.dateToLocalDate(productionNo.getConfirmTime()));
                    }
                    if (productionNo.getArchiveTime()!=null){
                        majorProduction.setSaveFileDate(DateUtils.dateToLocalDate(productionNo.getArchiveTime()));
                        majorProduction.setIfSaveFile(true);
                    }
                    majorProduction.setStandardAmount(productionNo.getStandardPrice());
                    majorProductionService.save(majorProduction);
                }
            }
            else{
                //更新已同步产品的归档状态、归档时间、送达状态、送达时间、产品出库时间
                boolean flog = false;
                for (MajorProduction majorProduction :list){
                    Date archiveTime = productionNo.getArchiveTime();
                    Date confirmTime = productionNo.getConfirmTime();
                    Date bgOutTime = productionNo.getBgOutTime();
                    if (archiveTime!=null){
                        flog = true;
                        majorProduction.setIfSaveFile(true);
                        majorProduction.setSaveFileDate(DateUtils.dateToLocalDate(archiveTime));
                    }
                    if (confirmTime!=null){
                        flog = true;
                        majorProduction.setDelivery(true);
                        majorProduction.setDeliveryDate(DateUtils.dateToLocalDate(confirmTime));
                    }
                    if (bgOutTime!=null){
                        flog = true;
                        majorProduction.setRepertoryOutTime(bgOutTime);
                    }
                    if (flog){
                        majorProductionService.update(new LambdaUpdateWrapper<MajorProduction>()
                                .eq(BaseEntity::getId,majorProduction.getId())
                                .set(majorProduction.getIfSaveFile()!=null,MajorProduction::getIfSaveFile,majorProduction.getIfSaveFile())
                                .set(majorProduction.getSaveFileDate()!=null,MajorProduction::getSaveFileDate,majorProduction.getSaveFileDate())
                                .set(majorProduction.getDelivery()!=null,MajorProduction::getDelivery,majorProduction.getDelivery())
                                .set(majorProduction.getDeliveryDate()!=null,MajorProduction::getDeliveryDate,majorProduction.getDeliveryDate())
                                .set(majorProduction.getRepertoryOutTime()!=null,MajorProduction::getRepertoryOutTime,majorProduction.getRepertoryOutTime()));

                    }

                }
            }
        }
        return true;
    }

    @Autowired
    private IMajorProductionAllotService majorProductionAllotService;

    @Override
    public Boolean updateCommissionDeclare() {
        List<HisCommissionDeclare> list = dyoaHistoryMapper.findCommissionDeclareInDyOA();
        BigDecimal divisor = new BigDecimal("100");
        for (HisCommissionDeclare hisCommissionDeclare : list){
            Long pgUserId = getMbsUserId(hisCommissionDeclare.getManagerName());
            Long scUserId = getMbsUserId(hisCommissionDeclare.getMasterName());
            Long majorId = dyoaRecordService.getMbsIdByDyOAId(hisCommissionDeclare.getId());
            Long mpId = null;
            if (StrUtil.isNotBlank(hisCommissionDeclare.getReportNO())){
                List<MajorProduction> mps = majorProductionService.list(new LambdaQueryWrapper<MajorProduction>()
                        .select(BaseEntity::getId)
                        .eq(MajorProduction::getProduction,REPORT.name())
                        .eq(MajorProduction::getReportNo, hisCommissionDeclare.getReportNO()));
                if  (CollectionUtils.isNotEmpty(mps)){
                    mpId = mps.get(0).getId();
                }
            }
            if (StrUtil.isNotBlank(hisCommissionDeclare.getPgApproveStatus()) &&
                "通过".equals(hisCommissionDeclare.getPgApproveStatus())){
                String pgBusinessType = hisCommissionDeclare.getPgBusinessType();
                Long pgBusinessType1 = findPgBusinessType(pgBusinessType);
                Long pgcdId = null;
                Date created = null;
                //查询在老系统里面的申报日期
                String pgFlowInstanceId = hisCommissionDeclare.getPgFlowInstanceId();
                if (StrUtil.isNotBlank(pgFlowInstanceId)){
                    created = dyoaHistoryMapper.findCommissionDeclareDate(pgFlowInstanceId);
                }
                List<CommissionDeclare> cds = commissionDeclareService.list(new LambdaQueryWrapper<CommissionDeclare>()
                        .eq(CommissionDeclare::getBusinessType, "COMMISSION_DECLARE_MAJOR_EVALUATE")
                        .eq(CommissionDeclare::getBusinessId, majorId)
                        .eq(mpId != null, CommissionDeclare::getProductionId, mpId)
                        .eq(CommissionDeclare::getDeclareUserId, pgUserId)
                        .eq(CommissionDeclare::getDeclareResult, "审核通过")
                        .eq(CommissionDeclare::getCommissionRateId, pgBusinessType1));
                if (cds==null || cds.size()==0 ){
                    CommissionDeclare commissionDeclare = new CommissionDeclare();
                    commissionDeclare.setBusinessType("COMMISSION_DECLARE_MAJOR_EVALUATE");
                    commissionDeclare.setBusinessId(majorId);
                    commissionDeclare.setDeclareResult("审核通过");
                    commissionDeclare.setDeclareUserId(pgUserId);
                    commissionDeclare.setCommissionRateId(pgBusinessType1);
                    commissionDeclare.setProductionId(mpId);
                    commissionDeclare.setCreated(created==null?hisCommissionDeclare.getCreatedDatetime():created);
                    commissionDeclareService.save(commissionDeclare);
                    pgcdId = commissionDeclare.getId();
                }else{
                    if (cds.size()>1){
                        commissionDeclareService.delete(cds.get(0).getId());
                        pgcdId = cds.get(1).getId();
                        commissionDeclareService.update(new LambdaUpdateWrapper<CommissionDeclare>()
                                .set(BaseEntity::getCreated,created==null?hisCommissionDeclare.getCreatedDatetime():created)
                                .set(CommissionDeclare::getProductionId,mpId)
                                .eq(BaseEntity::getId,pgcdId));
                    }else{

                        pgcdId = cds.get(0).getId();
                        commissionDeclareService.update(new LambdaUpdateWrapper<CommissionDeclare>()
                                .set(BaseEntity::getCreated,created==null?hisCommissionDeclare.getCreatedDatetime():created)
                                .set(CommissionDeclare::getProductionId,mpId)
                                .eq(BaseEntity::getId,pgcdId));
                    }
                }
                //查询评估人员绩效比例
                List<CommissionRate> rates = dyoaHistoryMapper.findPgRate(hisCommissionDeclare.getId());
                for (CommissionRate commissionRate : rates){
                    MajorProductionAllot majorProductionAllot = new MajorProductionAllot();
                    majorProductionAllot.setMajorProductionId(mpId);
                    majorProductionAllot.setMajorId(majorId);
                    majorProductionAllot.setUserId(getMbsUserId(commissionRate.getName()));
                    majorProductionAllot.setRatio(BigDecimal.valueOf(commissionRate.getRate()).divide(divisor));
                    majorProductionAllot.setUserType("EVALUATE");
                    majorProductionAllot.setDeclareId(pgcdId);
                    List<MajorProductionAllot> allos = majorProductionAllotService.list(new LambdaQueryWrapper<MajorProductionAllot>()
                            .eq(MajorProductionAllot::getDeclareId, pgcdId).eq(MajorProductionAllot::getUserId,majorProductionAllot.getUserId()));
                    if (CollectionUtils.isEmpty(allos)){
                        majorProductionAllotService.save(majorProductionAllot);
                    }

                }


            }
            if (StrUtil.isNotBlank(hisCommissionDeclare.getMasterApproveStatus()) &&
                    "通过".equals(hisCommissionDeclare.getMasterApproveStatus())){
                String scBusinessType = hisCommissionDeclare.getMasterBusinessType();
                Long scBusinessType1 = findSCBusinessType(scBusinessType);
                Long sccdId = null;
                Date created = null;
                String masterFlowInstanceId = hisCommissionDeclare.getMasterFlowInstanceId();
                if (StrUtil.isNotBlank(masterFlowInstanceId)){
                    created = dyoaHistoryMapper.findCommissionDeclareDate(masterFlowInstanceId);
                }
                CommissionDeclare pgCd = null;
                List<CommissionDeclare> pgCds = commissionDeclareService.list(new LambdaQueryWrapper<CommissionDeclare>()
                        .eq(CommissionDeclare::getBusinessType, "COMMISSION_DECLARE_MAJOR_MARKET")
                        .eq(CommissionDeclare::getBusinessId, majorId)
                        .eq(mpId != null, CommissionDeclare::getProductionId, mpId)
                        .eq(CommissionDeclare::getDeclareUserId, scUserId)
                        .eq(CommissionDeclare::getDeclareResult, "审核通过")
                        .eq(CommissionDeclare::getCommissionRateId, scBusinessType1).orderByDesc(BaseEntity::getCreated))
                        ;

                if (pgCds==null || pgCds.size()==0){
                    CommissionDeclare commissionDeclare = new CommissionDeclare();
                    commissionDeclare.setBusinessType("COMMISSION_DECLARE_MAJOR_MARKET");
                    commissionDeclare.setBusinessId(majorId);
                    commissionDeclare.setDeclareResult("审核通过");
                    commissionDeclare.setDeclareUserId(scUserId);
                    commissionDeclare.setCommissionRateId(scBusinessType1);
                    commissionDeclare.setProductionId(mpId);
                    commissionDeclare.setCreated(created==null?hisCommissionDeclare.getCreatedDatetime():created);
                    commissionDeclareService.save(commissionDeclare);
                    sccdId = commissionDeclare.getId();
                }else {
                    if (pgCds.size()>1){
                        commissionDeclareService.delete(pgCds.get(0).getId());
                        pgCd =pgCds.get(1);
                        sccdId = pgCd.getId();
                        commissionDeclareService.update(new LambdaUpdateWrapper<CommissionDeclare>()
                                .set(CommissionDeclare::getProductionId,mpId)
                                .set(BaseEntity::getCreated,created==null?hisCommissionDeclare.getCreatedDatetime():created).eq(BaseEntity::getId,sccdId));
                    }else{
                        pgCd =pgCds.get(0);
                        sccdId = pgCd.getId();
                        commissionDeclareService.update(new LambdaUpdateWrapper<CommissionDeclare>()
                                .set(CommissionDeclare::getProductionId,mpId)
                                .set(BaseEntity::getCreated,created==null?hisCommissionDeclare.getCreatedDatetime():created).eq(BaseEntity::getId,sccdId));
                    }

                }
                //查询市场人员绩效比例
                List<CommissionRate> rates = dyoaHistoryMapper.findScRate(hisCommissionDeclare.getId());
                for (CommissionRate commissionRate : rates){
                    MajorProductionAllot majorProductionAllot = new MajorProductionAllot();
                    majorProductionAllot.setMajorProductionId(mpId);
                    majorProductionAllot.setMajorId(majorId);
                    majorProductionAllot.setUserId(getMbsUserId(commissionRate.getName()));
                    majorProductionAllot.setRatio(BigDecimal.valueOf(commissionRate.getRate()).divide(divisor));
                    majorProductionAllot.setUserType("MARKET");
                    majorProductionAllot.setDeclareId(sccdId);
                    List<MajorProductionAllot> allos = majorProductionAllotService.list(new LambdaQueryWrapper<MajorProductionAllot>()
                            .eq(MajorProductionAllot::getDeclareId, sccdId).eq(MajorProductionAllot::getUserId,majorProductionAllot.getUserId()));
                    if (CollectionUtils.isEmpty(allos)){
                        majorProductionAllotService.save(majorProductionAllot);
                    }
                }
            }

        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean updatePersonalProduction() {
        List<HisPersonalProduction> list = dyoaRecordMapper.findPersonalProduction();
        for (HisPersonalProduction hisPersonalProduction : list){
            Long personalTargetId = dyoaRecordService.getPersonalTargetId(hisPersonalProduction.getId());
            if (personalTargetId != null){
                PersonalTarget target = personalTargetService.getById(personalTargetId);
                if (target!=null){
                    PersonalProduction pp = personalProductionServiceImpl.getOne(new LambdaQueryWrapper<PersonalProduction>()
                            .eq(PersonalProduction::getTargetId, personalTargetId));
                    Date bgOutRepoTime = hisPersonalProduction.getBgOutRepoTime();
                    Date bgInRepoTime = hisPersonalProduction.getBgInRepoTime();
                    if (pp==null){
                        PersonalProduction personalProduction = new PersonalProduction();

                        personalProduction.setTargetId(personalTargetId);
                        personalProduction.setProduction(FINAL.name());
                        if (bgOutRepoTime!=null){
                            personalProduction.setRepertoryState(true);
                            personalProduction.setRepertoryOutTime(DateUtils.parseLocalDateTime(DateUtils.dateTime(bgOutRepoTime)));
                        }
                        if (bgInRepoTime!=null){
                            personalProduction.setRepertoryInTime(DateUtils.parseLocalDateTime(DateUtils.dateTime(bgInRepoTime)));
                        }
                        personalProductionServiceImpl.save(personalProduction);
                    }else if(pp.getRepertoryState()==null){
                        pp.setRepertoryState(true);
                        pp.setRepertoryOutTime(DateUtils.parseLocalDateTime(DateUtils.dateTime(bgOutRepoTime)));
                        pp.setRepertoryInTime(DateUtils.parseLocalDateTime(DateUtils.dateTime(bgInRepoTime)));
                        personalProductionServiceImpl.updateById(pp);
                    }

                }
            }
        }
        return null;
    }


    @Override
    public Boolean updateAssetsProduction() {
        List<HisPersonalProduction> assetsProduction = dyoaRecordMapper.findAssetsProduction();
        for (HisPersonalProduction hisPersonalProduction : assetsProduction){
            Long assetsId = dyoaRecordService.getMbsIdByDyOAIdForAssets(hisPersonalProduction.getId());
            if (assetsId != null && hisPersonalProduction.getBgOutRepoTime()!=null){
                AssetsProduction ap = assetsProductionService.getOne(new LambdaQueryWrapper<AssetsProduction>().eq(AssetsProduction::getBusinessId, assetsId).ne(AssetsProduction::getProductionType,"STATEMENT"));
                if (ap!=null && ap.getRepertoryState()==null){
                        ap.setRepertoryState(true);
                        ap.setRepertoryOutTime(DateUtils.parseLocalDateTime(DateUtils.dateTime(hisPersonalProduction.getBgOutRepoTime())));
                        ap.setRepertoryInTime(DateUtils.parseLocalDateTime(DateUtils.dateTime(hisPersonalProduction.getBgInRepoTime())));
                    assetsProductionService.update(ap);
                }
            }
            if (assetsId!=null && hisPersonalProduction.getConfirmTime()!=null){
                AssetsProduction ap = assetsProductionService.getOne(new LambdaQueryWrapper<AssetsProduction>().eq(AssetsProduction::getBusinessId, assetsId).ne(AssetsProduction::getProductionType,"STATEMENT"));
                if (ap!=null && ap.getDeliveryDate()==null){
                    ap.setDelivery(true);
                    ap.setDeliveryDate(DateUtils.parseLocalDateTime(DateUtils.dateTime(hisPersonalProduction.getConfirmTime())));
                    assetsProductionService.update(ap);
                }
            }
        }
        return null;
    }

    @Autowired
    private IPersonalProductionService personalProductionService;

    @Autowired
    private IWorkFlowNodeInstanceService workFlowNodeInstanceService;


    @Override
    public Boolean updatePersonalProductionTime() {
        List<PersonalProductionDTO> list =  personalProductionService.updatePersonalProductionTime();
        for (PersonalProductionDTO prod : list){
            if (prod.getProduction().equals(STATEMENT.name())){
                Date nodeFinishedTime = workFlowNodeInstanceService.getNodeFinishedTime(PERSONAL_BUSINESS, GENERATE_STATEMENT, prod.getPid(), prod.getOrderId(), null);
                if (nodeFinishedTime!=null){
                    personalProductionService.update(new LambdaUpdateWrapper<PersonalProduction>().eq(BaseEntity::getId,prod.getId()).set(PersonalProduction::getProductionTime,nodeFinishedTime));
                }
            }
            if (prod.getProduction().equals(TECHNIC.name())){
                Date nodeFinishedTime = workFlowNodeInstanceService.getNodeFinishedTime(PERSONAL_BUSINESS, WRITE_REPORT, prod.getPid(), prod.getOrderId(), null);
                if (nodeFinishedTime!=null){
                    personalProductionService.update(new LambdaUpdateWrapper<PersonalProduction>().eq(BaseEntity::getId,prod.getId()).set(PersonalProduction::getProductionTime,nodeFinishedTime));
                }
            }
            if (prod.getProduction().equals(FINAL.name())){
                Date nodeFinishedTime = workFlowNodeInstanceService.getNodeFinishedTime(PERSONAL_BUSINESS, WRITE_REPORT, prod.getPid(), prod.getOrderId(), null);
                if (nodeFinishedTime!=null){
                    personalProductionService.update(new LambdaUpdateWrapper<PersonalProduction>().eq(BaseEntity::getId,prod.getId()).set(PersonalProduction::getProductionTime,nodeFinishedTime));
                }
            }
            if (prod.getProduction().equals(LETTER.name())){
                Date nodeFinishedTime = workFlowNodeInstanceService.getNodeFinishedTime(PERSONAL_BUSINESS, WRITE_LETTER, prod.getPid(), prod.getOrderId(), null);
                if (nodeFinishedTime!=null){
                    personalProductionService.update(new LambdaUpdateWrapper<PersonalProduction>().eq(BaseEntity::getId,prod.getId()).set(PersonalProduction::getProductionTime,nodeFinishedTime));
                }
            }
        }
        return null;
    }



    @Override
    public Boolean updateMajorSubClientId() {
        List<MajorSubClientDTO> list = majorServiceImpl.findMajorSubClient();
        for (MajorSubClientDTO majorSubClientDTO : list){
            if (majorSubClientDTO.getRealSubId()!=null && !majorSubClientDTO.getRealSubId().equals(majorSubClientDTO.getClienteleSubId())){
                majorServiceImpl.update(new LambdaUpdateWrapper<Major>()
                        .eq(BaseEntity::getId,majorSubClientDTO.getId())
                        .set(Major::getClienteleSubId,majorSubClientDTO.getRealSubId()));
            }
        }
        return true;
    }

    @Override
    public Boolean updateAssetsMembers() {
        List<Assets> list = assetsService.getMembersIsNull();
        for (Assets assets : list){
            String dyoaId = dyoaRecordService.getMembersAndSignerInDyoa(assets.getId());
            if (StrUtil.isNotBlank(dyoaId)){
                List<Long> memberIds = new ArrayList<>();
                Map<String,Object> members = dyoaHistoryMapper.getMembersAndSigner(dyoaId);
                if (members==null){
                    continue;
                }
                Object o = members.get("members");
                if (o!=null){
                    String mebStr = (String) o;
                    List<String> mList = Arrays.asList(mebStr.split(","));
                    for (String m : mList){
                        m = m.replaceAll(" ","");
                        Long mbsUserId = getMbsUserId(m);
                        if (!mbsUserId.equals(1L)){
                            memberIds.add(mbsUserId);
                        }
                    }
                }

                assets.setMembers(JSON.toJSONString(memberIds));

                assetsService.updateMembers(assets);
                List<Long> signs = new ArrayList<>();
                Object o1 = members.get("signEmpName1");
                if (o1!=null){
                    String s1 = (String) o1;
                    Long s1Id = getMbsUserId(s1);
                    if (!s1Id.equals(1L)){
                        signs.add(s1Id);
                    }
                }
                Object o2 = members.get("signEmpName2");
                if (o2!=null){
                    String s2 = (String) o2;
                    Long s2Id = getMbsUserId(s2);
                    if (!s2Id.equals(1L)){
                        signs.add(s2Id);
                    }
                }

                List<Long> reportByAssetsId = assetsProductionService.getReportByAssetsId(assets.getId());
                for (Long reportId : reportByAssetsId){
                    assetsProductionService.updateSigner(JSON.toJSONString(signs),reportId);
                }
            }
        }
        return null;
    }

    @Override
    public Boolean majorMarketDepartmentId() {
        List<Major> majors = majorServiceImpl.list(new LambdaQueryWrapper<Major>().select(BaseEntity::getId, Major::getClientManagerId));
        for (Major major : majors){
            Long clientManagerId = major.getClientManagerId();
            Set<Long> departmentIdByUserId = userService.getDepartmentIdByUserId(clientManagerId);
            if (CollectionUtil.isNotEmpty(departmentIdByUserId)){
                Long departmentId = departmentIdByUserId.stream().findFirst().get();
                majorServiceImpl.update(new LambdaUpdateWrapper<Major>().set(Major::getMarketDepartmentId,departmentId).eq(BaseEntity::getId,major.getId()));
            }
        }
        return true;
    }

    @Override
    public Boolean majorProductionTime() {
        List<MajorProduction> mps = majorProductionService.list(new LambdaQueryWrapper<MajorProduction>().select(BaseEntity::getId, MajorProduction::getMajorId, MajorProduction::getProduction, MajorProduction::getRepertoryInTime,MajorProduction::getRepertoryOutTime)
                .isNull(MajorProduction::getProductionTime).eq(BaseEntity::getDeleted, Boolean.FALSE));
        for (MajorProduction mp : mps){
            if (mp.getProduction().equals(STATEMENT.name())){
                Date majorProductionFinishedTime = workFlowNodeInstanceService.getMajorProductionFinishedTime(mp.getMajorId(), 62L);
                if (majorProductionFinishedTime==null){
                    majorProductionFinishedTime = mp.getRepertoryInTime();
                    if (majorProductionFinishedTime==null){
                        majorProductionFinishedTime = mp.getRepertoryOutTime();
                    }
                }
                majorProductionService.update(new LambdaUpdateWrapper<MajorProduction>().set(MajorProduction::getProductionTime,majorProductionFinishedTime).eq(BaseEntity::getId,mp.getId()));
            }
            if (mp.getProduction().equals(REPORT.name())){
                Date majorProductionFinishedTime = workFlowNodeInstanceService.getMajorProductionFinishedTime(mp.getMajorId(), 71L);
                if (majorProductionFinishedTime==null){
                    majorProductionFinishedTime = mp.getRepertoryInTime();
                    if (majorProductionFinishedTime==null){
                        majorProductionFinishedTime = mp.getRepertoryOutTime();
                    }
                }
                majorProductionService.update(new LambdaUpdateWrapper<MajorProduction>().set(MajorProduction::getProductionTime,majorProductionFinishedTime).eq(BaseEntity::getId,mp.getId()));
            }
            if (mp.getProduction().equals(LETTER.name())){
                Date majorProductionFinishedTime = workFlowNodeInstanceService.getMajorProductionFinishedTime(mp.getMajorId(), 78L);
                if (majorProductionFinishedTime==null){
                    majorProductionFinishedTime = mp.getRepertoryInTime();
                    if (majorProductionFinishedTime==null){
                        majorProductionFinishedTime = mp.getRepertoryOutTime();
                    }
                }
                majorProductionService.update(new LambdaUpdateWrapper<MajorProduction>().set(MajorProduction::getProductionTime,majorProductionFinishedTime).eq(BaseEntity::getId,mp.getId()));
            }
        }
        return true;
    }

    @Override
    public Boolean assetsMarketDepartment() {
        List<Assets> list = assetsService.list(new LambdaQueryWrapper<Assets>().isNull(Assets::getMarketDepartmentId).select(Assets::getClientManagerId, BaseEntity::getId));
        for (Assets assets : list){
            Long clientManagerId = assets.getClientManagerId();
            Set<Long> departmentIdByUserId = userService.getDepartmentIdByUserId(clientManagerId);
            Long departmentId = departmentIdByUserId.stream().collect(Collectors.toList()).get(0);
            assetsService.update(new LambdaUpdateWrapper<Assets>().set(Assets::getMarketDepartmentId,departmentId)
                    .eq(BaseEntity::getId,assets.getId()));
        }
        return null;
    }


    @Override
    public Boolean updateProductionFund() {
        List<OrderFund> orderFunds = orderFundService.getAllOrderFund();
        for (OrderFund orderFund : orderFunds) {
            List<ProductionFund> list = productionFundService.list(new LambdaQueryWrapper<ProductionFund>().eq(ProductionFund::getOrderFundId, orderFund.getId()));
            if (list.size()==0){
                ProductionFund pf = new ProductionFund();
                pf.setOrderFundId(orderFund.getId());
                pf.setBusinessType(MainBusinessEnum.MAJOR_BUSINESS.name());
                pf.setBusinessId(orderFund.getBusinessId());
                pf.setRealAmount(orderFund.getRealAmount());
                pf.setProductionShouldAmount(orderFund.getShouldAmount());
                pf.setBusinessId(orderFund.getBusinessId());
                pf.setStandardAmount(orderFund.getStandardAmount());
                pf.setProductionNo(orderFund.getReportNo());
                pf.setCreated(orderFund.getCreated());
                productionFundService.save(pf);
            }
        }
        return true;
    }

    @Override
    public Boolean updateClaimProductionId() {
        List<HisClaimProd> majorList = financeClaimService.updateClaimProductionId(MAJOR_BUSINESS.name());
        for (HisClaimProd hisClaimProd : majorList){
            financeClaimService.update(new LambdaUpdateWrapper<FinanceClaim>().eq(BaseEntity::getId,hisClaimProd.getFcid()).set(FinanceClaim::getProductionFundId,hisClaimProd.getPid()));
        }
        List<HisClaimProd> assetList = financeClaimService.updateClaimProductionId(ASSET_BUSINESS.name());
        for (HisClaimProd hisClaimProd : assetList){
            financeClaimService.update(new LambdaUpdateWrapper<FinanceClaim>().eq(BaseEntity::getId,hisClaimProd.getFcid()).set(FinanceClaim::getProductionFundId,hisClaimProd.getPid()));
        }
        return true;

    }

    @Autowired
    private IBusinessCommissionRateService businessCommissionRateService;



    public Long findPgBusinessType(String businessType){
        Long id = PG_BUSINESS_TYPE.get(businessType);
        if (id==null){
            List<PullDownModel> businessCate = businessCommissionRateService.getBusinessCate("MAJOR_BUSINESS", "EVALUATOR");
            PG_BUSINESS_TYPE = businessCate.stream().collect(Collectors.toMap(PullDownModel::getName, PullDownModel::getId));
            id = PG_BUSINESS_TYPE.get(businessType);
        }
        return id;
    }

    public Long findSCBusinessType(String businessType){
        Long id = SC_BUSINESS_TYPE.get(businessType);
        if (id==null){
            List<PullDownModel> businessCate = businessCommissionRateService.getBusinessCate("MAJOR_BUSINESS", "MARKETER");
            SC_BUSINESS_TYPE = businessCate.stream().collect(Collectors.toMap(PullDownModel::getName, PullDownModel::getId));
            id = SC_BUSINESS_TYPE.get(businessType);
        }
        return id;
    }


}
