package com.tax.token.web.controller;

import com.tax.token.constants.TokenConstants;
import com.tax.token.integration.user.UserClient;
import com.tax.token.model.*;
import com.tax.token.service.api.TkTokenService;
import com.yxcheng.token.common.annotation.LogT;
import com.yxcheng.token.common.controller.BaseClientController;
import com.yxcheng.token.common.enumutil.ResultEnum;
import com.yxcheng.token.common.model.CrRpcResult;
import com.yxcheng.token.common.model.JsonResult;
import com.yxcheng.token.common.model.TokenInfo;
import com.yxcheng.token.utils.ObjectUtil;
import com.yxcheng.token.utils.StringUtil;
import com.yxcheng.token.utils.UUIDGenerator;
import com.yxcheng.token.utils.ZoneUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * token服务统一入口
 */
@RestController
@RequestMapping("/client")
@ComponentScan(basePackages = {"com.tax.token.service"})
public class TokenController extends BaseClientController {

    @Autowired
    private TkTokenService tokenService;
    @Autowired
    private UserClient userClient;

    @RequestMapping(value ="/getToken" , method = RequestMethod.GET)
    @LogT
    public JsonResult<String>getToken(@RequestParam(value="taxno",required = true)String taxno,
                                      @RequestParam(value="zoneCode",required = true)String zoneCode,
                                      @RequestParam(value="userCode",required = true)String userCode){
        return tokenService.getToken(taxno, zoneCode, userCode, false, TokenConstants.FUNCTION_NO_FPY);
    }

    @RequestMapping(value ={"/getCookie","/login"} , method = RequestMethod.POST)
    @LogT
    public JsonResult<String>getCookie(@RequestBody CookieReq cookieReq){
        CrRpcResult crRpcResult = userClient.isSafe(cookieReq);
        if(!checkUserSafe(crRpcResult)){
            return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
        }
        if(cookieReq.checkParamNull() || !ZoneUtil.dqList.contains(cookieReq.getZoneCode())) {
            return JsonResult.errorResult(ResultEnum.param_error.getCode(), ResultEnum.param_error.getMessage());
        }
        JsonResult result = tokenService.getToken(cookieReq.getTaxno(), cookieReq.getZoneCode(), cookieReq.getAccessKeyID(),true, TokenConstants.FUNCTION_NO_FPY);
        return result;
    }

    @RequestMapping(value ={"/getRealCookie", "/checkLoginInfo"} , method = RequestMethod.POST)
    @LogT
    public JsonResult<String>getRealCookie(@RequestBody CookieReq cookieReq){
        CrRpcResult crRpcResult = userClient.isSafe(cookieReq);
        if(!checkUserSafe(crRpcResult)){
            return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
        }
        if(cookieReq.checkParamNull() || !ZoneUtil.dqList.contains(cookieReq.getZoneCode())) {
            return JsonResult.errorResult(ResultEnum.param_error.getCode(), ResultEnum.param_error.getMessage());
        }
        if (tokenService.checkTokenRealRequestCount(cookieReq.getAccessKeyID(), cookieReq.getTaxno())) {
            int realRequestCount = tokenService.getTokenRealRequestCount(cookieReq.getAccessKeyID(), cookieReq.getTaxno());
            if(realRequestCount>60) {
                return JsonResult.errorResult(ResultEnum.system_error.getCode(), "请求太频繁，请20分钟后重试!");
            }
        }
        String uuId = UUIDGenerator.generate();
        tokenService.setTokenRealRequestCount(cookieReq.getAccessKeyID(), cookieReq.getTaxno());

        return tokenService.getRealCookie(uuId, cookieReq.getTaxno(), cookieReq.getZoneCode(), cookieReq.getAccessKeyID(), true, TokenConstants.FUNCTION_NO_FPY, cookieReq.getUserInfoJson(), cookieReq.getCheckType(), cookieReq.getSite(), cookieReq.getTarget());
    }

    @RequestMapping(value ={"/getEtaxCookie", "/checkEtaxLoginInfo"} , method = RequestMethod.POST)
    @LogT
    public JsonResult<String>getEtaxCookie(@RequestBody CookieReq cookieReq){
        CrRpcResult crRpcResult = userClient.isSafe(cookieReq);
        if(!checkUserSafe(crRpcResult)){
            return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
        }
        if(cookieReq.checkParamNull() || !ZoneUtil.dqList.contains(cookieReq.getZoneCode())) {
            return JsonResult.errorResult(ResultEnum.param_error.getCode(), ResultEnum.param_error.getMessage());
        }
        String uuId = UUIDGenerator.generate();
        return tokenService.getRealCookie(uuId, cookieReq.getTaxno(), cookieReq.getZoneCode(), cookieReq.getAccessKeyID(), true,
               TokenConstants.FUNCTION_NO_DZSJ, cookieReq.getUserInfoJson(), cookieReq.getCheckType(), cookieReq.getSite(), cookieReq.getTarget());
    }

    @RequestMapping(value ={"/getNowCookie", "/checkIsLogin"} , method = RequestMethod.POST)
    @LogT
    public JsonResult<String> getNowCookie(@RequestBody CookieReq cookieReq){
        CrRpcResult crRpcResult = userClient.isSafe(cookieReq);
        if(!checkUserSafe(crRpcResult)){
            return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
        }
        String uuId = UUIDGenerator.generate();
        JsonResult<String> jsonResult = tokenService.getRealCookie(uuId, cookieReq.getTaxno(), cookieReq.getZoneCode(),
                cookieReq.getAccessKeyID(), false, TokenConstants.FUNCTION_NO_FPY,
                cookieReq.getUserInfoJson(), cookieReq.getCheckType(), cookieReq.getSite(), cookieReq.getTarget());
        //自动跳转并注册电子税局接口部分
        boolean isEle = tokenService.updateTokenFrom(uuId, cookieReq, jsonResult);
        if(isEle) {
            jsonResult = tokenService.getRealCookie(uuId, cookieReq.getTaxno(), cookieReq.getZoneCode(), "e" + cookieReq.getAccessKeyID(),
                    false, TokenConstants.FUNCTION_NO_FPY,
                    cookieReq.getUserInfoJson(), cookieReq.getCheckType(), cookieReq.getSite(), cookieReq.getTarget());
        }
        return jsonResult;
    }

