package com.gree.mall.manager.logic.contract;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.contract.*;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.ContractTypeEnum;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.enums.contract.FieldTypeEnum;
import com.gree.mall.manager.enums.contract.SignContractStatusEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.fadada.FDDNotifyLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.fadada.Auth4FDDUtil;
import com.gree.mall.manager.utils.oss.OSSUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class WebsitContractSignLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final AdminWebsitService adminWebsitService;
    private final WebsitContractSignRecordService websitContractSignRecordService;
    private final WebsitContractSignItemService websitContractSignItemService;
    private final WebsitContractSignFieldService websitContractSignFieldService;
    private final FDDNotifyLogic fddNotifyLogic;
    private final OSSUtil ossUtil;
    private final CompanyCaAuthService companyCaAuthService;
    private final WebsitFollowConfigItemService websitFollowConfigItemService;

    @Value("${fadada.websit.auth.verified-way}")
    private String fddAuthVerifiedWay;
    @Value("${fadada.websit.auth.page-modify}")
    private String fddAuthPageModify;
    @Value("${fadada.websit.auth.notify.url}")
    private String fddAuthNotifyUrl;
    @Value("${fadada.websit.sign.notify.url}")
    private String fddSignAuthNotifyUrl;
    @Value("${fadada.websit.person.auth.notify.url}")
    private String fddPersonAuthNotifyUrl;

    public IPage<WebsitContractSignVO> list(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, WebsitContractSignVO.class, adminUser);
        String websitId = null;
        if (adminUser.getType().equals(0) && adminUser.getAdminWebsitIds().size() == 1) {
            final AdminWebsit websit = adminWebsitService.lambdaQuery()
                    .eq(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .eq(AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds().get(0))
                    .one();
            if (websit.getLevel() == 2) {
                websitId = websit.getWebsitId();
            }
        }
        return commonMapper.websitContractSignPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, websitId);
    }

    public WebsitContractSignRecordBean detail(String id) {
        final WebsitContractSignRecord record = websitContractSignRecordService.getById(id);
        WebsitContractSignRecordBean bean = new WebsitContractSignRecordBean();
        BeanUtils.copyProperties(record, bean);
        final List<WebsitContractSignItem> signItems = websitContractSignItemService.lambdaQuery()
                .eq(WebsitContractSignItem::getWebsitContractSignRecordId, id)
                .list();
        bean.setItems(signItems);
        return bean;
    }

    public void cancel(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        websitContractSignRecordService.lambdaUpdate()
                .set(WebsitContractSignRecord::getStatus, SignContractStatusEnum.CANCEL.getKey())
                .set(WebsitContractSignRecord::getCancelBy, adminUser.getNickName())
                .set(WebsitContractSignRecord::getCancelTime, DateUtil.date())
                .eq(WebsitContractSignRecord::getId, id)
                .update();
    }

    public AuthBean sign(String id, String returnUrl) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        AuthBean bean = new AuthBean();

        WebsitContractSignRecord record = websitContractSignRecordService.getById(id);

        if (Objects.isNull(record)) {
            throw new RemoteServiceException("合同记录不存在");
        }
        WebsitContractSignItem item = websitContractSignItemService.lambdaQuery()
                .eq(WebsitContractSignItem::getWebsitContractSignRecordId, record.getId())
                .eq(WebsitContractSignItem::getContractType, ContractTypeEnum.MAIN.getKey())
                .one();

        AdminWebsit websit = adminWebsitService.getById(record.getWebsitId());

        // 未企业认证
        if (StringUtils.isBlank(websit.getFadadaWebsitNo()) && StringUtils.isBlank(websit.getFadadaWebsitId())
                || StringUtils.isBlank(websit.getFadadaWebsitNo()) && StringUtils.isNotBlank(websit.getFadadaWebsitId())) {
            this.companyAuthMethod(websit, bean, returnUrl);
        }

        // 企业认证已通过执行个人认证处理
        if (!bean.isJump()
                && StringUtils.isBlank(websit.getFadadaCustomerNo())
                && StringUtils.isBlank(websit.getFadadaCustomerAuthUrl())) {
            this.personAuthMethod(websit, record, bean, returnUrl);
        }

        // 避免前端调用过快,法大大还没更新状态
        Thread.sleep(3000);

        final List<WebsitContractSignItem> signItems = websitContractSignItemService.lambdaQuery()
                .eq(WebsitContractSignItem::getWebsitContractSignRecordId, record.getId())
                .list();

        long companySign = signItems.stream()
                .filter(v -> v.getNeedCompanySign().equals(IsYesNoEnum.YES.getKey()) && v.getCompanySignStatus().equals(IsYesNoEnum.NO.getKey()))
                .count();
        if (!bean.isJump() && companySign > 0 && websit.getFadadaWebsitRealStatus().equals(IsYesNoEnum.YES.getKey())) {
            // 签约企业签约跳
            this.companySignMethod(websit, item, bean, returnUrl);
        }

        long managerSign = signItems.stream()
                .filter(v -> v.getNeedManagerSign().equals(IsYesNoEnum.YES.getKey()) && v.getManagerSignStatus().equals(IsYesNoEnum.NO.getKey()))
                .count();
        if (!bean.isJump()
                && companySign == 0
                && managerSign > 0
                && websit.getFadadaCustomerRealStatus().equals(IsYesNoEnum.YES.getKey())) {
            // 签约负责人签约跳
            this.managerSignMethod(websit, item, bean, returnUrl);
        }
        record = websitContractSignRecordService.getById(id);
        if (!bean.isJump()) {
            if (websit.getFadadaWebsitRealStatus().equals(IsYesNoEnum.NO.getKey())) {
                bean.setJump(true);
                bean.setUrl(websit.getFadadaWebsitAuthUrl());
            } else if (websit.getFadadaCustomerRealStatus().equals(IsYesNoEnum.NO.getKey())) {
                bean.setJump(true);
                bean.setUrl(websit.getFadadaCustomerAuthUrl());
            } else if (companySign > 0 && record.getStatus().equals(SignContractStatusEnum.WAIT_SIGN.getKey())) {
                // 签约企业签约跳
                bean.setJump(true);
                bean.setUrl(item.getCompanySignUrl());
            } else if (managerSign > 0 && record.getStatus().equals(SignContractStatusEnum.WAIT_SIGN.getKey())) {
                // 签约负责人签约跳
                bean.setJump(true);
                bean.setUrl(item.getManagerSignUrl());
            }
        }

        return bean;
    }

    private void companySignMethod(AdminWebsit websit, WebsitContractSignItem item, AuthBean bean, String returnUrl) {
        // 公章签约地址不为空查询合同签章状态
        if (StringUtils.isNotBlank(item.getCompanySignUrl())) {
            this.queryCompanySignStatus(websit, item);
            // 同步查询公章签约结果成功退出不继续
            if (item.getCompanySignStatus().equals(IsYesNoEnum.YES.getKey())) {
                return;
            }
        }

        // 准备批量签合同
        if (StringUtils.isBlank(item.getCompanySignUrl())) {
            this.getNeedSignContract(websit, item, bean, returnUrl);
        }
    }

    private void getNeedSignContract(AdminWebsit websit, WebsitContractSignItem item, AuthBean bean, String returnUrl) {

        // 第一步 查询可签网点电子合同
        List<WebsitContractSignItem> websitFiles = websitContractSignItemService.lambdaQuery()
                .eq(WebsitContractSignItem::getWebsitContractSignRecordId, item.getWebsitContractSignRecordId())
                .eq(WebsitContractSignItem::getNeedCompanySign, IsYesNoEnum.YES.getKey())
                .isNotNull(WebsitContractSignItem::getFadadaTemplateId)
                .list();

        if (CollectionUtil.isEmpty(websitFiles)) {
            throw new RemoteServiceException("未发现可签电子合同");
        }

        // 第二步 用合同模版调用模板填充生成电子合同后调批量签署（半自动）接口

        // 构造signdata
        JSONArray signData = new JSONArray();
        String batchId = IdWorker.getIdStr();
        for (WebsitContractSignItem websitFile : websitFiles) {
            String generateContractId = IdWorker.getIdStr();
            String generateTransactionId = IdWorker.getIdStr();
            String fddParams = this.getContractParams(websit, websitFile.getId());
            if (StringUtils.isNotBlank(fddParams)) {
                Auth4FDDUtil.generateContract(websitFile.getFadadaTemplateId(), generateContractId,
                        websitFile.getContractName(), null, null, fddParams);
            } else {
                String urlWw = websitFile.getContractTemplatePdf();
                Auth4FDDUtil.uploadContract(generateContractId, websitFile.getContractName(),
                        null, urlWw);
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.set("contractId", generateContractId);
            jsonObject.set("keywordStrategy", "0");
            jsonObject.set("signKeyword", websitFile.getCompanySignFiled());
            jsonObject.set("transactionId", generateTransactionId);
            signData.set(jsonObject);

            websitFile.setFadadaContractId(generateContractId)
                    .setFadadaTransactionId(generateTransactionId)
                    .setFadadaBatchId(batchId)
                    .setFadadaBatchTitle("批量签署");
        }
//        List<WebsitContractSignItem> collect = websitFiles.stream()
//                .peek(v -> v.setFadadaSignData(signData.toString()))
//                .collect(Collectors.toList());

        websitFiles.get(0).setFadadaSignData(signData.toString());

        websitContractSignItemService.saveOrUpdateBatch(websitFiles);
        // 调用批量签
        String companySignUrl = Auth4FDDUtil.batchExtSign(batchId, "批量签署", signData.toString(), websit.getFadadaWebsitId(),
                "1", "0", null, returnUrl, this.fddSignAuthNotifyUrl);
        item.setCompanySignUrl(companySignUrl);

        websitContractSignItemService.lambdaUpdate()
                .set(WebsitContractSignItem::getCompanySignUrl, companySignUrl)
                .eq(WebsitContractSignItem::getId, item.getId())
                .update();

        bean.setJump(true);
        bean.setUrl(companySignUrl);
    }

    private String getContractParams(AdminWebsit websit, String id) {
        List<WebsitContractSignField> fields = websitContractSignFieldService.lambdaQuery()
                .eq(WebsitContractSignField::getWebsitContractSignItemId, id)
                .list();

        final WebsitFollowConfigItem followItem = websitFollowConfigItemService.lambdaQuery()
                .eq(WebsitFollowConfigItem::getCompanyWechatId, websit.getCompanyWechatId())
                .eq(WebsitFollowConfigItem::getSubWebsitId, websit.getWebsitId())
                .one();

        final CompanyCaAuth companyCaAuth = companyCaAuthService.lambdaQuery()
                .eq(CompanyCaAuth::getWebsitId, followItem.getParentId())
                .eq(CompanyCaAuth::getCompanyWechatId, websit.getCompanyWechatId())
                .eq(CompanyCaAuth::getFadadaIsAuth, IsYesNoEnum.YES.getKey())
                .eq(CompanyCaAuth::getFadadaAuthAutoStatus, IsYesNoEnum.YES.getKey())
                .one();

        final AdminWebsit parentWebsit = adminWebsitService.getById(followItem.getParentId());

        if (Objects.isNull(companyCaAuth)) {
            throw new RemoteServiceException("未找到上级网点的CA认证记录");
        }

        if (CollectionUtil.isEmpty(fields)) {
            return "";
        }
        JSONObject params = new JSONObject();
        String formatDate = DateUtil.formatDate(DateUtil.date());
        String[] dateSplit = formatDate.split("-");

        for (WebsitContractSignField field : fields) {
            if (field.getFieldType().equals(FieldTypeEnum.CUSTOM.getKey())) {
                params.set(field.getFieldName(), field.getFieldValue());

            } else if (field.getFieldType().equals(FieldTypeEnum.YYYYMMDD.getKey())) {
                params.set(field.getFieldName(), formatDate);

            } else if (field.getFieldType().equals(FieldTypeEnum.NEXT_YYYY.getKey())) {
                params.set(field.getFieldName(), Integer.parseInt(dateSplit[0]) + 1);

            } else if (field.getFieldType().equals(FieldTypeEnum.YYYY.getKey())) {
                params.set(field.getFieldName(), dateSplit[0]);

            } else if (field.getFieldType().equals(FieldTypeEnum.MM.getKey())) {
                params.set(field.getFieldName(), dateSplit[1]);

            } else if (field.getFieldType().equals(FieldTypeEnum.DD.getKey())) {
                params.set(field.getFieldName(), dateSplit[2]);

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_WEBSIT_NAME.getKey())) {
                params.set(field.getFieldName(), websit.getName());

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_WEBSIT_ID.getKey())) {
                params.set(field.getFieldName(), websit.getWebsitId());

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_EMAIL.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(websit.getEmail()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_ADDRESS.getKey())) {
                String address = Optional.ofNullable(websit.getAddress()).orElse("");
                String execAddress = address;
//                if (address.length() > 14) {
//                    execAddress = address.substring(0, 14) + "\n" + address.substring(14, address.length() - 1);
//                }
                params.set(field.getFieldName(), execAddress);

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_TEL.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(websit.getWebsitPhone()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_FAX.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(websit.getFax()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_ZIP_CODE.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(websit.getZipCode()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_BANK_DEPOSIT.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(websit.getOpenBank()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_BANK_ACCOUNT.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(websit.getBankAccount()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.Y_LEGAL_NAME.getKey())) {
                params.set(field.getFieldName(), websit.getLegalName());

            } else if (field.getFieldType().equals(FieldTypeEnum.WEBSIT_NAME.getKey())) {
                params.set(field.getFieldName(), parentWebsit.getName());

            } else if (field.getFieldType().equals(FieldTypeEnum.SHORT_NAME.getKey())) {
                params.set(field.getFieldName(), companyCaAuth.getShortName());

            } else if (field.getFieldType().equals(FieldTypeEnum.ADDRESS.getKey())) {
                String address = Optional.ofNullable(companyCaAuth.getCompanyAddress()).orElse("");
                String execAddress = address;
//                if (address.length() > 14) {
//                    execAddress = address.substring(0, 14) + "\n" + address.substring(14, address.length() - 1);
//                }
                params.set(field.getFieldName(), execAddress);

            } else if (field.getFieldType().equals(FieldTypeEnum.TEL.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(parentWebsit.getWebsitPhone()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.FAX.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(parentWebsit.getFax()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.ZIP_CODE.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(parentWebsit.getZipCode()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.BANK_DEPOSIT.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(parentWebsit.getOpenBank()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.BANK_ACCOUNT.getKey())) {
                params.set(field.getFieldName(), Optional.ofNullable(parentWebsit.getBankAccount()).orElse(""));

            } else if (field.getFieldType().equals(FieldTypeEnum.CA_LEGAL_NAME.getKey())) {
                params.set(field.getFieldName(), companyCaAuth.getLegalName());

            } else {
                throw new RemoteServiceException("找不到填充类型");
            }
        }

        return params.toString();
    }

    private void companyAuthMethod(AdminWebsit websit, AuthBean bean, String returnUrl) throws Exception {
        // 企业认证
        if (StringUtils.isBlank(websit.getFadadaWebsitId())) {
            String customerId = Auth4FDDUtil.regAccount("2", websit.getWebsitId() + DateUtil.date().getTime()).get("data", String.class, true);
            if (StringUtils.isBlank(customerId)) {
                throw new RemoteServiceException("注册法大大企业失败");
            }
            adminWebsitService.lambdaUpdate()
                    .set(AdminWebsit::getFadadaWebsitId, customerId)
                    .eq(AdminWebsit::getWebsitId, websit.getWebsitId())
                    .update();

            websit.setFadadaWebsitId(customerId);
        }

        if (StringUtils.isNotBlank(websit.getFadadaWebsitNo())) {
            this.queryWebsitAuthResult(websit);
            // 同步查询企业认证结果成功退出不继续
            if (websit.getFadadaWebsitRealStatus().equals(IsYesNoEnum.YES.getKey())) {
                return;
            }
            if (StringUtils.isNotBlank(websit.getFadadaWebsitAuthUrl())) {
                bean.setJump(true);
                bean.setUrl(websit.getFadadaWebsitAuthUrl());
                return;
            }
        }
        CompanyInfo company = new CompanyInfo();
        company.setCompanyName(websit.getName());
//        company.setCreditNo(websit.getTaxNo());
//        company.setCreditImagePath(ossUtil.getUrlWw(ossUtil.replaceLongKeyUrl(websit.getBusinessLicenseUrl())));

        LegalInfo legal = new LegalInfo();
        legal.setLegalName(websit.getLegalName());
        legal.setLegalId(websit.getLegalIdCard());
        legal.setLegalMobile(websit.getLegalMobile());

        JSONObject resultJson = Auth4FDDUtil.getAuthCompanyUrl(websit.getFadadaWebsitId(), this.fddAuthPageModify,
                this.fddAuthVerifiedWay, null, null, null,
                null, null, null, null, null,
                null, null, null, null, null, this.fddAuthNotifyUrl,
                returnUrl, company, legal, null, null);


        JSONObject data = resultJson.getJSONObject("data");
        String authUrl = Auth4FDDUtil.decodeUrl(data.get("url", String.class));

        websit.setFadadaWebsitNo(data.get("transactionNo", String.class))
                .setFadadaWebsitAuthUrl(authUrl);

        adminWebsitService.lambdaUpdate()
                .set(AdminWebsit::getFadadaWebsitNo, websit.getFadadaWebsitNo())
                .set(AdminWebsit::getFadadaWebsitAuthUrl, websit.getFadadaWebsitAuthUrl())
                .eq(AdminWebsit::getWebsitId, websit.getWebsitId())
                .update();

        bean.setJump(true);
        bean.setUrl(authUrl);
    }


    private void queryWebsitAuthResult(AdminWebsit websit) {
        fddNotifyLogic.websitAuthResultHandle(websit);
        adminWebsitService.lambdaUpdate()
                .set(AdminWebsit::getFadadaWebsitRealStatus, websit.getFadadaWebsitRealStatus())
                .set(AdminWebsit::getFadadaAuthFailReason, websit.getFadadaAuthFailReason())
                .set(AdminWebsit::getFadadaRegFormPath, websit.getFadadaRegFormPath())
                .set(AdminWebsit::getFadadaOrganizationPath, websit.getFadadaOrganizationPath())
                .eq(AdminWebsit::getWebsitId, websit.getWebsitId())
                .update();
    }

    private void personAuthMethod(AdminWebsit websit, WebsitContractSignRecord record, AuthBean bean, String returnUrl) throws Exception {
        // 个人认证
        if (StringUtils.isBlank(websit.getFadadaCustomerId())) {
            String personCustomerId = Auth4FDDUtil.regAccount("1", IdUtil.objectId()).get("data", String.class, true);
            if (StringUtils.isBlank(personCustomerId)) {
                throw new RemoteServiceException("注册法大大个人失败");
            }
            adminWebsitService.lambdaUpdate()
                    .set(AdminWebsit::getFadadaCustomerId, personCustomerId)
                    .eq(AdminWebsit::getWebsitId, websit.getWebsitId())
                    .update();
            websit.setFadadaCustomerId(personCustomerId);
        }

        if (StringUtils.isNotBlank(websit.getFadadaCustomerNo())) {
            this.queryWebsitPersonAuthResult(websit);
            // 同步查询个人认证结果成功退出不继续
            if (websit.getFadadaCustomerRealStatus().equals(IsYesNoEnum.YES.getKey())) {
                return;
            }
            if (StringUtils.isNotBlank(websit.getFadadaCustomerAuthUrl())) {
                bean.setJump(true);
                bean.setUrl(websit.getFadadaCustomerAuthUrl());
                return;
            }
        }

        JSONObject personResultJson = Auth4FDDUtil.getAuthPersonUrl(websit.getFadadaCustomerId(), this.fddAuthPageModify, this.fddAuthVerifiedWay,
                websit.getLegalName(), "0", "", websit.getLegalMobile(),
                null, null, null, "1", "0", null, null,
                "2", null, null, this.fddPersonAuthNotifyUrl, returnUrl, null, null);

        JSONObject personData = personResultJson.getJSONObject("data");
        String personAuthUrl = Auth4FDDUtil.decodeUrl(personData.get("url", String.class));
        websit.setFadadaCustomerAuthUrl(personAuthUrl);
        websit.setFadadaCustomerNo(personData.get("transactionNo", String.class));

        adminWebsitService.lambdaUpdate()
                .set(AdminWebsit::getFadadaCustomerNo, websit.getFadadaCustomerNo())
                .set(AdminWebsit::getFadadaCustomerAuthUrl, websit.getFadadaCustomerAuthUrl())
                .eq(AdminWebsit::getWebsitId, websit.getWebsitId())
                .update();

        bean.setJump(true);
        bean.setUrl(personAuthUrl);
    }

    private void queryWebsitPersonAuthResult(AdminWebsit websit) {
        fddNotifyLogic.websitPersonAuthResultHandle(websit);
        adminWebsitService.lambdaUpdate()
                .set(AdminWebsit::getFadadaCustomerRealStatus, websit.getFadadaCustomerRealStatus())
                .set(AdminWebsit::getFadadaAuthFailReason, websit.getFadadaAuthFailReason())
                .set(AdminWebsit::getFadadaCustomerHeadPhotoPath, websit.getFadadaCustomerHeadPhotoPath())
                .set(AdminWebsit::getFadadaCustomerAuditorTime, websit.getFadadaCustomerAuditorTime())
                .set(AdminWebsit::getFadadaCustomerPhotoUuid, websit.getFadadaCustomerPhotoUuid())
                .eq(AdminWebsit::getWebsitId, websit.getWebsitId())
                .update();
    }

    private void queryCompanySignStatus(AdminWebsit websit, WebsitContractSignItem item) {
        List<WebsitContractSignItem> websitFiles = websitContractSignItemService.lambdaQuery()
                .eq(WebsitContractSignItem::getWebsitContractSignRecordId, item.getWebsitContractSignRecordId())
                .eq(WebsitContractSignItem::getNeedCompanySign, IsYesNoEnum.YES.getKey())
                .list();
        if (CollectionUtils.isEmpty(websitFiles)) {
            throw new RemoteServiceException("未找到有效签约合同");
        }
        boolean sign = false;
        // 遍历查询签章状态
        for (WebsitContractSignItem file : websitFiles) {
            JSONObject object = Auth4FDDUtil.querySignStatus(file.getFadadaContractId(), websit.getFadadaWebsitId(), file.getFadadaTransactionId());
            Integer code = object.get("code", Integer.class);
            String msg = object.get("msg", String.class);
            JSONObject data = object.getJSONObject("data");
            log.info("{} 二级网点签约查询结果: {}", websit.getWebsitId(), msg);
            if (code != 1) {
                sign = false;
                break;
            }
            String result = data.get("result", String.class);
            sign = result.equals("3000");
        }

        if (sign) {
            websitContractSignItemService.lambdaUpdate()
                    .set(WebsitContractSignItem::getCompanySignStatus, IsYesNoEnum.YES.getKey())
                    .eq(WebsitContractSignItem::getWebsitContractSignRecordId, item.getWebsitContractSignRecordId())
                    .update();
            item.setCompanySignStatus(IsYesNoEnum.YES.getKey());
        }

        // 检查是否更新为待审核状态
        final List<WebsitContractSignItem> signItems = websitContractSignItemService.lambdaQuery()
                .eq(WebsitContractSignItem::getWebsitContractSignRecordId, item.getWebsitContractSignRecordId())
                .list();

        final long managerCount = signItems.stream()
                .filter(v -> v.getNeedManagerSign().equals(IsYesNoEnum.YES.getKey()) && v.getManagerSignStatus().equals(IsYesNoEnum.NO.getKey()))
                .count();
        if (managerCount == 0) {
            // 无需法人签，直接把记录改为待审核
            websitContractSignItemService.lambdaUpdate()
                    .set(WebsitContractSignItem::getContractStatus, SignContractStatusEnum.WAIT.getKey())
                    .eq(WebsitContractSignItem::getWebsitContractSignRecordId, item.getWebsitContractSignRecordId())
                    .update();
            websitContractSignRecordService.lambdaUpdate()
                    .set(WebsitContractSignRecord::getFadadaWebsitId, websit.getFadadaWebsitId())
                    .set(WebsitContractSignRecord::getFadadaWebsitNo, websit.getFadadaWebsitNo())
                    .set(WebsitContractSignRecord::getFadadaCustomerId, websit.getFadadaCustomerId())
                    .set(WebsitContractSignRecord::getFadadaCustomerNo, websit.getFadadaCustomerNo())
                    .set(WebsitContractSignRecord::getStatus, SignContractStatusEnum.WAIT.getKey())
                    .eq(WebsitContractSignRecord::getId, item.getWebsitContractSignRecordId())
                    .update();
        }
    }

    private void managerSignMethod(AdminWebsit websit, WebsitContractSignItem item, AuthBean bean, String returnUrl) {
        // 负责人签约地址不为空查询合同签章状态
        if (StringUtils.isNotBlank(item.getManagerSignUrl())) {
            this.queryManagerSignStatus(websit, item);
            // 同步查询负责人签约结果成功退出不继续
            if (item.getManagerSignStatus().equals(IsYesNoEnum.YES.getKey())) {
                return;
            }
        }

        if (StringUtils.isBlank(item.getManagerSignUrl())) {
            // 第一步 查询可签网点电子合同
            List<WebsitContractSignItem> websitFiles = websitContractSignItemService.lambdaQuery()
                    .eq(WebsitContractSignItem::getWebsitContractSignRecordId, item.getWebsitContractSignRecordId())
                    .eq(WebsitContractSignItem::getNeedManagerSign, IsYesNoEnum.YES.getKey())
                    .list();

            // 构造signdata
            JSONArray signData = new JSONArray();
            String batchId = IdWorker.getIdStr();
            for (WebsitContractSignItem websitFile : websitFiles) {
                String generateTransactionId = IdWorker.getIdStr();

                JSONObject jsonObject = new JSONObject();
                jsonObject.set("contractId", websitFile.getFadadaContractId());
                jsonObject.set("keywordStrategy", "0");
                jsonObject.set("signKeyword", websitFile.getManagerSignField());
                jsonObject.set("transactionId", generateTransactionId);
                signData.set(jsonObject);

                websitFile.setManagerTransactionId(generateTransactionId)
                        .setManagerBatchId(batchId)
                        .setManagerBatchTitle("批量签署");
            }

            websitContractSignItemService.saveOrUpdateBatch(websitFiles);
            // 调用批量签
            String managerSignUrl = Auth4FDDUtil.batchExtSign(batchId, "批量签署", signData.toString(), websit.getFadadaCustomerId(),
                    "1", "0", null, returnUrl, this.fddSignAuthNotifyUrl);
            item.setManagerSignUrl(managerSignUrl);
            websitContractSignItemService.lambdaUpdate()
                    .set(WebsitContractSignItem::getManagerSignUrl, managerSignUrl)
                    .eq(WebsitContractSignItem::getId, item.getId())
                    .update();
            bean.setJump(true);
            bean.setUrl(managerSignUrl);
        }
    }

    private void queryManagerSignStatus(AdminWebsit websit, WebsitContractSignItem item) {
        List<WebsitContractSignItem> websitFiles = websitContractSignItemService.lambdaQuery()
                .eq(WebsitContractSignItem::getWebsitContractSignRecordId, item.getWebsitContractSignRecordId())
                .eq(WebsitContractSignItem::getNeedManagerSign, IsYesNoEnum.YES.getKey())
                .list();

        if (CollectionUtils.isEmpty(websitFiles)) {
            throw new RemoteServiceException("未找到有效签约合同");
        }
        boolean sign = false;
        // 遍历查询签章状态
        for (WebsitContractSignItem file : websitFiles) {
            JSONObject object = Auth4FDDUtil.querySignStatus(file.getFadadaContractId(), websit.getFadadaCustomerId(), file.getManagerTransactionId());
            Integer code = object.get("code", Integer.class);
            String msg = object.get("msg", String.class);
            JSONObject data = object.getJSONObject("data");
            log.info("{} 法人签约查询结果: {}", websit.getWebsitId(), msg);
            if (code != 1) {
                sign = false;
                break;
            }
            String result = data.get("result", String.class);
            sign = result.equals("3000");
        }

        if (sign) {
            item.setManagerSignStatus(IsYesNoEnum.YES.getKey());
            websitContractSignItemService.lambdaUpdate()
                    .set(WebsitContractSignItem::getSignDate, DateUtil.date())
                    .set(WebsitContractSignItem::getManagerSignStatus, IsYesNoEnum.YES.getKey())
                    .set(WebsitContractSignItem::getContractStatus, SignContractStatusEnum.WAIT.getKey())
                    .eq(WebsitContractSignItem::getWebsitContractSignRecordId, item.getWebsitContractSignRecordId())
                    .update();
            websitContractSignRecordService.lambdaUpdate()
                    .set(WebsitContractSignRecord::getSignTime, DateUtil.date())
                    .set(WebsitContractSignRecord::getAuthStatus, IsYesNoEnum.YES.getKey())
                    .set(WebsitContractSignRecord::getFadadaWebsitId, websit.getFadadaWebsitId())
                    .set(WebsitContractSignRecord::getFadadaWebsitNo, websit.getFadadaWebsitNo())
                    .set(WebsitContractSignRecord::getFadadaCustomerId, websit.getFadadaCustomerId())
                    .set(WebsitContractSignRecord::getFadadaCustomerNo, websit.getFadadaCustomerNo())
                    .set(WebsitContractSignRecord::getStatus, SignContractStatusEnum.WAIT.getKey())
                    .eq(WebsitContractSignRecord::getId, item.getWebsitContractSignRecordId())
                    .update();
        }
    }

    @Transactional
    public void confirm(String id, SignContractStatusEnum status, String remark) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        final WebsitContractSignRecord record = websitContractSignRecordService.getById(id);

        if (Objects.isNull(record)) {
            throw new RemoteServiceException("合同签约记录不存在");
        }

        List<WebsitContractSignItem> signItemList = websitContractSignItemService.lambdaQuery()
                .eq(WebsitContractSignItem::getWebsitContractSignRecordId, record.getId())
                .list();

        for (WebsitContractSignItem signItem : signItemList) {
            if (status.getKey().equals(SignContractStatusEnum.OK.getKey())) {
                if (signItem.getNeedPartyASign().equals(IsYesNoEnum.YES.getKey())) {
                    //甲方签署
                    try {
                        JSONObject object = Auth4FDDUtil.extSignAuto(IdWorker.getIdStr(), signItem.getFadadaContractId(),
                                signItem.getCaCustomerId(), "甲方签章", "0",
                                signItem.getPartyASignFiled(), "", "", "");
                        log.info(signItem.getFadadaContractId() + " 甲方签章结果：{}", object);
                    } catch (Exception e) {
                        if (!e.getMessage().contains("合同已归档")) {
                            throw new RemoteServiceException(e.getMessage());
                        }
                    }
                }

                // 法大大合同归档
                JSONObject object1 = Auth4FDDUtil.contractFiling(signItem.getFadadaContractId());
                log.info(signItem.getFadadaContractId() + " 合同归档结果：{}", object1);

                websitContractSignItemService.lambdaUpdate()
                        .set(WebsitContractSignItem::getContractStatus, SignContractStatusEnum.OK.getKey())
                        .set(WebsitContractSignItem::getConfirmBy, adminUser.getNickName())
                        .set(WebsitContractSignItem::getConfirmTime, DateUtil.date())
                        .eq(WebsitContractSignItem::getId, signItem.getId())
                        .update();
            } else {
                websitContractSignItemService.lambdaUpdate()
                        .set(WebsitContractSignItem::getContractStatus, SignContractStatusEnum.REJECT.getKey())
                        .set(WebsitContractSignItem::getConfirmBy, adminUser.getNickName())
                        .set(WebsitContractSignItem::getConfirmTime, DateUtil.date())
                        .eq(WebsitContractSignItem::getId, signItem.getId())
                        .update();
            }
        }

        // 合同都已审核，更新记录为审核通过
        websitContractSignRecordService.lambdaUpdate()
                .set(WebsitContractSignRecord::getRemark, remark)
                .set(WebsitContractSignRecord::getStatus, status.getKey())
                .set(WebsitContractSignRecord::getConfirmBy, adminUser.getNickName())
                .set(WebsitContractSignRecord::getConfirmTime, DateUtil.date())
                .eq(WebsitContractSignRecord::getId, id)
                .update();

    }

    public WebsitContractSignRecordCount count() {
        final Integer count = websitContractSignRecordService.lambdaQuery()
                .eq(WebsitContractSignRecord::getStatus, SignContractStatusEnum.WAIT_SIGN.getKey())
                .count();
        final Integer count1 = websitContractSignRecordService.lambdaQuery()
                .eq(WebsitContractSignRecord::getStatus, SignContractStatusEnum.WAIT.getKey())
                .count();
        WebsitContractSignRecordCount recordCount = new WebsitContractSignRecordCount();
        recordCount.setWaitCount(count);
        recordCount.setEndCount(count1);
        return recordCount;
    }
}
