package com.jianshui.invoiceall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.enums.ErrorCode;
import com.jianshui.common.utils.ValidateUtils;
import com.jianshui.common.utils.http.HttpUtils;
import com.jianshui.invoiceall.domain.dto.InoviceAllQdLoginDTO;
import com.jianshui.invoiceall.domain.dto.eleplant.AutonomousAuthorizationDTO;
import com.jianshui.invoiceall.domain.dto.eleplant.InvoiceAllSubmitNoteDTO;
import com.jianshui.invoiceall.service.AutonomousSqService;
import com.jianshui.system.domain.InvoiceAllApiLog;
import com.jianshui.system.domain.InvoiceAllLoginResult;
import com.jianshui.system.domain.InvoiceAllYhdj;
import com.jianshui.system.mapper.CompanyserviceMapper;
import com.jianshui.system.mapper.InvoiceAllApiLogMapper;
import com.jianshui.system.mapper.InvoiceAllLoginResultMapper;
import com.jianshui.system.mapper.InvoiceAllYhdjMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author xingze
 * @date 2023/8/13
 */
@Service
@Slf4j
public class AutonomousSqServiceImpl implements AutonomousSqService {
    @Autowired
    private InvoiceAllApiLogMapper allApiLogMapper;

    @Autowired
    private InvoiceAllYhdjMapper yhdjMapper;

    @Autowired
    private InvoiceAllLoginResultMapper invoiceAllLoginResultMapper;
    @Autowired
    private CompanyserviceMapper companyserviceMapper;

