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

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.contract.CompanyCaAuthVO;
import com.gree.mall.manager.bean.contract.CompanyInfo;
import com.gree.mall.manager.bean.contract.LegalInfo;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.AdminWebsit;
import com.gree.mall.manager.plus.entity.CompanyCaAuth;
import com.gree.mall.manager.plus.service.AdminWebsitService;
import com.gree.mall.manager.plus.service.CompanyCaAuthService;
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.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class CompanyCaAuthLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final CompanyCaAuthService companyCaAuthService;
    private final AdminWebsitService adminWebsitService;
    private final OSSUtil ossUtil;
    @Value("${fadada.company.auth.page-modify}")
    private String fddAuthPageModify;
    @Value("${fadada.company.auth.verified-way}")
    private String fddAuthVerifiedWay;
    @Value("${fadada.company.auth.notify.url}")
    private String fddAuthNotifyUrl;
    @Value("${fadada.company.auth.return.url}")
    private String fddAuthReturnUrl;

    public IPage<CompanyCaAuthVO> list(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, CompanyCaAuthVO.class, adminUser);
        return commonMapper.companyCaAuthPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public CompanyCaAuth detail(String companyCaAuthId) {
        return companyCaAuthService.lambdaQuery()
                .eq(CompanyCaAuth::getCompanyCaAuthId, companyCaAuthId)
                .one();
    }

    public void add(CompanyCaAuth companyCaAuth) {
        final AdminWebsit websit = adminWebsitService.getById(companyCaAuth.getWebsitId());
        companyCaAuth.setCompanyName(websit.getName());
        companyCaAuth.setCompanyWechatId(websit.getCompanyWechatId());
        companyCaAuth.setCompanyWechatName(websit.getCompanyWechatName());
        CompanyCaAuth caAuth = companyCaAuthService.lambdaQuery()
                .eq(CompanyCaAuth::getWebsitId, companyCaAuth.getWebsitId())
                .one();
        if (Objects.nonNull(caAuth)) {
            throw new RemoteServiceException("网点已存在");
        }

        this.checkInfo(companyCaAuth);
        companyCaAuth.setFadadaCustomerId(null)
                .setFadadaTransactionNo(null)
                .setFadadaAuthUrl(null)
                .setFadadaIsAuth(null)
                .setFadadaStatus(null)
                .setFadadaAuditFailReason(null)
                .setFadadaAuthAutoId(null)
                .setFadadaAuthAutoContractId(null)
                .setFadadaAuthAutoStatus(null)
                .setFadadaAuthAutoUrl(null)
                .setFadadaAuthAutoViewpdfUrl(null)
                .setFadadaAuthAutoDownloadUrl(null)
                .insert();
    }

    public void update(CompanyCaAuth companyCaAuth) {
        final AdminWebsit websit = adminWebsitService.getById(companyCaAuth.getWebsitId());
        companyCaAuth.setCompanyName(websit.getName());
        companyCaAuth.setCompanyWechatId(websit.getCompanyWechatId());
        companyCaAuth.setCompanyWechatName(websit.getCompanyWechatName());
        this.checkInfo(companyCaAuth);
        CompanyCaAuth byId = companyCaAuthService.getById(companyCaAuth.getCompanyCaAuthId());

        // 对比关键信息是否变动
        if (this.compareRequireValue(companyCaAuth, byId)) {
            byId.setFadadaIsAuth(IsYesNoEnum.NO.getKey());
        }
        byId.updateById();
    }

    private void checkInfo(CompanyCaAuth companyCaAuth) {
        if (StringUtils.isBlank(companyCaAuth.getCompanyName())) {
            throw new RemoteServiceException("公司名称不能为空");
        }
        if (StringUtils.isBlank(companyCaAuth.getShortName())) {
            throw new RemoteServiceException("网点简称不能为空");
        }
        if (StringUtils.isBlank(companyCaAuth.getCompanyAddress())) {
            throw new RemoteServiceException("公司地址不能为空");
        }
        if (StringUtils.isBlank(companyCaAuth.getTaxNo())) {
            throw new RemoteServiceException("统一社会信用代码不能为空");
        }
        if (StringUtils.isBlank(companyCaAuth.getBusinessLicenseUrl())) {
            throw new RemoteServiceException("营业执照附件不能为空");
        }
        if (StringUtils.isBlank(companyCaAuth.getLegalName())) {
            throw new RemoteServiceException("法人不能为空");
        }
        if (StringUtils.isBlank(companyCaAuth.getLegalMobile())) {
            throw new RemoteServiceException("法人联系方式不能为空");
        }
        if (StringUtils.isBlank(companyCaAuth.getLegalIdCard())) {
            throw new RemoteServiceException("法人身份证不能为空");
        }
        if (StringUtils.isBlank(companyCaAuth.getLegalIdCard())) {
            throw new RemoteServiceException("法人身份证不能为空");
        }
    }

    private boolean compareRequireValue(CompanyCaAuth c1, CompanyCaAuth c2) {
        boolean flag = false;
        if (!c1.getCompanyName().trim().equals(c2.getCompanyName().trim())) {
            c2.setCompanyName(c1.getCompanyName().trim());
            flag = true;
        }
        if (!c1.getCompanyAddress().trim().equals(c2.getCompanyAddress().trim())) {
            c2.setCompanyAddress(c1.getCompanyAddress().trim());
//            flag = true;
        }
        if (!c1.getTaxNo().trim().equals(c2.getTaxNo().trim())) {
            c2.setTaxNo(c1.getTaxNo().trim());
            flag = true;
        }
        if (!c1.getBusinessLicenseUrl().trim().equals(c2.getBusinessLicenseUrl().trim())) {
            c2.setBusinessLicenseUrl(c1.getBusinessLicenseUrl().trim());
            flag = true;
        }
        if (!c1.getLegalName().trim().equals(c2.getLegalName().trim())) {
            c2.setLegalName(c1.getLegalName().trim());
            flag = true;
        }
        if (!c1.getLegalMobile().trim().equals(c2.getLegalMobile().trim())) {
            c2.setLegalMobile(c1.getLegalMobile().trim());
            flag = true;
        }
        if (!c1.getLegalIdCard().trim().equals(c2.getLegalIdCard().trim())) {
            c2.setLegalIdCard(c1.getLegalIdCard().trim());
            flag = true;
        }
        if (!c1.getShortName().trim().equals(c2.getShortName().trim())) {
            c2.setShortName(c1.getShortName().trim());
        }
        return flag;
    }

    public void delete(String companyCaAuthId) {
        companyCaAuthService.lambdaUpdate()
                .eq(CompanyCaAuth::getCompanyCaAuthId, companyCaAuthId)
                .remove();
    }

    public String getAuth(String companyCaAuthId) throws Exception {
        CompanyCaAuth companyCaAuth = companyCaAuthService.getById(companyCaAuthId);
        if (Objects.isNull(companyCaAuth)) {
            throw new RemoteServiceException("企业CA认证不存在");
        }

        if (companyCaAuth.getFadadaIsAuth().equals(IsYesNoEnum.YES.getKey())) {
            throw new RemoteServiceException("法大大已认证");
        }

        if (StringUtils.isBlank(companyCaAuth.getFadadaStatus()) && StringUtils.isNotBlank(companyCaAuth.getFadadaAuthUrl())) {
            // 法大大认证状态为空并且认证地址不为空时返回认证地址
            return companyCaAuth.getFadadaAuthUrl();
        }

        if (StringUtils.isBlank(companyCaAuth.getFadadaCustomerId())) {
            String id = Auth4FDDUtil.regAccount("2", companyCaAuth.getWebsitId()).get("data", String.class);
            companyCaAuth.setFadadaCustomerId(id);
        }

        CompanyInfo company = new CompanyInfo();
        company.setCompanyName(companyCaAuth.getCompanyName());
        company.setCreditNo(companyCaAuth.getTaxNo());
//        company.setCreditImagePath(ossUtil.getUrlWw(ossUtil.replaceLongKeyUrl(companyCaAuth.getBusinessLicenseUrl())));

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

        JSONObject resultJson = Auth4FDDUtil.getAuthCompanyUrl(companyCaAuth.getFadadaCustomerId(), this.fddAuthPageModify,
                this.fddAuthVerifiedWay, null, null, null,
                null, null, null, null, null,
                null, null, null, null, null, this.fddAuthNotifyUrl,
                null, company, legal, null, null);

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

        companyCaAuth.setFadadaTransactionNo(data.get("transactionNo", String.class))
                .setFadadaAuthUrl(authUrl);
        companyCaAuth.updateById();

        return authUrl;
    }
}
