package com.sifang.modules.customer.Service;

import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationDao;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationInsuranceDao;
import com.sifang.modules.customer.dao.CrmYxIncomingLogDao;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.partner.service.HuaRongApiService;
import com.sifang.modules.partner.utils.HuaRongCustomer;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.GuardUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Service
public class HuaRongManagementService extends BaseService {
    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    @Lazy
    private CustomerEntryService customerEntryService;
    @Autowired
    private HuaRongApiService huaRongApiService;
    @Autowired
    private CrmYxIncomingLogDao yxIncomingLogDao;
    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    private PartnerService partnerService;

    /**
     * 更新华融进件状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateIncomingApplicationStatus(CrmCustomerIncomingApplication incomingApplication, HuaRongCustomer customer, CustomerEntry entry,String type){
        logger.info(" 华融状态值回调 HuaRongCustomer ：{}",new Gson().toJson(customer));
        if (!"FT".equals(entry.getFirstApplyStatus()) && StringUtil.equalsAny(type, "1", "3")) {
            logger.info("华融更新第一次进件状态  ");
            customerEntryService.updateFirstStateHuaRong(entry.getId(), customer);
        }
        if (customer != null && StringUtil.equalsAny(customer.getProjectStatus(), "DS", "MR", "ST", "CS","PR","LS","RJ","CL")
                && StringUtil.equalsAny(type,"2","3")){
            logger.info("华融更新第二次进件状态  ");
            customerEntryService.updateSecondStateHuaRong(entry,customer,incomingApplication);
        }
    }

    public void accessProjectApplyTwo(CustomerEntry entry,CrmCustomerIncomingApplication incomingApplication, Operator operator){
        logger.info("....accessProjectApplyTwo  第二次进件 进件序号:{}",incomingApplication.getPartnersContractNumber());
        CrmPartner partner = partnerService.getById(entry.getPartnerId());
//        GuardUtils.notNull(entry.getFirstGenerationTime(),"尚未获取到首日发电日期，不允许并网信息推送！");
            if ("1".equals(entry.getTenantType()) && !StringUtil.equalsAny(entry.getSignStatus(),"5","g","e")) {
            throw new BusinessException("当前电站未签约《农户合同》，请在签约后再操作并网");
        }
//        if (StringUtil.isNotBlank(entry.getNextApplyStatus())&&!StringUtil.equalsAny(entry.getNextApplyStatus(),"DS")) {
//            throw new IllegalArgumentException("资方完工资料还未审核通过 ，无法并网验收通过进行并网信息推送");
//        }

        //提交进件申请
        try {
            Result uploadFile = huaRongApiService.uploadFile(entry, incomingApplication, "3", new HashSet<>());
            if (!"200".equals(uploadFile.getCode())) {
                throw new IllegalArgumentException(uploadFile.getErrMsg());
            }
            Result result = huaRongApiService.accessProjectApply(entry, incomingApplication, partner,"2");
            if (!result.isOk()){
                throw new IllegalArgumentException(result.getErrMsg());
            }
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_BWYTJ);
            entry.setNextApplyStatus("MR");
            incomingApplication.setApplyTime(new Date());
            incomingApplication.setFarmerSignStatus("MR");
            incomingApplication.setStatus(entry.getApplyStatus());
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(),incomingApplication.getPartnersContractNumber(),"5","推送进件信息 ",operator);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("gridIncomingApplication  e:{}",e);
            throw new IllegalArgumentException("并网进件失败，"+e.getMessage());
        }
        applicationDao.save(incomingApplication);
    }
    public String getHRContent(HuaRongCustomer customer){
        String msg = "";
        if (StringUtil.isNotBlank(customer.getFileCode())){
            // 附件编码转化为文字描述
            List<String> strings = PartnerConstants.hrFileCodeToRemarks(customer.getFileCode());
            if (!strings.isEmpty()) {
                msg = String.join(",", strings);
            }
        }
        String content = "";
        switch (customer.getProjectStatus()) {
            case "NS":
                content = "数据不存在";
                break;
            case "RJ":
                content = "拒绝"+(StringUtil.isNotBlank(customer.getReturnReason())?",拒绝原因："+customer.getReturnReason():"");
                break;
            case "JD":
                content = "建档完成，推送进件异常，需要取消进件，重新推送进件信息";
                break;
            case "FR":
                content = "建档审核中";
                break;
            case "FA":
                content = "建档审核通过";
                break;
            case "FS":
                content = StringUtil.isNotBlank(customer.getReturnReason()) ? customer.getReturnReason()+";"+msg:"建档待补充资料:"+msg;
                break;
            case "JT":
                content = "建档审核提交完成";
                break;
            case "FT":
                content = "审核通过";
                break;
            case "ST":
                content = "二次进件完成";
                break;
            case "DS":
                content = StringUtil.isNotBlank(customer.getReturnReason()) ? customer.getReturnReason()+";"+msg:"待补充资料:"+msg;
                break;
            case "MR":
                content = "人工审核中";
                break;
            case "CS":
                content = "确认单已生成";
                break;
            case "PR":
                content = "审批通过";
                break;
            case "LS":
                content = "已完成放款";
                break;
            case "CL":
                content = "废止";
                break;
            default:
        }
        return content;
    }
}
