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.utils.ResponseMsgUtil;
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.*;
import com.hfkj.openapi.service.ApiGasService;
import com.hfkj.service.agent.BsAgentApiLogService;
import com.hfkj.service.agent.BsAgentApiParamService;
import com.hfkj.service.agent.BsAgentMerService;
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;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping(value = "/gas")
@Api(value = "油站管理")
public class BsGasController {
    private static Logger log = LoggerFactory.getLogger(BsGasController.class);
    @Resource
    private BsAgentApiParamService agentApiParamService;
    @Resource
    private BsAgentMerService agentMerService;
    @Resource
    private ApiGasService apiGasService;

    @RequestMapping(value="/queryList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分页获取（全量）油站信息")
    public ResponseData queryList(@Validated @RequestBody RequestQueryGasListModel 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, "");
            }
            PageHelper.startPage(body.getPageNum(), body.getPageSize());
            PageInfo<ResponseQueryGasInfoModel> pageInfo = new PageInfo<>(agentMerService.getMerNoList(apiParam.getAgentId()));
            for (int i = 0; i < pageInfo.getList().size();i++) {
                pageInfo.getList().set(i, apiGasService.queryGasInfo(apiParam.getAgentId(),pageInfo.getList().get(i).getGasNo()));
            }
            Map<String,Object> response = new LinkedHashMap<>();
            response.put("totalCount", pageInfo.getTotal());
            response.put("totalPageNum", pageInfo.getPages());
            response.put("currPageIndex", pageInfo.getPageNum());
            response.put("gasInfoList", pageInfo.getList());
            log.info("返回参数：" + JSONObject.toJSONString(response));
            return ResponseMsgUtil.success(response);

        } catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            return exception;
        } finally {
            log.info("========= END 分页获取（全量）油站信息 END ===========");
        }
    }

    @RequestMapping(value="/queryGasInfoByGasNo",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取油站信息")
    public ResponseData queryGasInfoByGasNo(@Validated @RequestBody RequestQueryGasInfoModel 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, "");
            }
            // 查询油站
            BsAgentMer agentMer = agentMerService.getDetailByAgent(apiParam.getAgentId(), body.getGasNo());
            if (agentMer == null) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未查到加油站信息");
            }
            ResponseQueryGasInfoModel response = apiGasService.queryGasInfo(apiParam.getAgentId(), body.getGasNo());
            log.info("返回参数：" + JSONObject.toJSONString(response));
            return ResponseMsgUtil.success(response);

        }  catch (Exception e) {
            log.info("出现异常：", e);
            // 异常内容
            ResponseData exception = ResponseMsgUtil.exception(e);
            return exception;
        } finally {
            log.info("========= END 获取油站信息 END ===========");
        }
    }

}
