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.entity.CompanyAuthDO;
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;

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

    @Autowired
    private QccEntAuthUtil qccEntAuthUtil;

    @Autowired
    private CompanyAuthDao companyAuthDao;

    @Override
    public ResultBody add(CompanyAuthVO companyAuthVO) {
        log.info("用户:"+companyAuthVO.getUserAccountId()+" 企业认证：{}", JSONObject.toJSONString(companyAuthVO));
        CompanyAuthDO companyAuthDO = companyAuthDao.getCompanyAuth(companyAuthVO.getUserAccountId());
        if (companyAuthDO != null){
            return ResultBody.success("已通过");
        }
        ResultBody companyCheckRes = this.companyCheck(companyAuthVO);
        System.out.println(companyCheckRes);
        if (!companyCheckRes.getCode().equals("200")){

            return companyCheckRes;
        }
        companyAuthDO = new CompanyAuthDO(companyAuthVO);
        companyAuthDO.setAuthStatus(1);
        companyAuthDao.addCompanyAuth(companyAuthDO);
        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) {
        CompanyAuthDO companyAuthDO = companyAuthDao.getCompanyAuth(userAccountId);
        if (companyAuthDO == null){
            return null;
        }
        return companyAuthDO.buildCompanyAuth();
    }
}
