package com.openapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.pay.util.SignatureUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsAgentApiAccount;
import com.hfkj.entity.BsAgentApiParam;
import com.hfkj.model.ResponseData;
import com.hfkj.openapi.model.request.RequestAmountModel;
import com.hfkj.openapi.model.response.ResponseAmountModel;
import com.hfkj.service.agent.BsAgentApiAccountService;
import com.hfkj.service.agent.BsAgentApiParamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping(value = "/account")
@Api(value = "账户管理")
public class BsAccountController {
    private static Logger log = LoggerFactory.getLogger(BsAccountController.class);
    @Resource
    private BsAgentApiParamService agentApiParamService;
    @Resource
    private BsAgentApiAccountService agentApiAccountService;

    @RequestMapping(value="/queryAmount",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询账户余额")
    public ResponseData queryAmount(@Validated @RequestBody RequestAmountModel body) {
        log.info("========= Start 查询账户余额 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        try {
            // 验证签名
            BsAgentApiParam apiParam = agentApiParamService.getParamByAppId(body.getAppId());
            if (!SignatureUtil.checkSign(body.getSign(), body, apiParam.getAppSecret())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_SIGN_ERR, "");
            }
            // 查询账户
            BsAgentApiAccount account = agentApiAccountService.getAccount(apiParam.getAgentId());
            if (account == null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到账户");
            }
            ResponseAmountModel response = new ResponseAmountModel();
            response.setAppId(body.getAppId());
            response.setAmount(account.getAmount());
            log.info("返回参数：" +response);
            return ResponseMsgUtil.success(response);

        } catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            return exception;
        } finally {
            log.info("========= END 查询账户余额 END ===========");
        }
    }

}