    @RequestMapping(value ="/updateErrorInfo" , method = RequestMethod.POST)
    @LogT
    public JsonResult<String>updateErrorInfo(@RequestBody PushTokenReq pushTokenReq){
        if(StringUtil.isEmpty(pushTokenReq.getUserCode()) || StringUtil.isEmpty(pushTokenReq.getTaxno())
                || StringUtil.isEmpty(pushTokenReq.getCode()) || StringUtil.isEmpty(pushTokenReq.getMessage())) {
            return new JsonResult().errorResponse(ResultEnum.param_error);
        }
        return tokenService.updateErrorInfo(pushTokenReq);
    }

    @RequestMapping(value ="/pushToken" , method = RequestMethod.POST)
    @LogT
    public JsonResult<String>pushToken(@RequestBody PushTokenReq pushTokenReq){
        if(!ObjectUtil.checkData(pushTokenReq.getTaxno(),pushTokenReq.getZoneCode(),pushTokenReq.getToken(),pushTokenReq.getRecevDate())){
            return new JsonResult().errorResponse(ResultEnum.param_error);
        }
        CrRpcResult crRpcResult = userClient.isSafe(pushTokenReq);
        if(!checkUserSafe(crRpcResult)){
            return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
        }
        return new JsonResult().errorResponse(ResultEnum.system_error);
    }

    @RequestMapping(value ="list" , method = RequestMethod.GET)
    public JsonResult<String>test(){
        return new JsonResult<String>();
    }

    @RequestMapping(value ="/signData" , method = RequestMethod.POST)
    @LogT
    public JsonResult<String>signData(@RequestBody SignDataReq signDataReq){
        return tokenService.signData(signDataReq);
    }



    @RequestMapping(value ="/getSignFromTaxDisk" , method = RequestMethod.POST)
    @LogT
    public JsonResult<String>getSignFromTaxDisk(@RequestBody SignDataReq signDataReq){
        return tokenService.getSignFromTaxDisk(signDataReq);
    }


    @RequestMapping(value ="/insertToken" , method = RequestMethod.POST)
    @LogT
    public JsonResult<String> insertToken(@RequestBody TkToken tkToken){
        return tokenService.insertToken(tkToken);
    }

    @RequestMapping(value ="/queryTokenErrorInfo" , method = RequestMethod.POST)
    @LogT
    public JsonResult<TkTokenRemarkLog>queryTokenErrorInfo(@RequestBody TkToken tkToken){

        return tokenService.queryTokenErrorInfo(tkToken);
    }

    @RequestMapping(value ="/heartbeat" , method = RequestMethod.GET)
    public JsonResult<String>heartbeat(){
        return new JsonResult<>();
    }

    @RequestMapping(value ="/selectErrorTokenList" , method = RequestMethod.POST)
    @LogT
    public JsonResult<String>selectErrorTokenList(@RequestBody TokenErrorReq tokenErrorReq){
        CrRpcResult crRpcResult = userClient.isSafe(tokenErrorReq);
        if(!checkUserSafe(crRpcResult)){
            return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
        }
        return tokenService.selectErrorTokenList(tokenErrorReq.getAccessKeyID(), tokenErrorReq.getPageId());
    }
    @RequestMapping(value ={"/cleanCookie", "/cleanLoginInfo"} , method = RequestMethod.POST)
    @LogT
    public JsonResult<String> cleanCookie(@RequestBody CookieReq cookieReq){
        CrRpcResult crRpcResult = userClient.isSafe(cookieReq);
        if(!checkUserSafe(crRpcResult)){
            return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
        }
        cookieReq.setUserCode(cookieReq.getAccessKeyID());
        String uuId = UUIDGenerator.generate();
        JsonResult<String> jsonResult = tokenService.cleanCookie(uuId, cookieReq);
        return jsonResult;
    }

    @RequestMapping(value ={"/cleanGroupCookie", "/cleanGroupInfo"} , method = RequestMethod.POST)
    @LogT
    public JsonResult<String> cleanGroupCookie(@RequestBody CookieReq cookieReq){
        String uuId = UUIDGenerator.generate();
        JsonResult<String> jsonResult = tokenService.cleanGroupCookie(uuId, cookieReq);
        return jsonResult;
    }

    @RequestMapping(value ="/queryTokenInfo")
    @LogT
    public JsonResult<String> queryTokenInfo(@RequestParam(value="taxno",required = true)String taxno,
                                             @RequestParam(value="userCode",required = true)String userCode,
                                             @RequestParam(value="optType",required = true)String optType){
        return tokenService.queryTokenInfo(optType, userCode, taxno);
    }

    @RequestMapping(value ="/selectTokenListByErrorCode")
    @LogT
    public List<TokenInfo> selectTokenListByErrorCode(@RequestParam(value="userCode",required = true)String userCode,
                                                      @RequestParam(value="errorCode",required = true)String errorCode){
        return tokenService.selectTokenListByErrorCode(userCode, errorCode);
    }

}
