package com.chinaweal.aiccs.outside.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.revoke.entity.CancelRegisterList;
import com.chinaweal.aiccs.aiccs.revoke.entity.CancelRevocationRegList;
import com.chinaweal.aiccs.aiccs.revoke.entity.CancelRevokelist;
import com.chinaweal.aiccs.aiccs.revoke.entity.Revokelist;
import com.chinaweal.aiccs.aiccs.revoke.service.CancelRegisterListService;
import com.chinaweal.aiccs.aiccs.revoke.service.CancelRevocationRegListService;
import com.chinaweal.aiccs.aiccs.revoke.service.CancelRevokelistService;
import com.chinaweal.aiccs.aiccs.revoke.service.RevokelistService;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.outside.api.MosSMSApi;
import com.chinaweal.aiccs.outside.api.TfServiceApi;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.dtflys.forest.http.ForestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 泰富吊销接口
 */
@Service
@Slf4j
public class TfRevokeServicelmpl {

    @Resource
    private TfServiceApi tfServiceApi;
    @Resource
    private RevokelistService revokelistService;
    @Resource
    private CancelRevokelistService cancelRevokelistService;
    @Resource
    private CancelRegisterListService cancelRegisterListService;
    @Resource
    private CancelRevocationRegListService cancelRevocationRegListService;

    @Value("${tfApi.appid}")
    private String appid;

    @Value("${tfApi.appsecret}")
    private String appsecret;

