package com.order.controller.notify;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.OrderUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsOrderMeituan;
import com.hfkj.entity.BsOrderRefund;
import com.hfkj.meituan.MeiTuanService;
import com.hfkj.service.goods.BsOrderMeiTuanService;
import com.hfkj.service.order.BsOrderRefundService;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.sysenum.order.OrderChildStatusEnum;
import com.meituan.sqt.utils.EncryptUtil;
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.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 java.util.Date;
import java.util.Objects;

@Controller
@RequestMapping(value = "/meiTuan")
@Api(value = "美团通知")
public class MeiTuanController {

    @Resource
    private BsOrderMeiTuanService bsOrderMeiTuanService;
    @Resource
    private BsOrderRefundService orderRefundService;
    @Resource
    private BsOrderService orderService;

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

    @RequestMapping(value = "/placeOrder", method = RequestMethod.POST)
    @ApiOperation(value = "下单")
    @ResponseBody
    public Object placeOrder(@RequestBody JSONObject reqBodyStr) {
        try {
            log.info("============回调任务Start=============");
            String accessKey = reqBodyStr.getString("accessKey");
            String content = reqBodyStr.getString("content");
            log.info("美团-回调参数: {}", reqBodyStr);
            if (accessKey == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "accessKey错误");
            }

            if (!Objects.equals(accessKey, CommonSysConst.getSysConfig().getMtAccessKey())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "accessKey错误");
            }

