package com.engine.htxc.contract.web;

import com.engine.htxc.common.ParamValidException;
import com.engine.htxc.contract.dao.ContractDao;
import com.engine.htxc.contract.dto.*;
import com.engine.htxc.contract.entity.UserEntity;
import com.engine.integration.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.util.List;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: K1810050
 * @version: 1.0
 * @CreateDate: 2022/9/29:59
 * @Description: 合同流程数据校验
 * @ModifyLog:
 **/
public class ContractProcessValidator {

    private static final Logger logger= LoggerFactory.getLogger(ContractProcessValidator.class);
    /**
     * 最大文件数
     */
    public static final int MAX_FILE_COUNT = 100;

    private ContractProcessDTO contractProcessDTO;

    public ContractProcessValidator(ContractProcessDTO contractProcessDTO){
        this.contractProcessDTO=contractProcessDTO;
    }

    public void validate() throws ParamValidException {
        logger.info("调用系统：[{}]",contractProcessDTO.getSysCode());
        //校验 ContractProcessDTO
        if (StringUtils.isBlank(contractProcessDTO.getSysCode())) {
            throw new ParamValidException("sysCode参数不能为空");
        }
        //流程标题
        if(StringUtils.isBlank(contractProcessDTO.getProcessTitle())){
            throw new ParamValidException("流程标题不能为空");
        }
        //合同详情列表
        if(null==contractProcessDTO.getContractList()||contractProcessDTO.getContractList().isEmpty()){
            throw new ParamValidException("合同列表不能为空");
        }
        //必填，true：自动用印，false：非自动用印。
        //自动用印为true，必须传模板id（遍历合同列表判断，只要有一个不包含模板id，抛异常）
        validateAutoSeal();

        //拟稿人工号
        if (StringUtils.isBlank(contractProcessDTO.getUserCode())) {
            throw new ParamValidException("拟稿人工号为空");
        }

        //拟稿人部门
        if(StringUtils.isBlank(contractProcessDTO.getUserDeptCode())){
            throw new ParamValidException("拟稿人部门为空");
        }

        final Map<String, String> user = ContractDao.getUserByWorkcodeAndDeptCode(contractProcessDTO.getUserCode(), contractProcessDTO.getUserDeptCode());
        if(user.isEmpty()||StringUtils.isBlank(user.get("USERID"))){
            throw new ParamValidException("拟搞人不存在");
        }

        //校验合同类型
        if(StringUtils.isBlank(contractProcessDTO.getContractCategoryId())){
            throw new ParamValidException("合同类型不能为空");
        }
        final PropBean propBean = new PropBean();
        if(!ContractDao.checkCategory(propBean.getPropName("contract.jc.categoryPrefix")+"_"+contractProcessDTO.getContractCategoryId())){
            throw new ParamValidException("合同类型不存在");
        }

        //校验审批人员
        validateProcessApprovers();

        //校验 合同详情 ContractDetailDTO
        validateContractDetail();
    }

    private void validateProcessApprovers() {
        //通知阅读人员 默认主岗
        final List<UserDeptInfoDTO> noticeReaderIds = contractProcessDTO.getNoticeReaderIds();
        if(null!= noticeReaderIds &&!noticeReaderIds.isEmpty()){
            final List<UserEntity> noticeReaders = ContractDao.getUsersByWorkcodeAndJobCodeList(noticeReaderIds);
            if(noticeReaders.size()!= noticeReaderIds.size()){
                throw new ParamValidException("通知阅读人员有误");
            }
        }

        //内部审核人员
        final List<UserDeptInfoDTO> internalAuditIds = contractProcessDTO.getInternalAuditIds();
        if(null!= internalAuditIds &&!internalAuditIds.isEmpty()){
            final List<UserEntity> internalUsers = ContractDao.getUsersByWorkcodeAndJobCodeList(internalAuditIds);
            if(internalUsers.size()!= internalAuditIds.size()){
                throw new ParamValidException("内部审核人员有误");
            }
        }

        //部门领导
        final List<UserDeptInfoDTO> deptHeadIds = contractProcessDTO.getDeptHeadIds();
        if(null!= deptHeadIds &&!deptHeadIds.isEmpty()){
            final List<UserEntity> headers = ContractDao.getUsersByWorkcodeAndJobCodeList(deptHeadIds);
            if(headers.size()!= deptHeadIds.size()){
                throw new ParamValidException("部门领导人员有误");
            }
        }
    }

