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.config.WxOrderConfig;
import com.hai.entity.ApiMerchants;
import com.hai.entity.ApiOrder;
import com.hai.entity.ApiProductConfig;
import com.hai.entity.HighOrder;
import com.hai.model.OrderRefundModel;
import com.hai.model.ResponseData;
import com.hai.openApi.service.ApiOrderService;
import com.hai.order.model.RefundPriceModel;
import com.hai.order.service.OrderService;
import com.hai.order.type.OrderProductType;
import com.hai.order.type.OrderRefundOpUserType;
import com.hai.service.*;
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.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
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.servlet.http.HttpServletRequest;
import javax.sound.midi.Soundbank;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/order")
@Api(value = "订单业务")
public class orderController {

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

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private SecConfigService secConfigService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Resource
    private OrderService orderService;

    @Resource
    private ApiIpAddressService apiIpAddressService;

    @Resource
    private ApiOrderService apiOrderService;

    @Resource
    private HighOrderService highOrderService;

    @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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

            if (
                    StringUtils.isBlank(object.getString("productType")) ||
                    StringUtils.isBlank(object.getString("timetable")) ||
                    StringUtils.isBlank(object.getString("orderNo")) ||
                    StringUtils.isBlank(object.getString("sign")) ||
                    StringUtils.isBlank(object.getString("content")) ||
                    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("getRechargeProduct error!", "帐户错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

            if (!secConfigService.isConfig(OrderProductType.getDataByType(object.getInteger("productType")).getApiCode(), object.getString("merchId"))) {
                log.error("getAllCities error!", "当前帐户无权限查询！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOT_AUTHORIZED);
            }

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

            if (object.getInteger("productType").equals(OrderProductType.PRODUCT_TYPE6.getNumber())) {
                JSONObject dataObject = JSONObject.parseObject(object.getString("content"));
                if (dataObject.getBigDecimal("refuelPrice") == null
                        || StringUtils.isBlank(dataObject.getString("gasOilNo"))
                        || StringUtils.isBlank(dataObject.getString("gasGunNo"))
                        || StringUtils.isBlank(dataObject.getString("storeCode"))
                ) {
                    log.error("OrderController -> create() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未填写加油信息；加油金额、油号、抢号");
                }
            }
            JSONObject dataObject = JSONObject.parseObject(object.getString("content"));

            if (object.getInteger("productType").equals(OrderProductType.PRODUCT_TYPE9.getNumber()) || object.getInteger("productType").equals(OrderProductType.PRODUCT_TYPE3.getNumber())) {
                if (StringUtils.isBlank(dataObject.getString("productId"))
                        || StringUtils.isBlank(dataObject.getString("mobile"))
                ) {
                    log.error("OrderController -> create() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未填写产品id，充值号码");
                }
            }

            if (object.getInteger("productType").equals(OrderProductType.PRODUCT_TYPE1.getNumber())) {
                if (StringUtils.isBlank(dataObject.getString("customerMobile"))
                ) {
                    log.error("OrderController -> create() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未填写下单手机号");
                }
            }

            if (object.getInteger("productType").equals(OrderProductType.PRODUCT_TYPE2.getNumber())) {
                if (dataObject.getJSONArray("data") == null
                        || StringUtils.isBlank(dataObject.getString("customerMobile"))
                        || StringUtils.isBlank(dataObject.getString("storeCode"))
                        || dataObject.getInteger("eatType") == null
                ) {
                    log.error("OrderController -> create() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未填写下单手机号，就餐方式，下单信息，门店编码");
                }
            }
            if (object.getInteger("productType").equals(OrderProductType.PRODUCT_TYPE13.getNumber())) {
                if (dataObject.getJSONArray("data") == null
                        || StringUtils.isBlank(dataObject.getString("couponCode"))
                        || StringUtils.isBlank(dataObject.getString("receiverPhone"))
                        || dataObject.getInteger("receiverCount") == null
                ) {
                    log.error("OrderController -> create() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未填写卡券编码，手机号，购买数量");
                }
            }

            return ResponseMsgUtil.success(apiOrderService.createOrder(object));

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

    @RequestMapping(value = "/orderPay", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "订单支付")
    public ResponseData orderPay(@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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

            if (
                            StringUtils.isBlank(object.getString("mchOrderNo")) ||
                            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("getRechargeProduct error!", "帐户错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

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

            ApiOrder apiOrder = apiOrderService.findByOrderNo(object.getString("mchOrderNo") , null);

            if (apiOrder.getStatus() != 1) {
                log.error("createOrder error!", "订单状态错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , "订单状态错误");
            }

            object.put("orderNo" , apiOrder.getOrderNo());

            ApiOrder order = apiOrderService.payOrder(object);

            return ResponseMsgUtil.success(order);

        } catch (Exception e) {
            log.error("HighOpenApiController --> createOrder() error!", e);
            return ResponseMsgUtil.exception(e);
        } finally {
            // 删除key，释放锁
            redisTemplate.delete( "apiMerchant" + object.getString("merchId"));
        }
    }

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

            if (
                            StringUtils.isBlank(object.getString("mchOrderNo")) ||
                            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("getRechargeProduct error!", "帐户错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

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

            return ResponseMsgUtil.success(apiOrderService.findByOrderNo(object.getString("mchOrderNo") , null));

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

    @RequestMapping(value = "/refund", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "退款")
    public ResponseData refund(@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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

            if (
                    StringUtils.isBlank(object.getString("mchOrderNo")) ||
                            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("getRechargeProduct error!", "帐户错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

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

            ApiOrder apiOrder = apiOrderService.findByOrderNo(object.getString("mchOrderNo") , null);

            HighOrder order = highOrderService.getOrderByOrderNo(apiOrder.getOrderNo());


            if (order.getOrderStatus() != 2) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "订单状态错误");
            }

            orderService.refundOrder(order, "商户退款退款", OrderRefundOpUserType.TYPE1,
                    null,
                    "系统自动退款");

            return ResponseMsgUtil.success("退款成功");

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



    @RequestMapping(value = "/externalOrderRefund", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "对外订单退款接口")
    public ResponseData externalOrderRefund(@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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

            if (
                            StringUtils.isBlank(object.getString("paySerialNo")) ||
                            StringUtils.isBlank(object.getString("wxMchId")) ||
                            StringUtils.isBlank(object.getString("refundPrice")) ||
                            StringUtils.isBlank(object.getString("payRealPrice")) ||
                            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("getRechargeProduct error!", "帐户错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

            Map<String , Object> map = new HashMap<>();
            map.put("paySerialNo" , object.getString("paySerialNo"));
            map.put("wxMchId" , object.getString("wxMchId"));
            map.put("payRealPrice" , object.getString("payRealPrice"));
            map.put("refundPrice" , object.getString("refundPrice"));
            map.put("apiKey" , apiMerchants.getApiKey());
            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);
            }

            return ResponseMsgUtil.success(WxOrderConfig.orderToRefund(object.getString("paySerialNo"),object.getBigDecimal("payRealPrice"), object.getString("wxMchId"), object.getBigDecimal("refundPrice")));

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

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "对外订单退款接口")
    public ResponseData test() {
        try {

            System.out.println("话费请求订单=================================");

            Thread.currentThread().sleep(30000);

            return ResponseMsgUtil.success("请求成功！");

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


}
