package com.sifang.modules.customer.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.sifang.modules.customer.Service.*;
import com.sifang.modules.customer.constant.YueXiuConstants;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationDao;
import com.sifang.modules.customer.dao.CrmYxProcessDao;
import com.sifang.modules.customer.dao.TenantYxBankCardDao;
import com.sifang.modules.customer.entity.CrmCustomerIncomingApplication;
import com.sifang.modules.customer.entity.CrmTenantYxBankCard;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.form.QueryDocumentRes;
import com.sifang.modules.customer.form.YueXiuHeadForm;
import com.sifang.modules.customer.form.YueXueBankCardVo;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.StringUtil;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(value = "${adminPath}/main/yueXiu")
public class YueXiuCallBackController{


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

    @Autowired
    private YueXiuContractService yueXiuContractService;

    @Autowired
    private OperatingLeaseService leaseService;

    @Autowired
    private YueXiuBankCardService yueXiuBankCardService;
    @Autowired
    private CustomerEntryExtraService customerEntryExtraService;

    @Autowired
    private CustomerEntryService customerEntryService;

    @Autowired
    private CrmCustomerIncomingApplicationDao crmCustomerIncomingApplicationDao;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Value("${yx.setting}")
    private String YX;
    /**
     * 越秀单据状态主动推送 接口
     *
     * 支持在以下时点主动推送，推送时返回对应时点前所有存在数据的状态：
     *   1）承租人预审；
     *   2）风险审查流程审批通过/拒绝；
     *   3）承租人签署完成；
     *   4）农户投放审查流程审批通过/拒绝；
     */
    @ResponseBody
    @RequestMapping(value = "receiptDocumentStatus")
    public Object receiptDocumentStatus(@RequestBody String pushStr) {
        logger.info("receiptDocumentStatus================ json：{}",pushStr);
        Map<String,Object> resultMap=new LinkedHashMap<>();
        String date=DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss");
        //处理返回json
        YueXiuHeadForm headForm=new YueXiuHeadForm(UUID.randomUUID().toString(), YueXiuConstants.CLIENT_ID,"YX_FINANCE_PROJECT_OL_STATUS_SEND"+YX,date,1);
        Map<String,Object> bodyMap=new LinkedHashMap<>();
        Gson gson=new Gson();
        String partnersContractNumber="";
        try {
            JSONObject jsonObject=JSONObject.parseObject(pushStr);
            JSONArray reqMap = jsonObject.getJSONArray("body");
            JSONObject re = reqMap.getJSONObject(0);
            logger.info(">>>>>>>>>>>>receiptDocumentStatus re:{}",re);
            partnersContractNumber=re.getString("businessKey");  //进件序号
            QueryDocumentRes res=re.getObject("prjProjectOperatingLeaseStatus",QueryDocumentRes.class);
            //根据进件序号 获取电站id(目前的进件可以取消，那么如果取消的话，重新进件，就会有一个新的进件序号)
            //****(越秀)支持各合作方主动取消进件，需注意取消的进件无法再次推送，如要继续进行业务，需使用新的合作方进件序号进行新的进行，支持取消的单据状态说明如下
            CrmCustomerIncomingApplication incomingApplication=crmCustomerIncomingApplicationDao.getByPartnersContractNumber(partnersContractNumber); //预审的时候，没有进件 返回的businessKey，是身份证号
            if(incomingApplication!=null){
                String entryId=incomingApplication.getEntryId();
                CustomerEntry entry=customerEntryService.getById(entryId);
                //修改合同状态
                yueXiuContractService.editContractStatusAfterLook(res,partnersContractNumber,entry);
                //更新进件状态
                customerEntryExtraService.updateIncomingApplicationStatus(res,partnersContractNumber,entry,incomingApplication);
            }else { //根据返回的businessKey 没找到进件申请，那么是由于还没有进件，还在预审状态
                //更新进件状态
                customerEntryExtraService.updateIncomingApplicationStatus(res,partnersContractNumber,null,incomingApplication);
            }
            //处理返回json
            headForm.setErrorCode("01");
            bodyMap.put("businessKey",partnersContractNumber);
            bodyMap.put("type","S");
            bodyMap.put("message","接口同步成功！");
        }catch (Exception e) {
            logger.error(">>>>>>>>>>>>>>>>>>receiptDocumentStatus 接口同步失败 e:{}", e);
            bodyMap.put("type","E");
            bodyMap.put("message","接口同步失败！");
        }
        resultMap.put("body",bodyMap);
        resultMap.put("head",headForm);
        String str=gson.toJson(resultMap);
        CrmYxProcessDao.addProcess(partnersContractNumber,"5","单据状态主动推送",pushStr,str,"0");
        logger.info(">>>>>>>>>>>>>>>callBack22  STR:{}",str);
        return str;
    }

    /**
     * 二类卡账户状态推送
     */
    @ResponseBody
    @RequestMapping(value = "openCardStatus")
    public Object openCardStatus(@RequestBody String pushStr){
        logger.info("openCardStatus================ json：{}",pushStr);
        Map<String,String> resultMap=new LinkedHashMap<>();
        String businessKey="";
        try{
            JSONObject jsonObject=JSONObject.parseObject(pushStr);
            JSONArray reqMap = jsonObject.getJSONArray("body");
            JSONObject re = reqMap.getJSONObject(0);
            logger.info(">>>>>>>>>>>>openCardStatus reJson:{}",re.toJSONString());
            YueXueBankCardVo vo=JSONObject.parseObject(re.toJSONString(), YueXueBankCardVo.class);
            businessKey=vo.getBusinessKey();
            logger.info(">>>>>>>>>>>>openCardStatus re:{}",re);
            resultMap.put("corpCommSerno",vo.getBusinessKey());
            CrmTenantYxBankCard card=tenantYxBankCardDao.getByCorpCommSerno(vo.getBusinessKey());
            yueXiuBankCardService.editBankCardStatus(vo,card);
            tenantYxBankCardDao.save(card);
            resultMap.put("type","S");
            resultMap.put("message","推送成功！");
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>>>>>openCardStatus 二类卡账户状态推送 e:{}", e);
            resultMap.put("type","E");
            resultMap.put("message","推送失败！");
        }
        Gson gson=new Gson();
        String str=gson.toJson(resultMap);
        CrmYxProcessDao.addProcess(businessKey,"6","承租人二类卡账户状态推送",pushStr,str,"0");
        logger.info(">>>>>>>>>>>>>>>openCardStatus  str:{}",str);
        return str;
    }

    /**
     * 手动触发第一次进件（初始化数据第一次进件）
     */
    @ResponseBody
    @RequestMapping(value = "initFirstApplyEntry")
    public Result initFirstApplyEntry(String powerStationCode){
        try{
            yueXiuBankCardService.initFirstApplyEntry(powerStationCode);
        }catch (IllegalArgumentException i){
            return Result.fail("进件失败，失败原因:"+i.getMessage());
        }
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "findOauthToken")
    public Object findOauthToken(){
        return leaseService.findOauthToken();
    }

}
