package com.openapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.security.AESEncodeUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsAgentApiAccount;
import com.hfkj.entity.BsAgentApiLogWithBLOBs;
import com.hfkj.entity.BsAgentApiParam;
import com.hfkj.entity.BsAgentMer;
import com.hfkj.model.ResponseData;
import com.hfkj.openapi.model.request.*;
import com.hfkj.openapi.model.response.ResponseOrderDetailModel;
import com.hfkj.openapi.model.response.ResponseOrderPushModel;
import com.hfkj.openapi.model.response.ResponseQueryGasInfoModel;
import com.hfkj.openapi.service.ApiGasOrderService;
import com.hfkj.openapi.service.ApiGasService;
import com.hfkj.service.agent.BsAgentApiAccountService;
import com.hfkj.service.agent.BsAgentApiLogService;
import com.hfkj.service.agent.BsAgentApiParamService;
import com.hfkj.service.agent.BsAgentMerService;
import com.hfkj.sysenum.agent.AgentStatusEnum;
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 = "/gasOrder")
@Api(value = "油站管理")
public class BsGasOrderController {
    private static Logger log = LoggerFactory.getLogger(BsGasOrderController.class);
    @Resource
    private BsAgentApiParamService agentApiParamService;
    @Resource
    private ApiGasOrderService apiGasOrderService;
    @Resource
    private BsAgentApiAccountService agentApiAccountService;
    @Resource
    private BsAgentApiLogService agentApiLogService;

    @RequestMapping(value="/push",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "推送订单")
    public ResponseData push(@Validated @RequestBody RequestOrderPushModel body) {
        log.info("========= Start 推送订单 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        BsAgentApiLogWithBLOBs apiLog = new BsAgentApiLogWithBLOBs();
        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, "");
            }
            apiLog.setAppId(body.getAppId());
            apiLog.setRequestUrl("gasOrder/push");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            // 查询账户
            BsAgentApiAccount account = agentApiAccountService.getAccount(apiParam.getAgentId());
            if (account == null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未知的交易账户");
            }
            if (!account.getStatus().equals(AgentStatusEnum.status1.getCode())) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "交易账户已被禁用");
            }
            // 余额是否小于消费余额
            if (account.getAmount().compareTo(body.getRefuelingAmount()) == -1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "账户余额不足");
            }
            ResponseOrderPushModel response = apiGasOrderService.pushOrder(apiParam.getAgentId(), body);

            log.info("返回参数：" + JSONObject.toJSONString(response));
            apiLog.setResponseParam(JSONObject.toJSONString(response));

            return ResponseMsgUtil.success(response);

        } catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            apiLog.setErrorContent(JSONObject.toJSONString(exception));
            return exception;
        } finally {
            // 记录日志
            if (apiLog.getAppId() != null) {
                agentApiLogService.edit(apiLog);
            }
            log.info("========= END 推送订单 END ===========");
        }
    }

    @RequestMapping(value="/queryOrderDetail",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单详情")
    public ResponseData queryOrderDetail(@Validated @RequestBody RequestOrderDetailModel body) {
        log.info("========= Start 查询订单详情 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        BsAgentApiLogWithBLOBs apiLog = new BsAgentApiLogWithBLOBs();
        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, "");
            }
            apiLog.setAppId(body.getAppId());
            apiLog.setRequestUrl("gasOrder/queryOrderDetail");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            ResponseOrderDetailModel response = apiGasOrderService.queryOrderDetail(apiParam.getAgentId(),body);

            log.info("返回参数：" + JSONObject.toJSONString(response));
            apiLog.setResponseParam(JSONObject.toJSONString(response));

            return ResponseMsgUtil.success(response);

        } catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            apiLog.setErrorContent(JSONObject.toJSONString(exception));
            return exception;
        } finally {
            // 记录日志
            if (apiLog.getAppId() != null) {
                agentApiLogService.edit(apiLog);
            }
            log.info("========= END 查询订单详情 END ===========");
        }
    }

    @RequestMapping(value="/refund",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "退款申请")
    public ResponseData refund(@Validated @RequestBody RequestOrderRefundModel body) {
        log.info("========= Start 退款申请 Start ===========");
        log.info("请求参数：" + JSONObject.toJSONString(body));
        BsAgentApiLogWithBLOBs apiLog = new BsAgentApiLogWithBLOBs();
        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, "");
            }
            apiLog.setAppId(body.getAppId());
            apiLog.setRequestUrl("gasOrder/refund");
            apiLog.setRequestParam(JSONObject.toJSONString(body));

            String response = apiGasOrderService.refundOrder(apiParam.getAgentId(), body);

            log.info("返回参数：" + response);
            apiLog.setResponseParam(response);
            return ResponseMsgUtil.success(response);

        } catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            apiLog.setErrorContent(JSONObject.toJSONString(exception));
            return exception;
        } finally {
            // 记录日志
            if (apiLog.getAppId() != null) {
                agentApiLogService.edit(apiLog);
            }
            log.info("========= END 退款申请 END ===========");
        }
    }

}