    /**
     * 功能描述: 自主授权回调接口
     *
     * @param autonomousAuthorization
     * @return : java.lang.Object
     */
    @Override
    public Object autonomousAuthorization(AutonomousAuthorizationDTO autonomousAuthorization) {
        log.info("自主信息授权回调接口,入参：{}", JSONUtil.toJsonStr(autonomousAuthorization));
        // 存流水号
        InvoiceAllLoginResult byQqlsh = invoiceAllLoginResultMapper.findByQqlsh(autonomousAuthorization.getTrace());
        if (byQqlsh != null) {
            InvoiceAllLoginResult invoiceAllLoginResult = new InvoiceAllLoginResult();
            BeanUtil.copyProperties(autonomousAuthorization,invoiceAllLoginResult);
            invoiceAllLoginResult.setUpdateTime(new Date());
            int count = invoiceAllLoginResultMapper.updateInvoiceResult(invoiceAllLoginResult);
            if (count > 0) {
                log.info("全电登录接口，登录返回信息更新成功,信息为：{}", JSONUtil.toJsonStr(invoiceAllLoginResult));
            } else {
                log.error("全电登录接口，登录返回信息更新失败,信息为：{}", JSONUtil.toJsonStr(invoiceAllLoginResult));
            }
        } else {
            InvoiceAllLoginResult invoiceAllLoginResult = new InvoiceAllLoginResult();
            BeanUtil.copyProperties(autonomousAuthorization, invoiceAllLoginResult);
            invoiceAllLoginResult.setCreateTime(new Date());
            int count = invoiceAllLoginResultMapper.insertInvoiceAllLoginResult(invoiceAllLoginResult);
            if (count > 0) {
                log.info("全电登录接口，登录返回信息保存成功,信息为：{}", JSONUtil.toJsonStr(invoiceAllLoginResult));
            } else {
                log.error("全电登录接口，登录返回信息保存失败,信息为：{}", JSONUtil.toJsonStr(invoiceAllLoginResult));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 功能描述: 全电登录获取回调结果
     *
     * @param invoiceAllSubmitNoteDTO
     * @return : java.lang.Object
     */
    @Override
    public Object submitNoteResult(InvoiceAllSubmitNoteDTO invoiceAllSubmitNoteDTO) {
        log.info("全电登录获取回调结果，入参：{}", JSONUtil.toJsonStr(invoiceAllSubmitNoteDTO));
        // 短信提交
        InvoiceAllLoginResult invoiceAllLoginResult = invoiceAllLoginResultMapper.findByQqlsh(invoiceAllSubmitNoteDTO.getTraceno());
        if (invoiceAllLoginResult == null) {
            log.info("全电登录获取回调结果，未查询到该流水号相关信息，请确认后输入");
            return AjaxResult.success("未查询到该流水号相关信息，请确认后输入");
        }
        if ("F000".equals(invoiceAllLoginResult.getCode())) {
//            String[] splitResult = invoiceAllLoginResult.getMsg().split("：");
//            if (StringUtils.isNotBlank(splitResult[1])){
//                return AjaxResult.error(splitResult[1]);
//            }else {
//                return AjaxResult.error(splitResult[0]);
//            }
            return AjaxResult.error(invoiceAllLoginResult.getMsg());
        } else if ("S000".equals(invoiceAllLoginResult.getCode())) {
            return AjaxResult.success("10012");
        } else if ("SMS".equals(invoiceAllLoginResult.getCode())){
            return AjaxResult.success("10011");
        }else {
            return AjaxResult.success("获取失败");
        }
    }

    /**
     * 功能描述: 根据纳税人识别号转换地区
     * @param nsrsbh
     * @return : java.lang.Object
     */
    @Override
    public Object nsrsbhConvertAddr(String nsrsbh) {
        if (nsrsbh.length() < 6){
            return AjaxResult.success("");
        }
        String subNsrsbh = nsrsbh.substring(2, 4);
        if ("15".equals(subNsrsbh)){
            return AjaxResult.success("neimeng");
        }else if ("21".equals(subNsrsbh)){
            String substringNsrsbh = nsrsbh.substring(2, 6);
            if ("2102".equals(substringNsrsbh)){
                return AjaxResult.success("dalian");
            }
            return AjaxResult.success("liaoning");
        }else if ("22".equals(subNsrsbh)){
            return AjaxResult.success("jilin");
        }else if ("23".equals(subNsrsbh)){
            return AjaxResult.success("heilongjiang");
        }else if ("31".equals(subNsrsbh)){
            return AjaxResult.success("shanghai");
        }else if ("32".equals(subNsrsbh)){
            return AjaxResult.success("jiangsu");
        }else if ("33".equals(subNsrsbh)){
            String substringNsrsbh = nsrsbh.substring(2, 6);
            if ("3302".equals(substringNsrsbh)){
                return AjaxResult.success("ningbo");
            }
            return AjaxResult.success("zhejiang");
        }else if ("34".equals(subNsrsbh)){
            return AjaxResult.success("anhui");
        }else if ("35".equals(subNsrsbh)){
            String substringNsrsbh = nsrsbh.substring(2, 6);
            if ("3502".equals(substringNsrsbh)){
                return AjaxResult.success("xiamen");
            }
            return AjaxResult.success("fujian");
        }else if ("36".equals(subNsrsbh)){
            return AjaxResult.success("jiangxi");
        }else if ("37".equals(subNsrsbh)){
            String substringNsrsbh = nsrsbh.substring(2, 6);
            if ("3702".equals(substringNsrsbh)){
                return AjaxResult.success("qingdao");
            }
            return AjaxResult.success("shandong");
        }else if ("41".equals(subNsrsbh)){
            return AjaxResult.success("henan");
        }else if ("42".equals(subNsrsbh)){
            return AjaxResult.success("hubei");
        }else if ("43".equals(subNsrsbh)){
            return AjaxResult.success("hunan");
        }else if ("44".equals(subNsrsbh)){
            String substringNsrsbh = nsrsbh.substring(2, 6);
            if ("4403".equals(substringNsrsbh)){
                return AjaxResult.success("shenzhen");
            }
            return AjaxResult.success("guangdong");
        }else if ("45".equals(subNsrsbh)){
            return AjaxResult.success("guangxi");
        }else if ("46".equals(subNsrsbh)){
            return AjaxResult.success("hainan");
        }else if ("50".equals(subNsrsbh)){
            return AjaxResult.success("chongqing");
        }else if ("51".equals(subNsrsbh)){
            return AjaxResult.success("sichuan");
        }else if ("61".equals(subNsrsbh)){
            return AjaxResult.success("shanxi");
        }else if ("62".equals(subNsrsbh)){
            return AjaxResult.success("gansu");
        }else if ("63".equals(subNsrsbh)){
            return AjaxResult.success("qinghai");
        }else if ("64".equals(subNsrsbh)){
            return AjaxResult.success("ningxia");
        }else if ("65".equals(subNsrsbh)){
            return AjaxResult.success("xinjiang");
        }else {
            return AjaxResult.success("");
        }
    }

    /**
     * 功能描述: 全电登录
     *
     * @param inoviceAllQdLoginDTO
     * @return : com.jianshui.common.core.domain.AjaxResult
     */
    @Override
    public AjaxResult qdLogin(InoviceAllQdLoginDTO inoviceAllQdLoginDTO) {
        // 全电登录
        log.info("全电登录接口，入参：{}", JSONUtil.toJsonStr(inoviceAllQdLoginDTO));
        ValidateUtils.validate(inoviceAllQdLoginDTO);
        Companyservice companyservice = companyserviceMapper.selectCompanyserviceByTaxcode(inoviceAllQdLoginDTO.getNsrsbh());
        if (BeanUtil.isEmpty(inoviceAllQdLoginDTO.getNsrInfo())) {
            log.error("全电登录接口，传入报文错误，请检查,纳税人信息为空！");
            return AjaxResult.error("传入报文错误，请检查,纳税人信息为空！");
        }
        ValidateUtils.validate(inoviceAllQdLoginDTO.getNsrInfo());
        // 流水号(唯一)
        String qqlsh = inoviceAllQdLoginDTO.getNsrsbh() + inoviceAllQdLoginDTO.getNsrInfo().getGsnsyhm() + System.currentTimeMillis();
        inoviceAllQdLoginDTO.setTraceno(qqlsh);
        try {
            // 回调地址
            inoviceAllQdLoginDTO.setLoginType("1");
            inoviceAllQdLoginDTO.setCallback("http://dev.goldentaxcloud.com:8081/api/invoice_all/v1/autonomousAuthorization");
            log.info("全电登录接口，请求上游，地址：{},参数：{}", "http://zzsq.jcsk100.com/login/getLogin2", JSONUtil.toJsonStr(inoviceAllQdLoginDTO));
            Thread requestThread = new Thread(() -> {
                HttpUtils.sendJsonPost("http://zzsq.jcsk100.com/login/getLogin2", inoviceAllQdLoginDTO);
            });
            requestThread.start();
            // 用户信息封装
            InvoiceAllYhdj yhdj = BeanUtil.copyProperties(inoviceAllQdLoginDTO, InvoiceAllYhdj.class);
            yhdj.setDlsfmm(inoviceAllQdLoginDTO.getNsrInfo().getGsnsmm());
            yhdj.setBsrysfzjhm(inoviceAllQdLoginDTO.getNsrInfo().getSfzjhm());
            yhdj.setDlzh(inoviceAllQdLoginDTO.getNsrInfo().getGsnsyhm());
            yhdj.setBsryxm(inoviceAllQdLoginDTO.getNsrInfo().getBsryxz());
            QueryWrapper<InvoiceAllYhdj> yhdjQueryWrapper = new QueryWrapper<>();
            yhdjQueryWrapper.eq("nsrsbh", yhdj.getNsrsbh());
            yhdjQueryWrapper.eq("identity", companyservice.getIdentity());
            InvoiceAllYhdj yhdjTemp = yhdjMapper.selectOne(yhdjQueryWrapper);
            // 日志信息
            InvoiceAllApiLog invoiceAllApiLog = new InvoiceAllApiLog();
            invoiceAllApiLog.setCreateTime(new Date());
            invoiceAllApiLog.setCompany(companyservice.getSellertax());
            invoiceAllApiLog.setIdentityId(companyservice.getIdentity());
            invoiceAllApiLog.setUrl("http://zzsq.jcsk100.com/login/getLogin2");
            invoiceAllApiLog.setSendMsg(JSONUtil.toJsonStr(inoviceAllQdLoginDTO));
            invoiceAllApiLog.setRequestId(qqlsh);
            allApiLogMapper.insert(invoiceAllApiLog);
            // 更新记录表
            if (BeanUtil.isNotEmpty(yhdjTemp)) {
                BeanUtil.copyProperties(yhdj, yhdjTemp, CopyOptions.create().setIgnoreNullValue(true));
                yhdjTemp.setUpdateTime(new Date());
                yhdjMapper.updateInvoiceAllYhdj(yhdjTemp);
            } else {
                yhdj.setCreateTime(new Date());
                yhdj.setIdentity(companyservice.getIdentity());
                yhdjMapper.insertInvoiceAllYhdj(yhdj);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【全电登录】API请求异常，外部报文返回code非S000。错误信息:{}", e.getMessage());
            return AjaxResult.error(ErrorCode.INCOME_ERROR);
        }
        return AjaxResult.success(qqlsh);
    }

    /**
     * 功能描述: 提交短信验证码
     *
     * @param invoiceAllSubmitNoteDTO
     * @return : com.jianshui.common.core.domain.AjaxResult
     */
    @Override
    public AjaxResult submitNote(InvoiceAllSubmitNoteDTO invoiceAllSubmitNoteDTO) {
        log.info("自主授权短信提交接口，入参：{}", JSONUtil.toJsonStr(invoiceAllSubmitNoteDTO));
        // 短信提交
        ValidateUtils.validate(invoiceAllSubmitNoteDTO);
        // 根据流水号获取登录结果
        InvoiceAllLoginResult invoiceAllLoginResult = invoiceAllLoginResultMapper.findByQqlsh(invoiceAllSubmitNoteDTO.getTraceno());
        if (invoiceAllLoginResult == null) {
            log.info("自主授权短信提交接口，未查询到该流水号相关信息，请确认后输入");
            return AjaxResult.error("未查询到该流水号相关信息，请确认后输入");
        }
        if ("SMS".equals(invoiceAllLoginResult.getCode()) || "F000".equals(invoiceAllLoginResult.getCode())) {
            try {
                // 请求封装
                log.info("自主授权短信提交接口，请求上游地址：{}，入参：{}", "http://zzsq.jcsk100.com/login/submitSms", JSONUtil.toJsonStr(invoiceAllSubmitNoteDTO));
                Thread requestThread = new Thread(() -> {
                    HttpUtils.sendJsonPost("http://zzsq.jcsk100.com/login/submitSms", invoiceAllSubmitNoteDTO);
                });
                requestThread.start();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("【金四服务类】【自主授权提交短信验证码】API请求异常，外部报文返回code非S000。错误信息:{}", e.getMessage());
                return AjaxResult.error(ErrorCode.INCOME_ERROR);
            }
        }else if ("S000".equals(invoiceAllLoginResult.getCode())){
            return AjaxResult.success("10012");
        }else {
            log.error("自主授权短信提交接口，提交短信失败，失败原因：{}", "登录失败，请重新授权登录");
            return AjaxResult.error("登录失败，请重新授权登录");
        }
        return AjaxResult.success();
    }
}
