package com.trade.service.credit.service.impl;

import java.util.*;

import javax.annotation.Resource;

import com.trade.service.contract.constant.ContractConstant;
import com.trade.service.contract.util.esign.bizprocess.SignedBizProcessor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.trade.common.exception.ServiceException;
import com.trade.service.DictConstants;
import com.trade.service.contract.dto.*;
import com.trade.service.contract.service.ContractService;
import com.trade.service.contract.util.esign.ESignConstant;
import com.trade.service.credit.domain.BizEntityCreditAuth;
import com.trade.service.credit.mapper.BizEntityCreditAuthMapper;
import com.trade.service.credit.service.BizEntityCreditAuthService;
import com.trade.service.enterprise.customer.domain.Enterprise;
import com.trade.service.enterprise.customer.domain.EnterpriseRelatedPerson;
import com.trade.service.enterprise.customer.service.EnterpriseBaseService;
import com.trade.service.enterprise.customer.service.EnterpriseRelatedPersonBaseService;

/**
 * <p>
 * 企业征信授权记录 服务实现类
 * </p>
 *
 * @author zhangchenm
 * @since 2024-06-05
 */
@Service("bizEntityCreditAuthService")
public class BizEntityCreditAuthServiceImpl extends ServiceImpl<BizEntityCreditAuthMapper, BizEntityCreditAuth> implements BizEntityCreditAuthService
, SignedBizProcessor {

    @Resource
    private ContractService contractService;
    @Resource
    private EnterpriseBaseService enterpriseBaseService;
    @Resource
    private EnterpriseRelatedPersonBaseService relatedPersonBaseService;

    @Override
    public void doAuth(Long customerUserId) {
        // 查询企业信息
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerUserId);
        // 根据证件号码查询征信授权记录
        BizEntityCreditAuth bizEntityCreditAuth = this
                .getOne(new QueryWrapper<BizEntityCreditAuth>().eq("cert_no", enterprise.getCertNo()));
        if (bizEntityCreditAuth != null && 1 == bizEntityCreditAuth.getStatus()) {
            throw new ServiceException("企业已授权");
        }
        EnterpriseRelatedPerson legal = relatedPersonBaseService
                .getLegalByChangeRecordId(enterprise.getChangeRecordId());
        if (legal == null) {
            throw new ServiceException("未获取到企业法人信息");
        }
        ContractGenInputItem inputItem = getContractGenInputItem(enterprise, legal);
        // 生成合同
        ContractGenOutputItem outputItem = contractService.generateSingleContract(inputItem, customerUserId);
        // 签署合同
        ContractSignOutput signOutput = contractService
                .signContract(getContractSignInput(enterprise, legal, outputItem.getFileId()));
        // 保存签署记录
        BizEntityCreditAuth addAuth = new BizEntityCreditAuth();
        addAuth.setCertNo(enterprise.getCertNo());
        addAuth.setSignFlowId(signOutput.getFlowId());
        addAuth.setStatus(0);
        this.save(addAuth);
    }

    @NotNull
    private ContractGenInputItem getContractGenInputItem(Enterprise enterprise, EnterpriseRelatedPerson legal) {
        ContractGenInputItem inputItem = new ContractGenInputItem();
        inputItem.setTemplateCode("company_credit_auth_chink");
        inputItem.setContractName("企业征信授权书");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("companyName", enterprise.getName());
        dataMap.put("legal", legal.getName());
        inputItem.setParams(dataMap);
        return inputItem;
    }

    @NotNull
    private ContractSignInput getContractSignInput(Enterprise enterprise, EnterpriseRelatedPerson legal, Long fileId) {
        ContractSignInput signInput = new ContractSignInput();
        signInput.setBizType(ContractConstant.SIGN_BIZ_TYPE_COMPANY_AUTH_CREDIT);
        // signInput.setSignPlatform(1);
        signInput.setBizScene("贸服通-企业征信查询授权书");
        ContractSignInfo contractSignInfo = new ContractSignInfo();
        contractSignInfo.setFileId(fileId);
        ContractSigner signer = new ContractSigner();
        signer.setSigner(legal.getName());
        signer.setSignerIdNo(legal.getPersonalCertNo());
        signer.setSignerIdType(DictConstants.PERSONAL_CERT_TYPE_CN_IDCARD.equals(legal.getPersonalCertType())
                ? ESignConstant.CRED_PSN_CH_IDCARD
                : ESignConstant.CRED_PSN_PASSPORT);
        signer.setMobile(legal.getMobile());
        contractSignInfo.setSingleSigner(signer);
        List<ContractSeal> sealInfoList = new ArrayList<>();
        ContractSeal companySeal = new ContractSeal();
        // companySeal.setSigner(signer); 不设置时取singleSigner
        companySeal.setKeyword(ESignConstant.KEYWORD_COMPANY);
        companySeal.setSealIdType(ESignConstant.CRED_ORG_USCC);
        companySeal.setSealName(enterprise.getName());
        companySeal.setSealIdNo(enterprise.getCertNo());
        ContractSeal legalSeal = new ContractSeal();
        // legalSeal.setSigner(signer); 不设置时以签署人作为签章人
        legalSeal.setKeyword(ESignConstant.KEYWORD_PERSONAL);
        sealInfoList.add(companySeal);
        sealInfoList.add(legalSeal);
        contractSignInfo.setSealInfoList(sealInfoList);
        signInput.setSigneInfoList(Collections.singletonList(contractSignInfo));
        return signInput;
    }

    @Override
    public void process(SignCallback2Biz bizData) {
        BizEntityCreditAuth addAuth = this.lambdaQuery().eq(BizEntityCreditAuth::getSignFlowId, bizData.getSignFlowId())
                .one();
        if (ContractConstant.CONTRACT_SIGN_STATUS_SIGNED.equals(bizData.getSignStatus())) {
            addAuth.setStatus(1);
            addAuth.setFileStorageId(bizData.getSignedFiles().get(0).getFileId());
        } else {
            addAuth.setStatus(bizData.getSignStatus());
        }
        this.updateById(addAuth);
    }
}
