package com.v1.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongConfig;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.dao.HighGasOrderPushMapper;
import com.hai.entity.ApiMerchants;
import com.hai.entity.HighGasOrderPush;
import com.hai.entity.HighUser;
import com.hai.enum_type.OrderPushType;
import com.hai.model.ResponseData;
import com.hai.service.ApiMerchantsService;
import com.hai.service.HighOpenApiService;
import com.hai.service.HighUserService;
import com.hai.service.SecConfigService;
import com.v1.config.ToolConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/gzSinopec")
@Api(value = "贵州中石化")
public class  GzSinopecController {

    private static Logger log = LoggerFactory.getLogger(GzSinopecController.class);

    @Resource
    private HighOpenApiService highOpenApiService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private HighGasOrderPushMapper highGasOrderPushMapper;

    @Resource
    private SecConfigService secConfigService;

    @RequestMapping(value = "/getGzSinopecList", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取贵州中石化电子卡券")
    public ResponseData getGzSinopecList(@RequestBody JSONObject object , HttpServletRequest request) {
        try {

            String ip = "";
            // 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for
            if (request.getHeader("x-forwarded-for") == null) {
                ip = request.getRemoteAddr();
            } else {
                ip = request.getHeader("x-forwarded-for");
            }

            if (!secConfigService.isConfig("IP_WHITE", ip)) {
                log.error("getGuizhouSinopec error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "非法ip地址，请联系管理人员！");
            }


            if (StringUtils.isBlank(object.getString("apiKey")) ||
                    StringUtils.isBlank(object.getString("timetable")) ||
                    StringUtils.isBlank(object.getString("merchId")) ||
                    StringUtils.isBlank(object.getString("sign"))
            ) {
                log.error("getRechargeProduct error!", "请求参数校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR);
            }

            Map<String , Object> map = new HashMap<>();
            map.put("timetable" , object.getString("timetable"));
            map.put("apiKey" , object.getString("apiKey"));
            map.put("merchId" , object.getString("merchId"));

            if (!secConfigService.isSignVerify(map , object.getString("sign"))) {
                log.error("getRechargeProduct error!", "签名校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SIGN_VERIFY);
            }

            ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "错误商户，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }
            if (!secConfigService.isConfig("GZ_SINOPEC_CONFIG" , object.getString("merchId"))) {
                log.error("getAllCities error!", "当前帐户无权限！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOT_AUTHORIZED, "当前帐户无权限！");
            }

            if (!ToolConfig.timetableCheck(15L , object.getLong("timetable"))) {
                log.error("getRechargeProduct error!", "请求时间超过15分钟！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.TIME_OUT);
            }

            // 查询电子卡券类型
            JSONObject corpCouTypes = HuiLianTongConfig.getHltFuelCoupList();
            if (!corpCouTypes.getString("respCode").equals("0000")) {
                log.error("HighCouponController -> insertCoupon() error!","获取电子卡券列表失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "获取电子卡券列表失败");
            }
            // 参数解密
            JSONObject resolveResponseData = HuiLianTongUnionCardConfig.resolveResponse(corpCouTypes.getString("data"));

            return ResponseMsgUtil.success(resolveResponseData);
        } catch (Exception e) {
            log.error("HighCouponController -> getGuizhouSinopec() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/couJointDist", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "商户派发电子券")
    public ResponseData couJointDist(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

            String ip = "";
            // 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for
            if (request.getHeader("x-forwarded-for") == null) {
                ip = request.getRemoteAddr();
            } else {
                ip = request.getHeader("x-forwarded-for");
            }

            if (!secConfigService.isConfig("IP_WHITE", ip)) {
                log.error("couJointDist error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "非法ip地址，请联系管理人员！");
            }

            if (StringUtils.isBlank(object.getString("apiKey")) ||
                    StringUtils.isBlank(object.getString("orderNo")) ||
                    StringUtils.isBlank(object.getString("count")) ||
                    StringUtils.isBlank(object.getString("couTypeCode")) ||
                    StringUtils.isBlank(object.getString("phone")) ||
                    StringUtils.isBlank(object.getString("timetable")) ||
                    StringUtils.isBlank(object.getString("merchId")) ||
                    StringUtils.isBlank(object.getString("sign"))
            ) {
                log.error("getRechargeProduct error!", "请求参数校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR);
            }

            Map<String , Object> map = new HashMap<>();
            map.put("timetable" , object.getString("timetable"));
            map.put("apiKey" , object.getString("apiKey"));
            map.put("orderNo" , object.getString("orderNo"));
            map.put("count" , object.getString("count"));
            map.put("couTypeCode" , object.getString("couTypeCode"));
            map.put("phone" , object.getString("phone"));
            map.put("merchId" , object.getString("merchId"));

            if (!secConfigService.isSignVerify(map , object.getString("sign"))) {
                log.error("getRechargeProduct error!", "签名校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SIGN_VERIFY);
            }

            ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "错误商户，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }
            if (!secConfigService.isConfig("GZ_SINOPEC_CONFIG" , object.getString("merchId"))) {
                log.error("getAllCities error!", "当前帐户无权限！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOT_AUTHORIZED, "当前帐户无权限！");
            }

            if (!ToolConfig.timetableCheck(15L , object.getLong("timetable"))) {
                log.error("getRechargeProduct error!", "请求时间超过15分钟！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.TIME_OUT);
            }

            if (object.getInteger("count") > 5) {
                log.error("getRechargeProduct error!", "下单数量限制5张！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , "下单数量限制5张！");
            }

            // 下单请求
            JSONObject rechargeObject = HuiLianTongConfig.recharge(object.getString("orderNo"),
                    object.getInteger("count"),
                    object.getString("couTypeCode"),
                    object.getString("phone"));
            if (!rechargeObject.getString("respCode").equals("0000")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "下单失败");
            }
            JSONObject response = HuiLianTongUnionCardConfig.resolveResponse(rechargeObject.getString("data"));

            // 购买卡券
            JSONObject returnParam = HuiLianTongConfig.costRechargeOrder(response.getJSONObject("data").getString("rechargeOrderId"));

            if (returnParam != null && returnParam.getString("respCode").equals("0000")) {
                // 解密
                JSONObject jsonObject = HuiLianTongUnionCardConfig.resolveResponse(returnParam.getString("data"));
                JSONArray dataArray = JSONObject.parseObject(jsonObject.getString("data"), JSONArray.class);

                // 推送记录
                HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
                highGasOrderPush.setType(OrderPushType.type6.getType());
                highGasOrderPush.setOrderNo(object.getString("orderNo"));
                highGasOrderPush.setCreateTime(new Date());
                highGasOrderPush.setCode(returnParam.getString("respCode"));
                highGasOrderPush.setRequestContent(object.toJSONString());
                highGasOrderPush.setReturnContent(dataArray.toJSONString());
                highGasOrderPushMapper.insert(highGasOrderPush);

                return ResponseMsgUtil.success(dataArray);
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "下单失败");
            }

        } catch (Exception e) {
            log.error("HighOpenApiController -> couJointDist() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getPayOrderByCouNo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询核销状态")
    public ResponseData getPayOrderByCouNo(@RequestBody JSONObject object , HttpServletRequest request) {
        try {

            String ip = "";
            // 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for
            if (request.getHeader("x-forwarded-for") == null) {
                ip = request.getRemoteAddr();
            } else {
                ip = request.getHeader("x-forwarded-for");
            }

            if (!secConfigService.isConfig("IP_WHITE", ip)) {
                log.error("getGuizhouSinopec error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "非法ip地址，请联系管理人员！");
            }


            if (StringUtils.isBlank(object.getString("apiKey")) ||
                    StringUtils.isBlank(object.getString("timetable")) ||
                    StringUtils.isBlank(object.getString("merchId")) ||
                    StringUtils.isBlank(object.getString("couNo")) ||
                    StringUtils.isBlank(object.getString("sign"))
            ) {
                log.error("getRechargeProduct error!", "请求参数校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR);
            }

            Map<String , Object> map = new HashMap<>();
            map.put("timetable" , object.getString("timetable"));
            map.put("apiKey" , object.getString("apiKey"));
            map.put("couNo" , object.getString("couNo"));
            map.put("merchId" , object.getString("merchId"));

            if (!secConfigService.isSignVerify(map , object.getString("sign"))) {
                log.error("getRechargeProduct error!", "签名校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SIGN_VERIFY);
            }

            ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "错误商户，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }
            if (!secConfigService.isConfig("GZ_SINOPEC_CONFIG" , object.getString("merchId"))) {
                log.error("getAllCities error!", "当前帐户无权限！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOT_AUTHORIZED, "当前帐户无权限！");
            }

            if (!ToolConfig.timetableCheck(15L , object.getLong("timetable"))) {
                log.error("getRechargeProduct error!", "请求时间超过15分钟！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.TIME_OUT);
            }

            JSONObject jsonObject = HuiLianTongConfig.getPayOrderByCouNo(object.getString("couNo"));
            if (jsonObject.getString("respCode").equals("0000")) {
                JSONObject data = HuiLianTongUnionCardConfig.resolveResponse(jsonObject.getString("data"));

                return ResponseMsgUtil.success(data);
            } else {
                log.error("getRechargeProduct error!", "查询失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , "查询失败");
            }

        } catch (Exception e) {
            log.error("HighCouponController -> getGuizhouSinopec() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
