package com.sifang.modules.smallprogram.yuexiu;

import com.jfinal.plugin.activerecord.Db;
import com.sifang.modules.customer.Service.CustomerContractManagementService;
import com.sifang.modules.customer.Service.GuangFaContractService;
import com.sifang.modules.customer.Service.YueXiuContractService;
import com.sifang.modules.customer.constant.PartnerConstants;
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.CrmCustomerIncomingApplicationPerInfo;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.form.QueryDocumentRes;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.web.BaseExceptionController;
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.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/main/yueXiuContract")
public class YueXiuContractController extends BaseExceptionController {

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

    @Autowired
    private YueXiuContractService yueXueContractService;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    private GuangFaContractService guangFaContractService;

    @Autowired
    private CustomerEntryDao entryDao;

    @Value("${yx.contract.jump.url}")
    private String JUMP_URL;

    //查询农户单据状态
    @ResponseBody
    @RequestMapping(value = "queryDocumentStatus")
    public Result queryDocumentStatus(String entryId){
        logger.info(">>>>>queryDocumentStatus  entryId:{}",entryId);
        QueryDocumentRes res=yueXueContractService.queryDocumentStatus(entryId);
        return Result.ok();
    }

    //签约/重新签约  --获取签约的url--越秀
    //UNCREATED-未生成 CREATED-已生成 UNAUDITED-待审核（承租人签署完毕） AUDITED-已审核（越秀农户投放审查通过） SIGNED-已签约（盖章完成）
    @ResponseBody
    @RequestMapping(value = "toContractPage")
    public Result toContractPage(String entryId,String type){
        logger.info(">>>>>>>>>>>>>>toContractPage  entryId:{},type:{}",entryId,type);
        //获取进件申请
        if(StringUtil.isBlank(type)){
            type="00";
        }
        return getContractUrl(entryId, type);
    }

    public Result getContractUrl(String entryId,String type) {
        QueryDocumentRes res=yueXueContractService.queryDocumentStatus(entryId);
        String contractTextStatus=res.getContractTextStatus();
        logger.info(">>>>>>>>>>>>>toContractPage contractTextStatus:{} ",contractTextStatus);
        if("CREATED".equals(contractTextStatus)){ //已生成
            String mw=res.getPartnersContractEncr();  //密文
            //判断 1)不传co_signer字段请求时，默认返回承租人签约相关；2)co_signer=00时，返回承租人签约相关；3)co_signer=01时，返回共签人签约相关；
            String coSigner=type;
            //获取签约地址
            String contractUrl = String.format(JUMP_URL,mw,coSigner);
            Map map=new HashMap();
            map.put("contractUrl",contractUrl);
            CrmYxIncomingProcessDao.addIncomingProcess(entryId,"3","","0",null,null);
            return Result.success(map);
        }else if ("UNCREATED".equals(contractTextStatus)){
            return Result.fail("农户合同未生成，不能进行签约!");
        }else if("UNAUDITED".equals(contractTextStatus)){
            return Result.fail("农户合同审核中，不能重复签约!");
        }else if("AUDITED".equals(contractTextStatus) || "SIGNED".equals(contractTextStatus)){
            return Result.fail("农户合同已签约，不能重复签约!");
        } else {
            return Result.fail("农户合同文本状态不支持签约，不能进行签约!");
        }
    }

    //查看合同  获取合同地址
    @ResponseBody
    @RequestMapping(value = "getContractUrlToLook")
    public Result getContractUrlToLook(String entryId) throws IOException {
        logger.info(">>>>>>>>>>>>>>getContractUrlToLook  entryId:{}",entryId);
        CrmCustomerContractManagement management=contractManagementDao.getContractByEntryId(entryId);
        CustomerEntry customerEntry = entryDao.get(entryId);
        String partnerId = customerEntry.getPartnerId();
        if(partnerId.equals(PartnerConstants.PARTNER_ID_YX)){
            Map<String,String> resultMap=new HashMap<>();
            if(StringUtil.isBlank(management.getContractUrl())){
                try {
                    String URL=yueXueContractService.getContractDownloadUrl(management.getPartnersContractNumber());
                    if("5".equals(management.getStatus())){ //已审核的合同
                        management.setContractUrl(URL);
                        contractManagementDao.save(management);
                    }
                    resultMap.put("url",URL);
                    return Result.success(resultMap);
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.info(">>>>>>>>>>>getContractUrlToLook e:{}",e);
                    return Result.fail("获取合同地址失败,"+e.getMessage());
                }
            }else {
                resultMap.put("url",management.getContractUrl());
            }
            return Result.success(resultMap);
        }else if(partnerId.equals(PartnerConstants.PARTNER_ID_GF)){
            try {
                String res = guangFaContractService.download(entryId);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("url", res);
                return Result.success(resultMap);
            } catch (Exception e) {
                logger.info(">>>>>>>>>>>preview e:{}",e);
                return Result.fail("获取合同地址失败,"+e.getMessage());
            }
        }else if(partnerId.equals(PartnerConstants.PARTNER_ID_HR) && StringUtil.isNotBlank(management.getContractUrl())){
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("url", management.getContractUrl());
            return Result.success(resultMap);
        }
        return Result.fail("获取合同地址失败!!!!");
    }

    //查看合同  获取合同地址
    @ResponseBody
    @RequestMapping(value = "getContractUrlForPC")
    public Result getContractUrlForPC(String entryId, String type){
        logger.info(">>>>>>>>>>>>>>getContractUrlForPC  entryId:{}",entryId);
        Result result = getContractUrl(entryId, type);
        if (result.isOk() && "00".equals(type)) {
            contractManagementDao.setIfClick(entryId);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "ecordClickSign")
    public Result recordClickSign(String entryId){
        contractManagementDao.setIfClick(entryId);
        return Result.ok();
    }



}
