package com.cweb.controller.pay;

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.security.AESEncodeUtil;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonSysConst;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.config.UnionPayConfig;
import com.hai.config.WxOrderConfig;
import com.hai.dao.HighGasOrderRefundMapper;
import com.hai.entity.HighChildOrder;
import com.hai.entity.HighGasOrderRefund;
import com.hai.entity.HighOrder;
import com.hai.enum_type.OrderPayTypeEnum;
import com.hai.model.OrderRefundModel;
import com.hai.model.ResponseData;
import com.hai.service.HighOilCardService;
import com.hai.service.HighOrderService;
import com.hai.service.HighUserService;
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 javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.security.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/tuanyou")
@Api(value = "团油回调")
public class TuanYouController {

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

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighGasOrderRefundMapper highGasOrderRefundMapper;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighOilCardService oilCardService;

    @RequestMapping(value = "/orderPaymentNotify", method = RequestMethod.POST)
    @ApiOperation(value = "订单支付回调")
    public void orderPaymentNotify(HttpServletRequest request, HttpServletResponse response) {
        try {


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


    @RequestMapping(value = "/orderRefundNotify", method = RequestMethod.POST)
    @ApiOperation(value = "订单退款回调")
    @ResponseBody
    public void orderRefundNotify(@RequestBody String reqBodyStr,HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info(reqBodyStr);
            HighGasOrderRefund highGasOrderRefund = new HighGasOrderRefund();
            highGasOrderRefund.setCreateTime(new Date());
            highGasOrderRefund.setReturnContent(reqBodyStr);
            highGasOrderRefundMapper.insert(highGasOrderRefund);

            JSONObject dataObject = JSONObject.parseObject(reqBodyStr, JSONObject.class);
            String dataStr = AESEncodeUtil.aesDecryptByBytes(AESEncodeUtil.base64Decode(dataObject.getString("data")), CommonSysConst.getSysConfig().getTuanYouAppSecret());
            JSONObject object = JSONObject.parseObject(dataStr);

            // 查询订单
            HighOrder order = highOrderService.getOrderByOrderNo(object.getString("thirdOrderNo"));

            // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消   6.退款中   7.拒绝退款
            if (order != null) {
                if (order.getOrderStatus() == 2 || order.getOrderStatus() == 3 || order.getOrderStatus() == 6 || order.getOrderStatus() == 7) {
                    // 退单结果 true:成功  false:失败
                    if (object.getBoolean("refundResult") == true && order != null) {

                        if (order.getPayType() == 2) {
                            OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(order.getPaySerialNo(), order.getPayRealPrice(), order.getPayRealPrice());
                            if(orderRefundModel.getResult_code().equals("SUCCESS")) {
                                order.setOrderStatus(4);
                                order.setRefundTime(new Date());
                                order.setRefundPrice(order.getPayRealPrice());
                                highOrderService.updateOrderDetail(order);
                            }
                        } else if (order.getPayType() == 3){
                            String remark = "订单" + order.getOrderNo() + "退款，退还积分：" +  order.getPayGold();
                            // 积分退款
                            highUserService.goldHandle(order.getMemId(), order.getPayGold(),1, 3, order.getId() , remark);
                            order.setOrderStatus(4);
                            order.setRefundTime(new Date());
                            order.setRefundPrice(order.getPayRealPrice());
                            highOrderService.updateOrderDetail(order);

                        } else if (order.getPayType() == 4) {
                            String refundOrderNo = String.valueOf(System.currentTimeMillis());
                            JSONObject refund = HuiLianTongUnionCardConfig.refund(refundOrderNo, order.getPaySerialNo());
                            if(!refund.getString("respCode").equals("0000")) {
                                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR,refund.getString("respMessage"));
                            }
                            JSONObject consumptionResult = HuiLianTongUnionCardConfig.resolveResponse(refund.getString("data"));
                            if (consumptionResult.getBoolean("success") != true) {
                                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "交易失败!"+consumptionResult.getString("message"));
                            }
                            order.setOrderStatus(4);
                            order.setRefundTime(new Date());
                            order.setRefundPrice(order.getPayRealPrice());
                            highOrderService.updateOrderDetail(order);
                        } else if (order.getPayType() == 5) {

                            Calendar startTime = Calendar.getInstance();
                            startTime.set(Calendar.HOUR_OF_DAY, 00);
                            startTime.set(Calendar.MINUTE, 00);
                            startTime.set(Calendar.SECOND, 00);

                            Calendar endTime = Calendar.getInstance();
                            startTime.set(Calendar.HOUR_OF_DAY, 23);
                            startTime.set(Calendar.MINUTE, 59);
                            startTime.set(Calendar.SECOND, 59);

                            // 订单是否处于当日的订单
                            if (DateUtil.isEffectiveDate(order.getPayTime(), startTime.getTime(), endTime.getTime())) {
                                // 订单撤销
                                JSONObject refund = UnionPayConfig.cancel(UnionPayConfig.MER_ID3, UnionPayConfig.TERM_ID3, order.getOrderNo(), order.getPaySerialNo());
                                System.out.println(refund.toJSONString());
                                if (!refund.getString("resultcode").equals("00") || !refund.getString("resultcode").equals("W6")) {
                                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, refund.getString("returnmsg"));
                                }

                                order.setOrderStatus(4);
                                order.setRefundTime(new Date());
                                order.setRefundPrice(order.getPayRealPrice());
                                highOrderService.updateOrderDetail(order);

                            } else {
                                // 订单退款
                                JSONObject refund = UnionPayConfig.zwrefund(UnionPayConfig.MER_ID3, UnionPayConfig.TERM_ID3, order.getOrderNo(), order.getPaySerialNo(), order.getPayRealPrice().multiply(new BigDecimal("100")).longValue());
                                System.out.println(refund.toJSONString());
                                if (!refund.getString("resultcode").equals("00") || !refund.getString("resultcode").equals("W6")) {
                                    JSONObject refund2 = UnionPayConfig.zwrefund(UnionPayConfig.MER_ID1, UnionPayConfig.TERM_ID1, order.getOrderNo(), order.getPaySerialNo(), order.getPayRealPrice().multiply(new BigDecimal("100")).longValue());
                                    if (!refund2.getString("resultcode").equals("00") || !refund.getString("resultcode").equals("W6")) {
                                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, refund2.getString("returnmsg"));
                                    }
                                }

                                order.setOrderStatus(4);
                                order.setRefundTime(new Date());
                                order.setRefundPrice(order.getPayRealPrice());
                                highOrderService.updateOrderDetail(order);

                            }
                        } else if (order.getPayType().equals(OrderPayTypeEnum.type7.getType())) {
                            // 油卡退款
                            oilCardService.refund(order.getOrderNo());
                        }

                    } else if (!object.getBoolean("refundResult") == true && order != null) {
                        order.setOrderStatus(7);
                        order.setRefusalRefundContent(object.getString("refundFailReason"));
                        highOrderService.updateOrderDetail(order);
                    }
                }
            }

        } catch (Exception e) {
            log.error("WechatPayController --> wechatNotify() error!", e);
        } finally {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer= null;
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.write("success");
        }
    }

    @RequestMapping(value = "/abnormalOrderRefund", method = RequestMethod.POST)
    @ApiOperation(value = "异常订单退款")
    @ResponseBody
    public ResponseData abnormalOrderRefund(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isNotBlank(body.getString("orderNo"))) {
                // 查询订单
                HighOrder order = highOrderService.getOrderByOrderNo(body.getString("orderNo"));
                // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消   6.退款中   7.拒绝退款
                if (order != null && order.getOrderStatus() == 2) {
                    OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(order.getPaySerialNo(), order.getPayRealPrice(), order.getPayRealPrice());
                    if(orderRefundModel.getResult_code().equals("SUCCESS")) {
                        for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                            childOrder.setChildOrdeStatus(4);
                        }
                        order.setOrderStatus(4);
                        order.setRefundTime(new Date());
                        order.setRefundPrice(order.getPayRealPrice());
                        highOrderService.updateOrder(order);
                        return ResponseMsgUtil.success("退款成功");
                    }
                }
            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败");

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

}
