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

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.ElectronicSignatureUtil;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.financing.contract.ElectronicPersonInfo;
import com.sunxung.factoring.entity.financing.contract.SysCustomer;
import com.sunxung.factoring.mapper.financing.contract.SysCustomerMapper;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.financing.contract.IElectronicPersonInfoService;
import com.sunxung.factoring.service.financing.contract.ISysCustomerService;
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.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 IElectronicPersonInfoService electronicPersonInfoService;

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysCustomer sysCustomer) {
        //是否存在该供应商
        SysCustomer customer = getOne(new QueryWrapper<SysCustomer>().eq("ent_business_id", sysCustomer.getEntBusinessId()).eq("account_type", sysCustomer.getAccountType()).last("LIMIT 1"));
        if (customer != null) {
            throw new ValidatorException(CodeUtil.FAIL, "已经存在该企业信息，请勿重复添加");
        }

        if (sysCustomer.getAccountType().equals("1")) {
            ElectronicPersonInfo personInfo = electronicPersonInfoService.getBySocialCreditCode(sysCustomer.getElectronicPersonInfo().getSocialCreditCode());
            if (personInfo != null) {
                throw new ValidatorException(CodeUtil.FAIL, "已经存在该信息，请勿重复添加");
            }
            Integer j = 0;
            ElectronicPersonInfo electronicPersonInfo = sysCustomer.getElectronicPersonInfo();
            electronicPersonInfoService.saveOrUpdate(electronicPersonInfo);
            sysCustomer.setEntBusinessId(electronicPersonInfo.getId());
        }

        if (sysCustomer.getId() == null) {

            String openId = getOpenId(sysCustomer);
            //法大大认证
            String customerId = null;
            String authUrl = null;
            //添加身份信息

            String idType = sysCustomer.getElectronicPersonInfo() == null ? "" : sysCustomer.getElectronicPersonInfo().getCardTypeId();
            String idNumber = sysCustomer.getElectronicPersonInfo() == null ? "" : sysCustomer.getElectronicPersonInfo().getSocialCreditCode();
            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");
            } else if (sysCustomer.getAccountType().equals("2")) {
                String authResult = ElectronicSignatureUtil.getAuthUrl(sysCustomer.getAccountType(), openId, null);
                JSONObject authJson = (JSONObject) JSONObject.parse(authResult);
                authUrl = authJson.getString("authUrl");
                customerId = authJson.getString("customerId");
            }

            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);
//            保存记录
            saveOrUpdate(sysCustomer);
        }
    }

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

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

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