    /**
     * 获取token接口
     * lwd
     * 2021-09-03
     */
    public String queryTfToken() {
        String token = "";
        try {
            //调用泰富token接口
            ForestResponse<Map<String, Object>> tokens = tfServiceApi.getToken(appid, appsecret);
            Map<String, Object> result = tokens.getResult();
            Integer code = (Integer) result.get("code");
            if ("200".equals(String.valueOf(code))) {
                Map<String, Object> tokenmap = (Map<String, Object>) result.get("data");
                token = (String) tokenmap.get("token");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("批吊--泰富token接口访问异常"+e);
            throw new BusinessException("批吊--泰富token接口访问异常");
        }
        return token;
    }

    public String pushRevocation(String appid, Map<String, Object> param, String revlistid) {
        try {
            //调用泰富token接口
            ForestResponse<Map<String, Object>> tokens = tfServiceApi.revocationAiccode(appid, param);
            Revokelist revokelistModel = new Revokelist();
            revokelistModel.setRevlistid(revlistid);
            Map<String, Object> result = tokens.getResult();
            String code = StringUtils.tranObject(result.get("code"));
            String excode = StringUtils.tranObject(result.get("excode"));
            String message = StringUtils.tranObject(result.get("message"));
            revokelistModel.setCode(code);
            revokelistModel.setExCode(excode);
            revokelistModel.setMessage(message);
            revokelistModel.setReturnTime(LocalDateTime.now());
            boolean update = revokelistService.updateById(revokelistModel);
            if(!update){// 保存推送结果失败
                log.info("数据主键为{}推送结果保存失败",revlistid);
            }
            if("500".equals(code)){
                log.info("数据主键为{}推送返回异常结果",revlistid);
                return "error";
            }
        }catch(Exception e) {
            e.printStackTrace();
            log.error("数据主键为{}推送异常"+e,revlistid);
            return "error";
        }
        return "success";
    }

    /**
     * 获取token接口
     * zhouxy
     * 2023-04-19
     */
    public String queryTfToken(String msg) {
        String token = "";
        try {
            //调用泰富token接口
            ForestResponse<Map<String, Object>> tokens = tfServiceApi.getToken(appid, appsecret);
            Map<String, Object> result = tokens.getResult();
            if(result != null){
                Integer code = (Integer) result.get("code");
                if ("200".equals(String.valueOf(code))) {
                    Map<String, Object> tokenmap = (Map<String, Object>) result.get("data");
                    token = (String) tokenmap.get("token");
                }
            } else {
                token = "error";
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("{}--泰富token接口访问异常"+e,msg);
            throw new BusinessException(msg+"--泰富token接口访问异常");
        }
        return token;
    }

    public String cancelRevocation(String token, Map<String, Object> param, CancelRevokelist cancelRevoke) {
        try {
            //调用泰富token接口（可复用吊销接口的token）
            ForestResponse<Map<String, Object>> tokens = tfServiceApi.revocationAiccode(token, param);
            String revcancelid = cancelRevoke.getRevcancelid();
            Map<String, Object> result = tokens.getResult();
            String code = StringUtils.tranObject(result.get("code"));
            String excode = StringUtils.tranObject(result.get("excode"));
            String message = StringUtils.tranObject(result.get("message"));
            cancelRevoke.setCode(code)
                        .setExCode(excode)
                        .setMessage(message)
                        .setReturnTime(LocalDateTime.now());
            CancelRevokelist cancel = cancelRevokelistService.getOne(new LambdaQueryWrapper<CancelRevokelist>().eq(CancelRevokelist::getRevcancelid, revcancelid));
            if(cancel == null){ //若已有撤销吊销记录，则说明是第二次推送，不需要存入数据库
                boolean save = cancelRevokelistService.save(cancelRevoke);
                if(!save){// 保存推送结果失败
                    log.info("数据主键为{}推送结果保存失败",revcancelid);
                    return "error";
                }
            }
            if("500".equals(code)){
                log.info("数据主键为{}推送返回异常结果，原因{}",revcancelid,message);
                //返回异常代码
                return excode;
            }
        }catch(Exception e) {
            e.printStackTrace();
            log.error("数据主键为{}推送异常"+e,cancelRevoke.getRevcancelid());
            return "error";
        }
        return "success";
    }

    public String revocationReg(String token, Map<String, Object> param, CancelRegisterList cancelRegister) {
        try {
            //调用泰富撤销设立接口
            ForestResponse<Map<String, Object>> tokens = tfServiceApi.revocationAiccode(token, param);
            String fraudId = cancelRegister.getBizFraudId();
            Map<String, Object> result = tokens.getResult();
            String code = StringUtils.tranObject(result.get("code"));
            String excode = StringUtils.tranObject(result.get("excode"));
            String message = StringUtils.tranObject(result.get("message"));
            cancelRegister.setCode(code)
                    .setExCode(excode)
                    .setMessage(message)
                    .setReturnTime(LocalDateTime.now());
            boolean save = cancelRegisterListService.saveOrUpdate(cancelRegister);
            if(!save){// 保存推送结果失败
                log.info("数据主键为{}推送结果保存失败", fraudId);
            }
            if("500".equals(code)){
                log.info("数据主键为{}推送返回异常结果原因{}", fraudId, message);
                return excode;
            }
        }catch(Exception e) {
            e.printStackTrace();
            log.error("数据主键为{}推送异常"+e, cancelRegister.getBizFraudId());
            return "error";
        }
        return "success";
    }

    public String cancelRevocationReg(String token, Map<String, Object> param, CancelRevocationRegList cancelRevocationRegList) {
        try {
            //调用泰富撤销撤销设立接口
            ForestResponse<Map<String, Object>> tokens = tfServiceApi.revocationAiccode(token, param);
            String fraudId = cancelRevocationRegList.getRevokeTBizFraudId();
            Map<String, Object> result = tokens.getResult();
            String code = StringUtils.tranObject(result.get("code"));
            String excode = StringUtils.tranObject(result.get("excode"));
            String message = StringUtils.tranObject(result.get("message"));
            cancelRevocationRegList.setCode(code)
                    .setExCode(excode)
                    .setMessage(message)
                    .setReturnTime(LocalDateTime.now());
            boolean save = cancelRevocationRegListService.saveOrUpdate(cancelRevocationRegList);
            if(!save){// 保存推送结果失败
                log.info("数据主键为{}推送结果保存失败", fraudId);
            }
            if("500".equals(code)){
                log.info("数据主键为{}推送返回异常结果原因{}", fraudId, message);
                return excode;
            }
        }catch(Exception e) {
            e.printStackTrace();
            log.error("数据主键为{}推送异常"+e, cancelRevocationRegList.getRevokeTBizFraudId());
            return "error";
        }
        return "success";
    }
}
