package com.sunxung.factoring.web.purchcontractmanagement;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunxung.factoring.component.annotation.OperationLog;
import com.sunxung.factoring.component.enums.OperationTypeEnum;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.ElectronicSignatureUtil;
import com.sunxung.factoring.component.util.StringUtil;
import com.sunxung.factoring.component.util.ThreadLocalUtil;
import com.sunxung.factoring.component.util.fdd.TransactionIdCache;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.acceptance.AcceptanceSignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.customerinformation.Customer;
import com.sunxung.factoring.entity.customerinformation.ElectronicSignaturePersonal;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.purchcontractmanagement.*;
import com.sunxung.factoring.entity.settlement.SettlementElectronicInfo;
import com.sunxung.factoring.entity.signconfirmation.SignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.service.acceptancesheet.IAcceptanceSignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.customerinformation.CustomerService;
import com.sunxung.factoring.service.customerinformation.IElectronicSignaturePersonalService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.purchcontractmanagement.*;
import com.sunxung.factoring.service.settlement.SettlementElectronicInfoService;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.supplier.ICSupplierInfoHistoryService;
import com.sunxung.factoring.service.supplier.ISupplierInfoService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description : 采购合同签署controller
 * @Author : JiaYf
 * @Date: 2021-09-22 19:07
 */
@Controller
@RequestMapping("/purchContract/confirm")
public class PurchContractConfirmController {

    private final String prefix = "purchaseContract";

    private static Logger logger = LogManager.getLogger(PurchContractConfirmController.class);

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private PurchContractService purchContractService;

    @Autowired
    private PurchContractElectronicInfoService purchContractElectronicInfoService;

    @Autowired
    private IPurchContractSupplementElectronicInfoService supplementElectronicInfoService;

    @Autowired
    private IPurchContractSupplementInfoService supplementInfoService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private UserService userService;

    @Autowired
    private SettlementElectronicInfoService settlementElectronicInfoService;

    @Autowired
    TransactionIdCache transactionIdCache;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Value("${sop.synchronizeInformation}")
    private String synchronizeInformation;

    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;

    @Autowired
    private ISignConfirmationElectronicInfoService signConfirmationElectronicInfoService;

    @Autowired
    private IAcceptanceSignConfirmationElectronicInfoService acceptanceSignConfirmationElectronicInfoService;

    /**
     * 删除电子合同信息  以生成新的合同链接
     * @param businessKey
     * @return
     */
    @RequestMapping("/flush/url")
    @ResponseBody
    @OperationLog(operationModule = "采购合同",operationType = OperationTypeEnum.UPDATE,description = "删除电子合同信息  以生成新的合同链接")
    public ResponseJson flushUrl(Long businessKey) {
        //签署后流程
        purchContractElectronicInfoService.flushUrl(businessKey);
        return new ResponseJson("链接刷新成功！");
    }