            if (content == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "content错误");
            }


            JSONObject jsonObject = JSONObject.parseObject(EncryptUtil.aesDecrypt(content, CommonSysConst.getSysConfig().getMtSecretKey()));;
            log.info("美团-解密参数: {}", jsonObject);
            // 下单
            if (Objects.equals(jsonObject.getString("method"), "trade.third.pay")) {
                // 创建美团订单
                BsOrderMeituan bsOrderMeituan = bsOrderMeiTuanService.findOrderMeiTuanByTradeNo(jsonObject.getString("tradeNo"));
                JSONObject data = new JSONObject();
                JSONObject object = new JSONObject();
                String thirdTradeNo;

                if (bsOrderMeituan == null) {
                    thirdTradeNo = OrderUtil.generateMeiTuanOrderNo();
                    // 组装数据
                    BsOrderMeituan orderMeiTuan = new BsOrderMeituan();
                    orderMeiTuan.setPlatformCode(jsonObject.getString("platformCode"));
                    orderMeiTuan.setThirdTradeNo(thirdTradeNo);
                    orderMeiTuan.setCreateTime(new Date());
                    orderMeiTuan.setUpdateTime(new Date());
                    orderMeiTuan.setTraceId(jsonObject.getString("traceId"));
                    orderMeiTuan.setEntId(jsonObject.getLong("entId"));
                    orderMeiTuan.setTradeNo(jsonObject.getString("tradeNo"));
                    orderMeiTuan.setSqtBizOrderId(jsonObject.getString("sqtBizOrderId"));
                    orderMeiTuan.setTradeAmount(jsonObject.getBigDecimal("tradeAmount"));
                    orderMeiTuan.setEntPayAmount(jsonObject.getBigDecimal("entPayAmount"));
                    orderMeiTuan.setBusinessDiscountPayAmount(jsonObject.getBigDecimal("businessDiscountPayAmount"));
                    orderMeiTuan.setServiceFeeAmount(jsonObject.getBigDecimal("serviceFeeAmount"));
                    orderMeiTuan.setGoodsName(jsonObject.getString("goodsName"));
                    orderMeiTuan.setTradeExpiringTime(jsonObject.getDate("tradeExpiringTime"));
                    orderMeiTuan.setNotifyUrl(jsonObject.getString("notifyUrl"));
                    orderMeiTuan.setReturnUrl(jsonObject.getString("returnUrl"));
                    orderMeiTuan.setFirstBusinessType(jsonObject.getString("firstBusinessType"));
                    orderMeiTuan.setSecondBusinessType(jsonObject.getString("secondBusinessType"));
                    orderMeiTuan.setStaffInfo(jsonObject.getString("staffInfo"));
                    orderMeiTuan.setStatus(OrderChildStatusEnum.status1.getCode());
                    bsOrderMeiTuanService.create(orderMeiTuan);

                } else {
                    thirdTradeNo = bsOrderMeituan.getThirdTradeNo();
                }

                JSONObject staffInfo = jsonObject.getJSONObject("staffInfo");

                object.put("thirdTradeNo", thirdTradeNo);
                object.put("thirdPayUrl", "https://phgcs.dctpay.com/cweb/#/pages/meiTuanPay/index?tradeNo=" + jsonObject.getString("tradeNo") + "&goodsName=" +
                        jsonObject.getString("goodsName") +
                        "&tradeAmount=" + jsonObject.getString("tradeAmount") +
                        "&outSidePhone=" + staffInfo.getString("staffPhone")
                );
                log.info("美团下单-参数: {}", object);
                data.put("status", 0);
                data.put("msg", "成功");
                data.put("data",  EncryptUtil.aesEncrypt(object.toJSONString() , CommonSysConst.getSysConfig().getMtSecretKey()));
                log.info("============回调任务End=============");
                return data;

            }
            // 退款
            if (Objects.equals(jsonObject.getString("method"), "trade.third.refund")) {

                BsOrderRefund orderRefund = orderRefundService.meiTuanRefund(
                        jsonObject.getString("tradeRefundNo") ,
                        jsonObject.getString("tradeNo") ,
                        jsonObject.getBigDecimal("refundAmount") ,
                        "美团退款"
                        );
                // 美团退款订单
                JSONObject object = new JSONObject();
                object.put("thirdRefundNo" , orderRefund.getRefundOrderNo());
                log.info("美团关闭订单-参数: {}", object);
                JSONObject data = new JSONObject();
                data.put("status", 0);
                data.put("msg", "成功");
                data.put("data",  EncryptUtil.aesEncrypt(object.toJSONString() , CommonSysConst.getSysConfig().getMtSecretKey()));
                log.info("============回调任务End=============");
                return data;

            }
            // 交易关单
            if (Objects.equals(jsonObject.getString("method"), "trade.third.pay.close")) {
                BsOrderMeituan orderMeiTuan = bsOrderMeiTuanService.findOrderMeiTuanByTradeNo(jsonObject.getString("tradeNo"));

                if (orderMeiTuan != null) {
                    if (orderMeiTuan.getStatus() == OrderChildStatusEnum.status1.getCode() || orderMeiTuan.getStatus() == OrderChildStatusEnum.status5.getCode()) {

                        if (orderMeiTuan.getOrderNo() == null) {
                            orderMeiTuan.setCancelTime(new Date());
                            orderMeiTuan.setStatus(OrderChildStatusEnum.status5.getCode());
                            bsOrderMeiTuanService.update(orderMeiTuan);
                        } else {
                            orderService.cancel(orderMeiTuan.getOrderNo(), false);
                        }


                        // 美团查询订单
                        JSONObject object = new JSONObject();
                        object.put("tradeNo" , orderMeiTuan.getTradeNo());
                        object.put("thirdTradeNo" , orderMeiTuan.getThirdTradeNo());
                        log.info("美团关闭订单-参数: {}", object);
                        JSONObject data = new JSONObject();
                        data.put("status", 0);
                        data.put("msg", "成功");
                        data.put("data",  EncryptUtil.aesEncrypt(object.toJSONString() , CommonSysConst.getSysConfig().getMtSecretKey()));
                        log.info("============回调任务End=============");
                        return data;
                    }
                }

                return null;
            }
            if (Objects.equals(jsonObject.getString("method"), "trade.third.pay.query")) {
                // 美团查询订单
                JSONObject object = new JSONObject();
                BsOrderMeituan orderMeiTuan = bsOrderMeiTuanService.findOrderMeiTuanByTradeNo(jsonObject.getString("tradeNo"));
                object.put("tradeNo" , jsonObject.getString("tradeNo"));
                object.put("thirdTradeNo" , orderMeiTuan.getThirdTradeNo());

                if (orderMeiTuan.getPayTime() == null) {
                    object.put("tradeTime" , "1970-01-01 00:00:00");
                } else {
                    object.put("tradeTime" , orderMeiTuan.getPayTime());
                }
                object.put("tradeAmount" , orderMeiTuan.getTradeAmount());
                object.put("payStatus" , MeiTuanService.payStatus(orderMeiTuan.getStatus()));
                log.info("美团查询订单-参数: {}", object);
                JSONObject data = new JSONObject();
                data.put("status", 0);
                data.put("msg", "成功");
                data.put("data",  EncryptUtil.aesEncrypt(object.toJSONString() , CommonSysConst.getSysConfig().getMtSecretKey()));
                log.info("============回调任务End=============");
                return data;
            }

            return null;

        } catch (Exception e) {
            log.error("WechatPayController --> wechatNotify() error!", e);
            return  e;
        }
    }
}
