package com.sifang.modules.customer.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.customer.constant.YueXiuConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.CrmCustomerContractManagement;
import com.sifang.modules.customer.entity.CrmCustomerIncomingApplication;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.form.PrjDocumentStatusDto;
import com.sifang.modules.customer.form.QueryDocumentRes;
import com.sifang.modules.esign.constants.ESignConstants;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
public class YueXiuContractService {

    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private OperatingLeaseService operatingLeaseService;

    @Autowired
    private CustomerEntryDao entryDao;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    private CrmCustomerIncomingApplicationDao incomingApplicationDao;

    @Value("${yx.setting}")
    private String YX;
    /**
     * 农户单据状态查询
     * partnersContractNumber XX方的合同编号（进件序号和证件号码必填其一）
     * idCardNo   承租人证件号码（进件序号和证件号码必填其一）
     */
    public QueryDocumentRes  queryDocumentStatus(String entryId){
        logger.info("农户单据状态查询 queryDocumentStatus -------entryId：{}", entryId);
        CrmCustomerIncomingApplication application=incomingApplicationDao.getByEntryId(entryId);
        String partnersContractNumber=application.getPartnersContractNumber();
        Map<String, Object> map = new HashMap<>();
        List<Object> bodyData=new ArrayList<>();
        Map<String,Object> map1=new HashMap<>();
        PrjDocumentStatusDto documentStatusDto=new PrjDocumentStatusDto();
        documentStatusDto.setPartnersContractNumber(partnersContractNumber);
        map1.put("prjDocumentStatusDto",documentStatusDto);
        bodyData.add(map1);
        map.put("body",bodyData);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode",YueXiuConstants.TRANSACTION_CODE_CONTRACT+YX);
        head.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        Gson gson=new Gson();
        logger.info("农户单据状态查询  queryDocumentStatus json:{}",gson.toJson(map));
        JSONObject jieMap = operatingLeaseService.clientPostZYMap(map,YueXiuConstants.QUERY_DOCUMENT_STATUS);
        logger.info("农户单据状态查询 queryDocumentStatus -------返回结果：{}", jieMap);
        CrmYxProcessDao.addProcess(partnersContractNumber,"5","单据状态主动查询",gson.toJson(map),gson.toJson(jieMap),"0");
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject re = reqMap.getJSONObject(0);
        //type: S-请求成功 E-请求失败
        if ("S".equals(re.get("type"))) {
            QueryDocumentRes res=re.getObject("prjProjectOperatingLeaseStatus",QueryDocumentRes.class);
            res.setBusinessKey(partnersContractNumber);
            return res;
        } else {
            throw new BusinessException("查询农户单据状态失败!失败原因："+re.get("message"));
        }
    }

    //查看合同--获取合同的地址
    public String getContractDownloadUrl(String partnersContractNumber) throws IOException {
        Map<String, Object> map = new HashMap<>();
        List<Object> bodyData=new ArrayList<>();
        Map<String,Object> map1=new HashMap<>();
        map1.put("partnersContractNumber",partnersContractNumber);
        map1.put("queryCondition","TENANT");
        bodyData.add(map1);
        map.put("body",bodyData);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode",YueXiuConstants.TRANSACTION_CODE_CONTRACT_LOOK+YX);
        head.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info("合同文本获取  getContractDownloadUrl json:{}",new Gson().toJson(map));
        JSONObject jieMap = operatingLeaseService.clientPostZYMap(map,YueXiuConstants.QUERY_CONTRACT);
        logger.info("合同文本获取 getContractDownloadUrl -------返回结果：{}", jieMap);

        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject re = reqMap.getJSONObject(0);
        //type: S-请求成功 E-请求失败
        if ("S".equals(re.get("type"))) {
            JSONArray contractArray=re.getJSONArray("contract");
            if(contractArray.size()==0){
                throw new BusinessException("未生成合同文本!");
            }
            JSONObject contract=contractArray.getJSONObject(0);
            logger.info("合同文本获取 getContractDownloadUrl -------contract:{} ",contract);
            JSONArray fileMssages=contract.getJSONArray("fileMessage");
            if(fileMssages.size()>0){
                JSONObject fileMessage=fileMssages.getJSONObject(0);
                logger.info("合同文本获取 getContractDownloadUrl -------fileMessage:{} ",fileMessage);
                String downerUrl=fileMessage.getString("url");
                String path= AliyunOSSClientUtil.saveUrlWeb(downerUrl);
                logger.info(">>>>>>>>>>>>>getContractDownloadUrl  path:{}",path);
                return path;
            }else {
                throw new BusinessException("合同文本获取失败!失败原因："+re.get("message"));
            }

        } else {
            throw new BusinessException("合同文本获取失败!失败原因："+re.get("message"));
        }
    }