    /**
     * 签署回调
     *
     * @param contractId
     * @param transactionId
     * @return
     */
    @PostMapping("/signBack")
    @ResponseBody
    @CrossOrigin
    public synchronized void doSignBack(String contractId, String transactionId) {
        logger.error("=========================");
        logger.error("contractId:" + contractId);
        logger.error("transactionId:" + transactionId);
        logger.error("=========================");

        String[] fdds = transactionId.split("FDD");

        //新回调方式
        if (fdds == null || fdds.length < 2) {
//            String objStr = (String) transactionIdCache.getObjByTransactionId(transactionId);
//            if (StringUtil.isEmpty(objStr)) {
//                throw new ValidatorException(CodeUtil.PARAMETER_ERROR, "该签署信息已经失效!");
//            }
//            String[] objStrs = objStr.split("FDD");

            PurchContractSupplementElectronicInfo purchContractSupplementElectronicInfo = supplementElectronicInfoService.lambdaQuery().eq(PurchContractSupplementElectronicInfo::getContractId, contractId).one();
            PurchContractElectronicInfo purchContractElectronicInfo = purchContractElectronicInfoService.lambdaQuery().eq(PurchContractElectronicInfo::getContractId, contractId).one();
            SignConfirmationElectronicInfo signConfirmationElectronicInfo = signConfirmationElectronicInfoService.lambdaQuery().eq(SignConfirmationElectronicInfo::getContractId, contractId).one();
            AcceptanceSignConfirmationElectronicInfo acceptanceSignConfirmationElectronicInfo = acceptanceSignConfirmationElectronicInfoService.lambdaQuery().eq(AcceptanceSignConfirmationElectronicInfo::getContractId, contractId).one();
            if (purchContractElectronicInfo != null) {
                if (purchContractElectronicInfo.getCallBack().equals(0)) {
                    //采购合同签署回调
                    purchContractElectronicInfoService.doSignCallBack(contractId);
                }
            } else if (purchContractSupplementElectronicInfo != null) {
                if (purchContractSupplementElectronicInfo.getCallBack().equals(0)) {
                    //采购合同变更签署回调
                    supplementInfoService.doSignChangeCallBack(contractId);
                }
            } else if (signConfirmationElectronicInfo != null) {
                //签署确认回调
                signConfirmationElectronicInfoService.doSignCallBack(signConfirmationElectronicInfo);

            }else if(acceptanceSignConfirmationElectronicInfo != null){
                acceptanceSignConfirmationElectronicInfoService.doSignCallBack(acceptanceSignConfirmationElectronicInfo);
            }
        } else {
            //结算单签署回调
            if (transactionId.startsWith("signSettlement")) {
                //transactionId 是由 "signSettlement" +settlementBasicInfoId + "taskId" + "userId" 构成的
                Long settlementBasicInfoId = Long.valueOf(fdds[1]);
                String taskId = fdds[2];
                Long userId = Long.valueOf(fdds[3]);
                User user = userService.get(userId);
                ThreadLocalUtil.setUser(user);
                SettlementElectronicInfo settlementElectronicInfo = settlementElectronicInfoService.getOne(new QueryWrapper<SettlementElectronicInfo>().eq("settlement_basic_info_id", settlementBasicInfoId));
                //合同下载
                String contDownUrl = ElectronicSignatureUtil.downloadContract(contractId);
                FileStorage contractSupplementFile = fileStorageService.addFileStorageWithBelongAndName(fdds[1], FileModuleDict.ChildEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE, contDownUrl, null);
                fileStorageService.saveAttachmentRefByFileStorage(contractSupplementFile, FileModuleDict.ChildEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE, Long.valueOf(fdds[1]));
                //合同归档
                ElectronicSignatureUtil.contractFiled(contractId);
                //电子文件签署线上出证下载
                String reportDownUrl = ElectronicSignatureUtil.complianceContractReport(contractId);
                FileStorage contractSupplementReportFile = fileStorageService.addFileStorageWithBelongAndName(fdds[1], FileModuleDict.ChildEnum.SETTLEMENT_CONTRACT_REPORT, reportDownUrl, null);
                fileStorageService.saveAttachmentRefByFileStorage(contractSupplementReportFile, FileModuleDict.ChildEnum.SETTLEMENT_CONTRACT_REPORT, Long.valueOf(fdds[1]));
                //获取最新签署信息，更新签署状态
                settlementElectronicInfo.setSignStatus(1);
                settlementElectronicInfoService.updateById(settlementElectronicInfo);
                //签署后流程
                settlementElectronicInfoService.sign(settlementElectronicInfo, taskId);
                //清除用户信息
                ThreadLocalUtil.clearThreadVariable();
            } else if (transactionId.startsWith("platformFDD")) {
                //transactionId 是由 "platformFDD" + platform.getId()+"FDD"+ DateUtil.getCurrentDate().replace("-","").replace(" ","").replace(":","") 构成的
                Platform platform = platformService.getById(Long.valueOf(fdds[1]));
                platform.setAutoSignStatus(true);
                platformService.updateById(platform);
            }
        }
    }

