package com.sunxung.factoring.service.financing.contract.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.ElectronicSignatureUtil;
import com.sunxung.factoring.component.util.StringUtil;
import com.sunxung.factoring.entity.customerinformation.ElectronicSignaturePersonal;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.financing.contract.SysCustomer;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.mapper.financing.contract.SysCustomerMapper;
import com.sunxung.factoring.service.customerinformation.IElectronicSignaturePersonalService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.financing.contract.ISysCustomerService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 企业信息管理表 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2022-06-20
 */
@Service
public class SysCustomerServiceImpl extends ServiceImpl<SysCustomerMapper, SysCustomer> implements ISysCustomerService {

    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;

    @Autowired
    private PlatformService platformService;

    @Override
    public SysCustomer getByName(String companyName) {
        return baseMapper.getByName(companyName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysCustomer add(SysCustomer sysCustomer) {
        //是否存在该供应商
        SysCustomer customer;
        if (sysCustomer.getEntBusinessId() != null) {
            customer = getOne(new QueryWrapper<SysCustomer>().eq("ent_business_id", sysCustomer.getEntBusinessId()).eq("account_type", sysCustomer.getAccountType()).last("LIMIT 1"));
        } else {
            customer = lambdaQuery().eq(SysCustomer::getPlatformId, sysCustomer.getPlatformId()).eq(SysCustomer::getAccountType, sysCustomer.getAccountType()).one();
        }

        if (customer == null) {
            if (sysCustomer.getAccountType().equals("1")) {
                String openId = getOpenId(sysCustomer);
                //法大大认证
                String customerId = null;
                String authUrl = null;
                //添加身份信息
                if (sysCustomer.getAccountType().equals("1")) {
                    customerId = ElectronicSignatureUtil.registerAccount(openId, sysCustomer.getAccountType());
                    String authResult = ElectronicSignatureUtil.getAuthUrl(sysCustomer.getAccountType(), customerId, null);
                    JSONObject authJson = (JSONObject) JSONObject.parse(authResult);
                    authUrl = authJson.getString("authUrl");
                    if (authUrl == null || customerId == null) {
                        throw new ValidatorException(CodeUtil.FAIL, "生成认证链接出错");
                    }
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, authUrl);
                    sysCustomer.setShortAuthUrl(shortUrl);
                    sysCustomer.setShortAuthUrlCreate(new Date());
                    sysCustomer.setFddCustomerId(customerId);
                    sysCustomer.setAuthStatus(false);
                    sysCustomer.setAuthUrl(authUrl);
                    //开启自动签署
                    String transactionId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
                    String beforeAutoSignUrl = ElectronicSignatureUtil.beforeAutoSign(transactionId, customerId, customerId);
                    String shortAutoSignUrl = ElectronicSignatureUtil.shortUrl(null, beforeAutoSignUrl);
                    sysCustomer.setShortAutoSignUrl(shortAutoSignUrl);
                    sysCustomer.setShortAutoSignUrlCreate(new Date());
                    sysCustomer.setTransactionId(transactionId);
                    sysCustomer.setAutoSignStatus(0);
                    sysCustomer.setAutoSignUrl(beforeAutoSignUrl);

                    //更新电子签个人
                    ElectronicSignaturePersonal electronicSignaturePersonal = sysCustomer.getElectronicSignaturePersonal();
                    electronicSignaturePersonal.setFddCustomerId(customerId);
                    electronicSignaturePersonal.setOpenId(openId);
                    electronicSignaturePersonal.setAuthUrl(authUrl);
                    electronicSignaturePersonal.setShortAuthUrl(shortUrl);
                    electronicSignaturePersonal.setShortAuthUrlCreat(new Date());
                    electronicSignaturePersonal.setAuthStatus(0);
                    electronicSignaturePersonalService.save(electronicSignaturePersonal);

                    sysCustomer.setEntBusinessId(electronicSignaturePersonal.getId());
                }
            } else if (sysCustomer.getAccountType().equals("2")) {
                String shortUrl = null;
                String customerId = null;
                String authUrl = null;
                String shortAutoSignUrl = null;
                String beforeAutoSignUrl = null;
                Boolean authStatus = null;
                Integer autoSignStatus = 0;
                Date shortAuthUrlCreate = new Date();
                Date shortAutoSignUrlCreate = new Date();
                if (sysCustomer.getEntBusinessId() != null) {
                    Enterprise enterprise = enterpriseService.getById(sysCustomer.getEntBusinessId());
                    shortUrl = enterprise.getShortAuthUrl();
                    customerId = enterprise.getFddCustomerId();
                    authUrl = enterprise.getAuthUrl();
                    shortAutoSignUrl = enterprise.getShortAutoSignUrl();
                    beforeAutoSignUrl = enterprise.getAutoSignUrl();
                    authStatus = enterprise.getAuthStatus();
                    autoSignStatus = enterprise.getAutoSignStatus();
                } else if (sysCustomer.getPlatformId() != null) {
                    Platform platform = platformService.getById(sysCustomer.getPlatformId());
                    shortUrl = platform.getShortAuthUrl();
                    customerId = platform.getFddCustomerId();
                    authUrl = platform.getAuthUrl();
                    shortAutoSignUrl = platform.getShortAutoSignUrl();
                    beforeAutoSignUrl = platform.getAutoSignUrl();
                    authStatus = platform.getAuthStatus() == 0 ? false : true;
                    autoSignStatus = platform.isAutoSignStatus() == true ? 1 : 0;
                    shortAuthUrlCreate = platform.getShortAuthUrlCreate();
                    shortAutoSignUrlCreate = platform.getShortAutoSignUrlCreate();
                }
                sysCustomer.setShortAuthUrl(shortUrl);
                sysCustomer.setShortAuthUrlCreate(shortAuthUrlCreate);
                sysCustomer.setFddCustomerId(customerId);
                sysCustomer.setAuthStatus(authStatus);
                sysCustomer.setAuthUrl(authUrl);
                //开启自动签署
                sysCustomer.setShortAutoSignUrl(shortAutoSignUrl);
                sysCustomer.setShortAutoSignUrlCreate(shortAutoSignUrlCreate);
                sysCustomer.setAutoSignStatus(autoSignStatus);
                sysCustomer.setAutoSignUrl(beforeAutoSignUrl);
            }
//            保存记录
            save(sysCustomer);
            return sysCustomer;
        } else {
            return customer;
        }

    }

    @Override
    public SysCustomer getCustomerIdBySocialCreditCode(String socialCreditCode) {
        return baseMapper.getCustomerIdBySocialCreditCode(socialCreditCode);
    }

    @Override
    public SysCustomer getCustomerPersonBySocialCreditCode(String socialCreditCode) {
        return baseMapper.getCustomerPersonBySocialCreditCode(socialCreditCode);
    }

    @Override
    public void urlJob() {
        Date date = new Date();
        Date dateTime = DateUtil.offsetDay(date, -6);
        List<SysCustomer> sysCustomers = lambdaQuery().eq(SysCustomer::getAuthStatus, false).isNotNull(SysCustomer::getAuthUrl).list();
        if(CollectionUtil.isNotEmpty(sysCustomers)){
            for (SysCustomer sysCustomer : sysCustomers) {
                if(StringUtil.isEmpty(sysCustomer.getShortAuthUrl())){
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, sysCustomer.getShortAuthUrl());
                    sysCustomer.setShortAuthUrl(shortUrl);
                    sysCustomer.setShortAuthUrlCreate(date);
                }else if(sysCustomer.getShortAuthUrlCreate().compareTo(dateTime) < 1){
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, sysCustomer.getShortAuthUrl());
                    sysCustomer.setShortAuthUrl(shortUrl);
                    sysCustomer.setShortAuthUrlCreate(date);
                }
                updateById(sysCustomer);
            }
        }
        List<SysCustomer> sysCustomerAutos = lambdaQuery().eq(SysCustomer::getAutoSignStatus, 0).isNotNull(SysCustomer::getAutoSignUrl).list();
        if(CollectionUtil.isNotEmpty(sysCustomerAutos)){
            for (SysCustomer sysCustomerAuto : sysCustomerAutos) {
                if(StringUtil.isEmpty(sysCustomerAuto.getShortAutoSignUrl())){
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, sysCustomerAuto.getShortAutoSignUrl());
                    sysCustomerAuto.setShortAutoSignUrl(shortUrl);
                    sysCustomerAuto.setShortAutoSignUrlCreate(date);
                }else if(sysCustomerAuto.getShortAutoSignUrlCreate().compareTo(dateTime) < 1){
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, sysCustomerAuto.getShortAutoSignUrl());
                    sysCustomerAuto.setShortAutoSignUrl(shortUrl);
                    sysCustomerAuto.setShortAutoSignUrlCreate(date);
                }
                updateById(sysCustomerAuto);
            }
        }
        List<SysCustomer> sysCustomerCertificates = lambdaQuery().eq(SysCustomer::getCertificateSignStatus, 0).isNotNull(SysCustomer::getCertificateSignUrl).list();
        if(CollectionUtil.isNotEmpty(sysCustomerCertificates)){
            for (SysCustomer sysCustomerCertificate : sysCustomerCertificates) {
                if(StringUtil.isEmpty(sysCustomerCertificate.getCertificateShortSignUrl())){
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, sysCustomerCertificate.getCertificateShortSignUrl());
                    sysCustomerCertificate.setCertificateShortSignUrl(shortUrl);
                    sysCustomerCertificate.setCertificateShortSignUrlCreate(date);
                }else if(sysCustomerCertificate.getCertificateShortSignUrlCreate().compareTo(dateTime) < 1){
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, sysCustomerCertificate.getCertificateShortSignUrl());
                    sysCustomerCertificate.setCertificateShortSignUrl(shortUrl);
                    sysCustomerCertificate.setCertificateShortSignUrlCreate(date);
                }
                updateById(sysCustomerCertificate);
            }
        }
    }

    private String getOpenId(SysCustomer sysCustomer) {
        String openId = "";
        if (sysCustomer.getAccountType().equals("1")) {
            openId = sysCustomer.getElectronicSignaturePersonal().getSocialCreditCode();
        } else {
            Enterprise enterprise = enterpriseService.getById(sysCustomer.getEntBusinessId());
            if (enterprise != null) {
                openId = enterprise.getSocialCreditCode();
            }
        }
        return openId;
    }
}
