package com.jkcredit.invoice.hub.service.apiUser;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jkcredit.invoice.hub.constant.CommonConstant;
import com.jkcredit.invoice.hub.enums.ApiResponseCodeEnum;
import com.jkcredit.invoice.hub.model.dto.userBalance.UserBalanceDto;
import com.jkcredit.invoice.hub.model.dto.userBalance.UserBalanceDtoApi;
import com.jkcredit.invoice.hub.model.po.user.UserPo;
import com.jkcredit.invoice.hub.service.base.BaseService;
import com.jkcredit.invoice.hub.service.user.UserService;
import com.jkcredit.invoice.hub.service.userBalance.UserBalanceService;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import com.jkcredit.invoice.hub.spi.rest.data.ApiRequestParam;
import com.jkcredit.invoice.hub.spi.rest.data.ApiResponseData;
import com.jkcredit.invoice.hub.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ArrayUtils;

/**
 * @description: 接口用户信息验证
 * @author: xusonglin
 * @create: 2020/1/15 22:51
 * @version: V1.0
 **/
@Slf4j
@Service
public class ApiUserServiceImpl extends BaseService implements ApiUserService {
    @Autowired
    UserService userService;
    @Autowired
    UserBalanceService userBalanceService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Integer validateUser(ApiRequestParam param) {
        Object object = redisTemplate.opsForValue().get(CommonConstant.INVOICE_HUB_USER_APPKEY + param.getAppKey());
        Boolean availableUser;
        String userId = "";
        if (object != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));
            if (!param.getAppSecret().equals(jsonObject.get("appSecret")) || jsonObject.get("status") == null || !jsonObject.get("status").equals("1")) {
                availableUser = validateUser(param.getAppKey(), param.getAppSecret(), userId);
            } else {
                userId = jsonObject.get("userId").toString();
                availableUser = true;
            }
        } else {
            availableUser = validateUser(param.getAppKey(), param.getAppSecret(), userId);
        }

        // 无效用户
        if (!availableUser) {
            return ApiResponseCodeEnum.CODE_1000.getValue();
        }
        if (!ArrayUtils.contains(CommonConstant.CAR_FREE_API_ARGS, param.getApi())) {
            return ApiResponseCodeEnum.CODE_1080.getValue();
        }
        if (param.getApi().equals(CommonConstant.WAY_BILL_START) || param.getApi().equals(CommonConstant.WAY_BILL_HISTORY_START)) {
            UserPo userPo = userService.getUserByAppKey(param.getAppKey());
            if (userPo.getBalance() == null || (CommonUtil.parseDouble(userPo.getBalance()) / CommonUtil.parseDouble(userPo.getPrice()) < CommonUtil.parseDouble(userPo.getPrice()))) {
                return ApiResponseCodeEnum.CODE_1090.getValue();
            }
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param.getData()));
        jsonObject.put("userId", userId);
        param.setData(jsonObject);
        return ApiResponseCodeEnum.CODE_200.getValue();
    }

    private Boolean validateUser(String appKey, String appSecret, String userId) {
        UserPo userPo = userService.getUserByAppKey(appKey);
        if (userPo == null) {
            return false;
        } else if (!userPo.getAppSecret().equals(appSecret)) {
            return false;
        } else {
            userId = userPo.getId().toString();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("appSecret", appSecret);
            jsonObject.put("userId", userId);
            jsonObject.put("status", userPo.getStatus().toString());
            redisTemplate.opsForValue().set(CommonConstant.INVOICE_HUB_USER_APPKEY + appKey, jsonObject);
            return true;
        }
    }

    @Override
    public ApiResponseData balanceQuery(JSONObject param) {
        try {
            UserBalanceDtoApi dto = userBalanceService.getUserBalanceApi(param.getLong("userId"));
            return ApiResponseData.success(ApiResponseCodeEnum.CODE_200.getValue(), JSON.toJSONString(dto));
        } catch (ServiceException se) {
            log.error("[-balanceQuery-] 错误信息：" + se.getMessage());
            throw new ServiceException(se.getMessage());
        }
    }
}