    /**修改合同状态
     * 进件审核通过，合同待签约及合同签约驳回的数据。对应越秀合同文本状态（农户）接口状态为：CREATED-已生成
     *
     *进件审核通过，合同已签约的数据。
     * 对应越秀合同文本状态（农户）接口状态为：
     * UNAUDITED-待审核（承租人签署完毕）
     * AUDITED-已审核（农户投放审查通过）
     * SIGNED-已签约（盖章完成）
     *
     *
     * partnersContractNumber  进件序号
     */
    @Transactional(rollbackFor = Exception.class)
    public void editContractStatusAfterLook(QueryDocumentRes res,String partnersContractNumber,CustomerEntry entry){
//        if("2".equals(entry.getTenantType())){
//             return;
//        }
        logger.info("editContractStatusAfterLook partnersContractNumber:{} ",partnersContractNumber);
        Date date=new Date();
        String contractTextStatus=res.getContractTextStatus();   //合同文本状态（农户） UNCREATED-未生成;CREATED-已生成;UNAUDITED-待审核（承租人签署完毕）;AUDITED-已审核（越秀农户投放审查通过）;SIGNED-已签约（盖章完成）
        String contractStatus="";
        String applyStatus="";
        String managementId="";
        String reason="";
        Date tenantSignTime = null;
        Date time = null;
        if(StringUtil.isNotBlank(res.getContractNumber())){//合同编号
            CrmCustomerContractManagement management= contractManagementDao.getByContractNumber(res.getContractNumber());
            if(management!=null){
                logger.info("editContractStatusAfterLook managementId:{} ",management.getId());
                managementId=management.getId();
                time = management.getTenantSignTime();
            }
            if(management==null && "CREATED".equals(contractTextStatus)){ //创建合同
                logger.info("editContractStatusAfterLook  CREATED:{} ",partnersContractNumber);
                //如果有合同重签的情况，那么要删除之前的合同，重签合同的合同编码和之前是不一样的
                contractManagementDao.changeHistoryContractStatus(partnersContractNumber);
               /* management= new CrmCustomerContractManagement();
                management.setEntryId(entry.getId());
                management.setContractNumber(res.getContractNumber());
                management.setPowerStationCode(entry.getPowerStationCode());
                management.setTraderId(entry.getDistributorId());
                management.setTenantSignTime(date);
                management.setStatus(ESignConstants.YX_CONTRACT_STATUS_WAIT);
                management.setUpdateTime(date);
                management.setInvitationTime(date);
                management.setPartnersContractNumber(partnersContractNumber);
                contractManagementDao.save(management);*/
                StringBuffer sf=new StringBuffer();
                sf.append(" INSERT INTO crm_customer_contract_management(id,contract_number,entry_id,power_station_code,trader_id,STATUS,update_time,invitation_time,partners_contract_number) ");
                sf.append(" VALUES(?,?,?,?,?,'1',NOW(),NOW(),?) ");
                int i= Db.update(sf.toString(), IdGen.uuid(),res.getContractNumber(),entry.getId(),entry.getPowerStationCode(),entry.getDistributorId(),partnersContractNumber);
                logger.info("editContractStatusAfterLook  add:{}",i);
                //修改电站的签约状态
                entry.setSignStatus(ESignConstants.YX_CONTRACT_STATUS_WAIT);
                entry.setApplyStatus(YueXiuConstants.APPLY_STATUS_CONTRACT_WAIT);
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"3","","",null,"推送");
             /*   incomingApplicationDao.update(" UPDATE CrmCustomerIncomingApplication set contractTextStatus=:p1 where partnersContractNumber=:p2 ",new Parameter(contractTextStatus,partnersContractNumber));*/
                return;
            }else if(management!=null && "CREATED".equals(contractTextStatus)){
                contractStatus=ESignConstants.YX_CONTRACT_STATUS_WAIT;
                applyStatus=YueXiuConstants.APPLY_STATUS_CONTRACT_WAIT;
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"3","","",null,"");
            }else if("SIGNED".equals(contractTextStatus)){
                contractStatus=ESignConstants.YX_CONTRACT_STATUS_SIGN;
                applyStatus=YueXiuConstants.APPLY_STATUS_CONTRACT_SIGN;
                tenantSignTime = new Date();
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"3",contractTextStatus,"0","1",null);
            }else if("UNAUDITED".equals(contractTextStatus)){
                contractStatus=ESignConstants.YX_CONTRACT_STATUS_AUDIT;
                applyStatus=YueXiuConstants.APPLY_STATUS_CONTRACT_AUDIT;
                tenantSignTime = new Date();
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"3",contractTextStatus,"0","0",null);
            }else if("AUDITED".equals(contractTextStatus)){
                contractStatus=ESignConstants.YX_CONTRACT_STATUS_FINISH;
                applyStatus=YueXiuConstants.APPLY_STATUS_CONTRACT_APPROVE;
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"3",contractTextStatus,"0","2",null);
            }
        }

        logger.info(">>>>>>>>>>>editContractStatusAfterLook  contractStatus:{}",contractStatus);
        //修改电站和合同表的状态
        if(StringUtil.isNotBlank(contractStatus)){
            entry.setSignStatus(contractStatus);
            if(StringUtil.isBlank(entry.getNextApplyStatus())){
                entry.setApplyStatus(applyStatus);
            }
            if(StringUtil.isNotBlank(managementId)){
                if (time == null){
                    contractManagementDao.update("UPDATE CrmCustomerContractManagement SET status=:p1,reason=:p2,tenantSignTime=:p3 WHERE id=:p4 ",new Parameter(contractStatus,reason,tenantSignTime,managementId));
                }else {
                    contractManagementDao.update("UPDATE CrmCustomerContractManagement SET status=:p1,reason=:p2 WHERE id=:p3 ",new Parameter(contractStatus,reason,managementId));
                }
              /*  incomingApplicationDao.update(" UPDATE CrmCustomerIncomingApplication set contractTextStatus=:p1 where partnersContractNumber=:p2 ",new Parameter(contractTextStatus,partnersContractNumber));*/
            }
        }

    }

}