    /**
     * 获取认证信息
     *
     * @return
     */
    @PostMapping("/getAuthInfo")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Object getAuthInfo(@RequestBody Platform platform) throws ValidatorException {
        String result = ElectronicSignatureUtil.getAuthInfoDetail(platform.getFddCustomerId(), "2");
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject company = data.getJSONObject("company");
        String verifyType = company.getString("verifyType");
        switch (verifyType){
            case "0":
                verifyType = "银行卡认证";
                break;
            case "1":
                verifyType = "纸质审核认证";
                break;
            case "2":
                verifyType = "法人认证";
                break;
            case "4":
                verifyType = "法人授权认证";
                break;

        }
        String legalName = company.getString("legalName");
        String legal = company.getString("legal");
        JSONObject manager = data.getJSONObject("manager");
        String legalMobile = manager.getString("mobile");
        JSONObject json = new JSONObject();
        json.put("verifyType",verifyType);
        json.put("legalName",legalName);
        json.put("legal",legal);
        json.put("legalMobile",legalMobile);
        return new ResponseJson(json);
    }


    /**
     * 刷新认证状态
     *
     * @param customerId
     * @return
     */
    @GetMapping("/getAuthStatus")
    @ResponseBody
    public Object getAuthStatus(String customerId) {
        if (StringUtil.isEmpty(customerId)) {
            throw new ValidatorException(CodeUtil.FAIL, "参数不能为空!");
        }

        Enterprise customer = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("fdd_customer_id", customerId));
        ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.lambdaQuery().eq(ElectronicSignaturePersonal::getFddCustomerId, customerId).one();
        if (customer != null) {
            //先从sop更新信息
            ResponseJson forObject = restTemplate.getForObject(synchronizeInformation+"?socialCreditCode="+customer.getSocialCreditCode(), ResponseJson.class);
            Map<String,String> data = (Map) forObject.getData();
            customer.setAuthUrl(data.get("authUrl"));
            customer.setShortAuthUrl(data.get("shortAuthUrl"));
            customer.setCertificateSignUrl(data.get("certificateSignUrl"));
            customer.setCertificateShortSignUrl(data.get("certificateShortSignUrl"));
            customer.setFddCustomerId(data.get("fddCustomerId"));
            customer.setCertificateContractId(data.get("certificateContractId"));
            customer.setCertificateTransactionId(data.get("certificateTransactionId"));
            //更新自动签链接
            customer.setAutoSignUrl(data.get("autoSignUrl"));
            customer.setShortAutoSignUrl(data.get("shortAutoSignUrl"));
            enterpriseService.updateById(customer);

            //再查询状态
            String result = ElectronicSignatureUtil.getAuthInfo(customer.getSocialCreditCode(), "2");
            if ("1".equals(result)) {
                customer.setAuthStatus(true);
                enterpriseService.updateById(customer);
                purchContractElectronicInfoService.lambdaUpdate()
                        .eq(PurchContractElectronicInfo::getFddCustomerId, customer.getFddCustomerId())
                        .set(PurchContractElectronicInfo::getCertifyStatus, 1)
                        .update();
            }
            return new ResponseJson(customer);
        }
        if (electronicSignaturePersonal != null) {
            String authDeatil = electronicSignaturePersonalService.getAuthDeatil(customerId);
            JSONObject json = (JSONObject) JSONObject.parse(authDeatil);
            if (!"1".equals(json.getString("code"))) {
                throw new BusinessException(CodeUtil.FAIL, "法大大获取实名信息出现异常：" + json.getString("msg"));
            } else {
                String status = json.getJSONObject("data").getJSONObject("person").getString("status");
                if ("2".equals(status)) {
                    String idCard = json.getJSONObject("data").getJSONObject("person").getString("idCard");
                    electronicSignaturePersonal.setSocialCreditCode(idCard);
                }else {
                    throw new BusinessException(CodeUtil.FAIL, "法大大获取实名信息出现异常：" + json.getString("msg"));
                }
            }
            electronicSignaturePersonal.setAuthStatus(1);
            electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
            return new ResponseJson(electronicSignaturePersonal);
        }

        throw new ValidatorException(CodeUtil.FAIL,"刷新认证状态出错！");
    }

}
