package com.sifang.modules.customer.controller;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerContractManagementService;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.ContractManagementDao;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationDao;
import com.sifang.modules.customer.entity.CrmCustomerContractManagement;
import com.sifang.modules.customer.entity.CrmCustomerIncomingApplication;
import com.sifang.modules.esign.cn.tsign.hz.exception.EsignDemoException;
import com.sifang.modules.esign.constants.ESignConstants;
import com.sifang.modules.esign.service.ESignSignService;
import com.sifang.modules.esign.service.PartnerContractESignSignService;
import com.sifang.modules.partner.service.GuangfaOperatingService;
import com.sifang.modules.partner.utils.GuangfaQryContractVO;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
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.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.GuardUtils;
import com.sifang.modules.sys.util.LayuiPage;
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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 农户合同
 */
@Controller
@RequestMapping(value = "${adminPath}/customerContract")
public class CustomerContractManagementController extends BaseExceptionController {

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

    @Autowired
    private CustomerContractManagementService contractManagementService;

    @Autowired
    TraderService traderService;

    @Autowired
    AddressService addressService;

    @Autowired
    private GuangfaOperatingService guangfaOperatingService;

    @Autowired
    CrmCustomerIncomingApplicationDao incomingApplicationDao;

    @Autowired
    CustomerEntryService customerEntryService;

    @Autowired
    MemberService memberService;

    @Autowired
    PartnerContractESignSignService partnerContractESignSignService;

    @Autowired
    PartnerService partnerService;

    @RequestMapping(value = "customerContractList/{partner}")
    public String customerContractList(@PathVariable("partner")String partner , Model model) {
        User user = UserUtils.getUser();
        List<Record> projectList = memberService.getProjectLists();
        model.addAttribute("projectList", projectList);
        model.addAttribute("user", user);
        String traderId=user.getTraderId();
        model.addAttribute("ifTop",user.getTraderType());
        List<Record> twoTrader=traderService.getTwoTrader(traderId);
        model.addAttribute("twoTrader",twoTrader);
        //代理商列表
        List<Record> traderList = traderService.getTopTrader();
        model.addAttribute("traderList", traderList);
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("province", pros);
        model.addAttribute("partner",partner);
        model.addAttribute("downloadBtnPermission","XMGL_NHHT_DOWNLOAD_B_"+partner);
        switch (partner) {
            case PartnerConstants.PARTNER_ID_YX:
                return "modules/yangguang/systemSetting/contract/customerContractList";
            case PartnerConstants.PARTNER_ID_GF:
                model.addAttribute("signBtnPermission","XMGL_NHHT_SIGN_B_"+partner);
                model.addAttribute("previewBtnPermission","XMGL_NHHT_PREVIEW_B_"+partner);
                model.addAttribute("terminateBtnPermission","XMGL_NHHT_TERMINATE_B_"+partner);
                model.addAttribute("doSealBtnPermission","XMGL_NHHT_DOSEAL_B_"+partner);
                return "modules/yangguang/systemSetting/contract/customerContractList3";
            case PartnerConstants.PARTNER_ID_HR:
                model.addAttribute("uploadBtnPermission","XMGL_NHHT_UPLOAD_B_"+partner);
                model.addAttribute("getUrlBtnPermission","XMGL_NHHT_GETURL_B_"+partner);
                model.addAttribute("previewBtnPermission","XMGL_NHHT_PREVIEW_B_"+partner);
                model.addAttribute("terminateBtnPermission","XMGL_NHHT_TERMINATE_B_"+partner);
                model.addAttribute("createContractAgainPermission","XMGL_NHHT_AGAIN_CONTRACT_B_"+partner);
                CrmPartner partnerEntry = partnerService.getById(partner);
                model.addAttribute("partnerEntry",partnerEntry);
                return "modules/yangguang/systemSetting/contract/customerContractList2";
        }
        throw new BusinessException();
    }

    //列表数据
    @ResponseBody
    @RequestMapping(value = "ContractListDate")
    public Object getSite(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        contractManagementService.listDate(page, map,operator);
        return page.renderJson();
    }

    //上传合同
    @RequestMapping(value = "uploadContract")
    public String uploadContract(HttpServletRequest request, Model model) {
        Map<String, String> map = getParams(request);
        Record contract = contractManagementService.getOneById(map);
        int contractFilesCount = 0;
        if(StringUtil.isNotBlank(contract.getStr("contractUrl"))){
            String[] arr=contract.getStr("contractUrl").split(",");
            contractFilesCount = arr.length;
        }
        model.addAttribute("contractFilesCount", contractFilesCount);
        model.addAttribute("contract", contract);
        return "modules/yangguang/systemSetting/contract/uploadContract";
    }