    private void validateAutoSeal() {
        if(contractProcessDTO.getAutoSealFlag()){
            for (ContractDetailDTO contractDetailDTO : contractProcessDTO.getContractList()) {
                final String templateNo = contractDetailDTO.getTemplateNo();
                if(StringUtils.isBlank(templateNo)){
                    throw new ParamValidException("合同名称："+contractDetailDTO.getContractName()+" 自动用印，模板编号不能为空");
                }
                if(!ContractDao.checkTemplateNo(templateNo)){
                    throw new ParamValidException("合同名称："+contractDetailDTO.getContractName()+" 模板编号查不到对应模板id");
                }
            }
        }
    }


    private void validateContractDetail() {
        //是否普通合同或在线合同校验
        final ModuleCodeEnum moduleCodeEnum = ModuleCodeEnum.valueOf(contractProcessDTO.getModuleCode());
        for (ContractDetailDTO contractDetailDTO : contractProcessDTO.getContractList()) {
            //contractName
            if(StringUtils.isBlank(contractDetailDTO.getContractName())){
                throw new ParamValidException("合同名称不能为空");
            }
            //校验对手方
            validateCounterparty(contractDetailDTO.getCounterPartyList());
            //产品编码
            validateProductCode(moduleCodeEnum, contractDetailDTO.getProductCodeList());
            //合同正文校验
            if(null==contractDetailDTO.getMainFileList()||contractDetailDTO.getMainFileList().isEmpty()){
                throw new ParamValidException("合同正文不能为空");
            }
            validateContractMainFile(contractDetailDTO.getMainFileList());

            //合同附件校验 合同附件可以为空
            if(null!=contractDetailDTO.getAttachedFileList()){
                validateContractMainFile(contractDetailDTO.getAttachedFileList());
            }
            //合同印章校验
            validateContractSeals(contractDetailDTO.getSeals());
            //合同起草人工号 暂时复制流程拟稿人
            //合同起草人部门 暂时复制流程拟稿人
            //合同备注
            //文本来源
            TextSourceEnum.valueOf(contractDetailDTO.getTextSource());
            //未使用范本原因
            if(TextSourceEnum.LOCAL.name().equals(contractDetailDTO.getTextSource())&&StringUtils.isBlank(contractDetailDTO.getTextSource())){
                throw new ParamValidException("本地上传，未使用范本原因不能为空");
            }
        }
    }

    private void validateProductCode(ModuleCodeEnum moduleCodeEnum,final List<String> productCodeList) {
        if(moduleCodeEnum ==ModuleCodeEnum.ONLINE){
            if(null== productCodeList || productCodeList.isEmpty()){
                throw new ParamValidException("产品编码不能为空");
            }
            final List<String> dsfbmList = ContractDao.selectCounterPartyByCertCode(productCodeList);
            if(dsfbmList.isEmpty()){
                throw new ParamValidException("产品无关联对手方信息");
            }
            //查出关联关系个数少于产品个数
            if(dsfbmList.size()< productCodeList.size()){
                throw new ParamValidException("部分产品无关联对手方");
            }
            final String flag = dsfbmList.get(0);
            if (StringUtils.isBlank(flag)) {
                throw new ParamValidException("产品关联对手方错误");
            }
            //校验对手方是否同一个
            for (String dsfbm : dsfbmList) {
                if(!flag.equals(dsfbm)){
                    throw new ParamValidException("关联对手方编码不唯一");
                }
            }

        }
    }

    private void validateContractSeals(List<String> seals) {
        if(null!= seals&&!seals.isEmpty()){
            final List<String> contractSeal = ContractDao.findContractSeal(seals);
            if(contractSeal.size()!= seals.size()){
                throw new ParamValidException("印章校验失败");
            }
        }
    }

    private void validateContractMainFile(List<ContractFileDTO> mainFileList) {

        //单个合同文件数量限制 HTO-14585
        if(mainFileList.size()> MAX_FILE_COUNT){
            throw new ParamValidException("合同文件超过最大文件数"+MAX_FILE_COUNT);
        }

        for (ContractFileDTO contractFileDTO : mainFileList) {
            //文件名称
            if(StringUtils.isBlank(contractFileDTO.getFileName())){
                throw new ParamValidException("文件名称不能为空");
            }
            //存储网关文件id
            if(StringUtils.isBlank(contractFileDTO.getFileId())){
                throw new ParamValidException("文件id不能为空");
            }
            //文件后缀
            if(StringUtils.isBlank(contractFileDTO.getSuffix())){
                throw new ParamValidException("文件后缀不能为空");
            }
        }

    }

    private void validateCounterparty(List<CounterPartyDTO> counterPartyList) {
        //证件类型
        //证件号
        final List<Integer> counterparty = ContractDao.findCounterparty(counterPartyList);
        if(counterparty.size()!=counterPartyList.size()){
            throw new ParamValidException("校验对手方失败");
        }
    }

}
