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

    @Override
    public Integer validateUser(ApiRequestParam param) {
        // 无效用户
        UserPo userPo = userService.getUserByAppKey(param.getAppKey());

        if (userPo == null) {
            return ApiResponseCodeEnum.CODE_1000.getValue();
        } else if (!userPo.getAppSecret().equals(param.getAppSecret())) {
            return ApiResponseCodeEnum.CODE_1000.getValue();
        } else if (!ArrayUtils.contains(CommonConstant.CAR_FREE_API_ARGS, param.getApi())) {
            return ApiResponseCodeEnum.CODE_1080.getValue();
        } else if (CommonUtil.parseDouble(userPo.getBalance()) / CommonUtil.parseDouble(userPo.getPrice()) < CommonUtil.parseDouble(userPo.getPrice())) {
            return ApiResponseCodeEnum.CODE_1090.getValue();
        } else {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param.getData()));
            jsonObject.put("userId", userPo.getId());
            param.setData(jsonObject);
            return ApiResponseCodeEnum.CODE_200.getValue();
        }
    }

    @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());
        }
    }
}
