package com.v1.controller;

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.entity.*;
import com.hai.model.ResponseData;
import com.hai.service.*;
import com.v1.config.ToolConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @serviceName rechargeProductController.java
 * @author Sum1Dream
 * @version 1.0.0
 * @Description // 充值产品接口
 * @createTime 17:14 2022/6/9
 **/
@Controller
@RequestMapping(value = "/rechargeProduct")
@Api(value = "充值产品接口")
public class RechargeProductController {

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

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private SecConfigService secConfigService;

    @Resource
    private OutRechargeOrderService outRechargeOrderService;

    @Resource
    private ApiOrderRecordService apiOrderRecordService;

    @Resource
    private ApiProductService apiProductService;

    @Resource
    private ApiOpenService apiOpenService;

    @RequestMapping(value = "/getRechargeProduct", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取充值产品")
    public ResponseData getRechargeProduct(@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("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

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

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

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "错误商户，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

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

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

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

            return ResponseMsgUtil.success(apiMerchantsService.getMerchProduct(apiMerchants.getId() , object.getInteger("rechargeType")));

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

    @RequestMapping(value = "/checkAccountBalance", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询帐户余额")
    public ResponseData checkAccountBalance(@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("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

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

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

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "商户号错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

            Map<String , Object> map = new HashMap<>();
            map.put("apiKey" , object.getString("apiKey"));
            map.put("timetable" , object.getString("timetable"));
            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);
            }

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

            return ResponseMsgUtil.success(apiMerchants.getAmounts());

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

    @RequestMapping(value = "/queryOrderResult", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单结果")
    public ResponseData queryOrderResult(@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("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

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

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

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "商户号错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

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

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

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

            ApiOrderRecord apiOrderRecord = apiOrderRecordService.queryOrderResult(map);

            OutRechargeOrder rechargeOrder = outRechargeOrderService.findByOrderNo(apiOrderRecord.getOrderNo());

            JSONObject returnObject = new JSONObject();
            returnObject.put("sourceOrderNo" , apiOrderRecord.getSourceOrderNo());
            returnObject.put("callbackStatus" , apiOrderRecord.getStatus());
            returnObject.put("apiConfigProductId" , apiOrderRecord.getGoodsId());
            returnObject.put("type" , rechargeOrder.getType());
            returnObject.put("operatorName" , rechargeOrder.getOperatorName());
            returnObject.put("rechargeType" , rechargeOrder.getRechargeType());
            returnObject.put("rechargeContent" , rechargeOrder.getRechargeContent());
            returnObject.put("rechargePrice" , rechargeOrder.getRechargePrice());
            returnObject.put("payPrice" , rechargeOrder.getPayPrice());
            returnObject.put("createTimed" , rechargeOrder.getCreateTimed());
            returnObject.put("payStatus" , rechargeOrder.getPayStatus());
            returnObject.put("rechargeStatus" , rechargeOrder.getRechargeStatus());


            return ResponseMsgUtil.success(returnObject);

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


    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "充值预下单")
    public ResponseData createOrder(@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("createOrder error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

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

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

            if (apiMerchants == null) {
                log.error("createOrder error!", "商户错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

            Map<String, Object> productMap = new HashMap<>();

            productMap.put("id" , object.getString("apiConfigProductId"));
            productMap.put("merchantsId" , apiMerchants.getId());

            ApiProductConfig  apiProductConfig = apiProductService.findMchProduct(productMap);

            if (apiProductConfig == null) {
                log.error("createOrder error!", " 商品错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.PRODUCT_ERROR);
            }

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

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

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

            apiOpenService.createOrder(object , apiMerchants , apiProductConfig);
            return ResponseMsgUtil.success("下单成功");

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


}