    //删除合同
    @ResponseBody
    @RequestMapping(value = "deleteContract")
    public Result<Void> deleteContract(String ids) {
        GuardUtils.notBlank(ids, "ids不能为空");
        contractManagementService.deleteContract(ids);
        return Result.ok();
    }
    //广发合同 状态同步
    @ResponseBody
    @RequestMapping(value = "tbContractStatus")
    public Result tbContractStatus(String entryIds) {
        if (StringUtil.isBlank(entryIds)){
            return Result.fail("entryIds不能为空");
        }
        logger.info(" tbContractStatus  entryIds:{}",entryIds);
        String[] ids = entryIds.split(",");
        List<String> inputPieceIds = new ArrayList<>();
        for (String id : ids) {
            CrmCustomerIncomingApplication incomingApplication = incomingApplicationDao.getByEntryId(id);
            inputPieceIds.add(incomingApplication.getInputPieceId());
        }
        for (String inputPieceId : inputPieceIds) {
            List<String> idList = new ArrayList<>();
            idList.add(inputPieceId);
            if (!StringUtils.isEmpty(idList)){
                List<GuangfaQryContractVO> result = guangfaOperatingService.queryContract(PartnerConstants.PARTNER_ID_GF, idList);
                GuangfaQryContractVO v = result.get(0);
                try {
                    String status = v.getContractState();
                    String contractNormState = v.getContractNormState();
                    Record record = Db.findFirst(" select entry_id from crm_customer_incoming_application where if_delete = '0' and  input_piece_id = ? ", v.getInputPieceId());
                    customerEntryService.updateContractState(status,record.getStr("entry_id"),v.getContractNo(),contractNormState);
                } catch (Exception e) {
                    logger.warn("tbContractStatus fail for"+v.getInputPieceId(), e);
                }
            }
        }
        return Result.ok();
    }

    /**
     * 华融  获取合同链接
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getSignUrl")
    public Result getSignUrl(String id) {
        try {
            String contractUrl = partnerContractESignSignService.getSignUrl(id);
            Map<String,Object> resultMap=new HashMap<>();
            resultMap.put("contractUrl",contractUrl);
            return Result.success(resultMap);
        } catch (EsignDemoException e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>getSignUrl  e:{} ", e);
            return Result.fail("获取合同签约链接失败:"+e.getMessage());
        }catch (Exception w) {
            w.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>getSignUrl  w:{} ", w);
            return Result.fail("获取合同签约链接失败!");
        }
    }

    /**
     * 华融 预览合同
     */
    @ResponseBody
    @RequestMapping(value = "getFilePreviewUrl")
    public Result getFilePreviewUrl(String id){
        try {
            String contractUrl = partnerContractESignSignService.getFilePreviewUrl(id);
            Map<String,Object> resultMap=new HashMap<>();
            resultMap.put("previewUrl",contractUrl);
            return Result.success(resultMap);
        } catch (EsignDemoException e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>getFilePreviewUrl  e:{} ", e);
            return Result.fail("获取预览合同链接失败:"+e.getMessage());
        }catch (Exception w) {
            w.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>getFilePreviewUrl  w:{} ", w);
            return Result.fail("获取预览合同链接失败!");
        }
    }

    /**
     * 华融 发起合同
     * id  合同id
     */
    @ResponseBody
    @RequestMapping(value = "createHuaRongContract")
    public Result createHuaRongContract(String id){
        User user=UserUtils.getUser();
        Operator operator=Operator.of(user);
        partnerContractESignSignService.createHuaRongContract(id,operator);
        return Result.ok();
    }

    /**
     * 华融 合同作废
     * id  合同id
     * reason 作废原因
     */
    @ResponseBody
    @RequestMapping(value = "revokeContract")
    public Result revokeContract(String id,String reason){
         User user=UserUtils.getUser();
         Operator operator=Operator.of(user);
         partnerContractESignSignService.revokeContract(id,reason,operator);
         return Result.ok();
    }

    /**
     * 华融 重新发起合同
     * id  合同id
     */
    @ResponseBody
    @RequestMapping(value = "createContractAgain")
    public Result createContractAgain(String id){
        User user=UserUtils.getUser();
        Operator operator=Operator.of(user);
        partnerContractESignSignService.createContractAgain(id,operator);
        return Result.ok();
    }


    /**
     * 华融 合同转换
     *  线上签约模式《===》上传 模式
     */
    @ResponseBody
    @RequestMapping(value = "changeContractPattern")
    public Result changeContractPattern(String id){
        User user=UserUtils.getUser();
        Operator operator=Operator.of(user);
        partnerContractESignSignService.changeContractPattern(id,operator);
        return Result.ok();
    }
}
