package com.mmc.iuav.user.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
import com.mmc.iuav.user.dao.CompanyAuthDao;
import com.mmc.iuav.user.dao.CompanyDao;
import com.mmc.iuav.user.entity.CompanyInfoDO;
import com.mmc.iuav.user.entity.CompanyMemberDO;
import com.mmc.iuav.user.model.vo.CompanyAuthVO;
import com.mmc.iuav.user.service.CompanyAuthService;
import com.mmc.iuav.user.util.QccEntAuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: zj
 * @Date: 2023/5/17 13:38
 */
@Slf4j
@Service
public class CompanyAuthServiceImpl implements CompanyAuthService {

    @Autowired
    private QccEntAuthUtil qccEntAuthUtil;

    @Autowired
    private CompanyAuthDao companyAuthDao;

    @Autowired
    private CompanyDao companyDao;

    @Override
    @Transactional
    public ResultBody add(CompanyAuthVO companyAuthVO) {
        log.info("用户:" + companyAuthVO.getUserAccountId() + " 企业认证：{}", JSONObject.toJSONString(companyAuthVO));
        // 查询此单位有没有被认证
        CompanyInfoDO companyInfoDO = companyDao.getCompanyInfoByName(companyAuthVO.getCompanyName());
        if (companyInfoDO != null) {
            List<CompanyMemberDO> companyMemberDOS = companyDao.listCompanyMembers(companyInfoDO.getId());
            if (!CollectionUtils.isEmpty(companyMemberDOS)) {
                return ResultBody.error(ResultEnum.COMPANY_EXIST_ERROR);
            }
        } else {
            companyInfoDO = new CompanyInfoDO();
            companyInfoDO.setCompanyName(companyAuthVO.getCompanyName());
            companyInfoDO.setCompanyType(1);
            companyInfoDO.setCreditCode(companyAuthVO.getCreditCode());
            companyInfoDO.setLicenseImg(companyAuthVO.getLicenseImg());
            companyDao.addCompanyInfo(companyInfoDO);
        }
        ResultBody companyCheckRes = this.companyCheck(companyAuthVO);
        if (!companyCheckRes.getCode().equals(ResultEnum.SUCCESS.getResultCode())) {
            return companyCheckRes;
        }
        // 绑定用户
        CompanyMemberDO companyMemberDO = new CompanyMemberDO();
        companyMemberDO.setCompanyInfoId(companyInfoDO.getId());
        companyMemberDO.setUserAccountId(companyAuthVO.getUserAccountId());
        companyMemberDO.setLeader(1);
        companyDao.addCompanyMember(companyMemberDO);
        return ResultBody.success();
    }

    public ResultBody companyCheck(CompanyAuthVO companyAuthVO) {
        String businessRes = qccEntAuthUtil.businessLicenseCheck(companyAuthVO.getLicenseImg());
        if (businessRes == null) {
            ResultBody resultBody = ResultBody.error(ResultEnum.BUSINESS_LICENSE_CHECK_ANALYSIS_ERROR);
            return resultBody;
        }
        //将字符串转化成json对象
        JSONObject businessResJson = JSONObject.parseObject(businessRes);
        if (businessResJson.getString("success").equals("false")) {
            return ResultBody.error(ResultEnum.BUSINESS_LICENSE_CHECK_ANALYSIS_ERROR);
        } else {
            if (businessResJson.getString("name").equals(this.convert(companyAuthVO.getCompanyName()))
                    && businessResJson.getString("reg_num").equals(companyAuthVO.getCreditCode())) {
                String check2Res = qccEntAuthUtil.check2(companyAuthVO.getCompanyName(), companyAuthVO.getCreditCode());
                if (check2Res != null) {
                    String status = qccEntAuthUtil.FormartJson(check2Res, "Status");
                    if (status.equals("200")) {
                        Integer verifyCode = qccEntAuthUtil.resultFormatJson(check2Res);
                        if (verifyCode.equals(1)) {
                            return ResultBody.success();
                        }
                        String returnString = "";
                        if (verifyCode.equals(0)) {
                            returnString = "统一社会信用代码有误";
                        } else if (verifyCode.equals(2)) {
                            returnString = "企业名称不一致";
                        } else if (verifyCode.equals(3)) {
                            returnString = "法定代表人名称不一致";
                        }
                        return ResultBody.error(returnString);
                    }
                    String errorString = "";
                    if (status.equals("201")) {
                        errorString = "查询无结果";
                    } else if (status.equals("202")) {
                        errorString = "查询参数错误，请检查";
                    } else if (status.equals("205")) {
                        errorString = "等待处理中";
                    } else if (status.equals("207")) {
                        errorString = "请求数据的条目数超过上限（5000）";
                    } else if (status.equals("208")) {
                        errorString = "此接口不支持此公司类型查询";
                    } else if (status.equals("209")) {
                        errorString = "企业数量超过上限";
                    } else if (status.equals("213")) {
                        errorString = "参数长度不能小于2";
                    } else if (status.equals("215")) {
                        errorString = "不支持的查询关键字";
                    } else if (status.equals("218")) {
                        errorString = "该企业暂不支持空壳扫描";
                    } else if (status.equals("219")) {
                        errorString = "该企业暂不支持准入尽调";
                    } else if (status.equals("105")) {
                        errorString = "接口已下线停用";
                    } else if (status.equals("110")) {
                        errorString = "当前相同查询连续出错，请等2小时后重试";
                    } else {
                        errorString = "认证报错，请联系管理员";
                    }
                    return ResultBody.error(errorString);
                } else {
                    return ResultBody.error("认证报错");
                }
            } else {
                return ResultBody.error(ResultEnum.BUSINESS_LICENSE_CHECK_PARAMETER_ERROR);
            }
        }
    }

    public String convert(String entName) {
        StringBuffer afterConvertEntName = new StringBuffer(entName);
        afterConvertEntName.length();
        for (int i = 0; i < afterConvertEntName.length(); i++) {
            if (afterConvertEntName.charAt(i) == '（') {
                afterConvertEntName.setCharAt(i, '(');
            }
            if (afterConvertEntName.charAt(i) == '）') {
                afterConvertEntName.setCharAt(i, ')');
            }
        }
        return afterConvertEntName.toString();
    }

    @Override
    public ResultBody fuzzyQueryCompany(String searchKey) {
        String companyResult = qccEntAuthUtil.fuzzySearch(searchKey);
        //将字符串转化成json对象
        JSONObject entResultJson = JSONObject.parseObject(companyResult);
        if (companyResult == null) {
            return ResultBody.error("无数据,请手动输入");
        }
        if ("200".equals(entResultJson.getString("Status"))) {
            return ResultBody.success(entResultJson);
        } else {
            return ResultBody.error("无数据,请手动输入");
        }
    }

    @Override
    public CompanyAuthVO getCompanyAuthByUId(Integer userAccountId) {
        CompanyInfoDO companyInfoDO = companyDao.getAppCompanyInfoUId(userAccountId);
        if (companyInfoDO == null) {
            return null;
        }
        CompanyAuthVO companyAuthVO = companyInfoDO.buildCompanyAuthVO();
        companyAuthVO.setUserAccountId(userAccountId);
        companyAuthVO.setAuthStatus(1);
        return companyAuthVO;
    }
}
