package com.hfkj.service.order;

import com.alibaba.fastjson.JSONArray;
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.DateUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.model.order.OrderModel;
import com.hfkj.qianzhu.CinemaService;
import com.hfkj.qianzhu.StarbucksService;
import com.hfkj.service.coupon.BsOrderCouponNoService;
import com.hfkj.service.coupon.BsOrderCouponService;
import com.hfkj.service.coupon.channel.ChongQingCNPCCouponService;
import com.hfkj.service.coupon.channel.HuiLianTongCouponService;
import com.hfkj.service.coupon.channel.PcytCNPCCouponConfig;
import com.hfkj.service.coupon.channel.PetroConfig;
import com.hfkj.service.goods.*;
import com.hfkj.service.goods.impl.BsOrderStarbucksServiceImpl;
import com.hfkj.service.hlt.HuiLianTongUnionCardService;
import com.hfkj.sysenum.GoodsVpdSourceEnum;
import com.hfkj.sysenum.order.*;
import com.hfkj.yushang.YuShangService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className: OrderPaySuccesService
 * @author: HuRui
 * @date: 2024/5/7
 **/
@Component
public class OrderPaySuccessService {
    Logger log = LoggerFactory.getLogger(OrderPaySuccessService.class);
    @Resource
    private BsOrderService orderService;
    @Resource
    private BsOrderGoodsService bsOrderGoodsService;
    @Resource
    private BsOrderCouponService orderCouponService;
    @Resource
    private BsOrderCouponNoService orderCouponNoService;
    @Resource
    private GoodsMsgService goodsMsgService;
    @Resource
    private GoodsVpdService goodsVpdService;
    @Resource
    private BsOrderStarbucksService orderStarbucksService;
    @Resource
    private BsOrderCinemaService bsOrderCinemaService;
    @Autowired
    private BsOrderStarbucksServiceImpl bsOrderStarbucksService;

    /**
     * 订单业务处理
     * @param order
     * @throws Exception
     */
    public void orderBusHandle(OrderModel order) {
        for (BsOrderChild childOrder : order.getOrderChildList()) {
            try {
                if (childOrder.getProductType().equals(OrderChildProductTypeEnum.type1.getCode())) {
                    goods(order, childOrder);
                } else if (childOrder.getProductType().equals(OrderChildProductTypeEnum.type2.getCode())) {
                    product(order, childOrder);
                } else if (childOrder.getProductType().equals(OrderChildProductTypeEnum.type3.getCode())) {
                    cinema(order, childOrder);
                } else if (childOrder.getProductType().equals(OrderChildProductTypeEnum.type4.getCode())) {
                    starbucks(order , childOrder);
                }
             } catch (Exception e) {

            }
        }
    }

    /**
     * 处理产品
     * @param childOrder
     * @throws Exception
     */
    public void product(OrderModel order,BsOrderChild childOrder) throws Exception {
        // 查询产品
        GoodsMsg goods = goodsMsgService.queryDetail(childOrder.getProductId());
        if (goods.getType() == 1) {

        } else if (goods.getType() == 2) {
            productVpd(order, childOrder);
        }
    }

    /**
     * 虚拟产品
     * @param childOrder
     */
    public void productVpd(OrderModel order, BsOrderChild childOrder) throws Exception {
        // 查询卡券订单
        BsOrderCoupon orderCoupon = orderCouponService.getDetailByChildOrderNo(childOrder.getChildOrderNo());
        // 查询卡券订单的卡密
        List<BsOrderCouponNo> couponNoList = orderCouponNoService.getListByCouponOrderId(orderCoupon.getId());
        for (BsOrderCouponNo couponNo : couponNoList) {
            try {
                // 虚拟商品
                GoodsVpd vpd = goodsVpdService.queryDetailBySpecsId(childOrder.getProductSpecId());
                if (vpd.getSource() == GoodsVpdSourceEnum.type1.getCode()) {

                } else if (vpd.getSource() == GoodsVpdSourceEnum.type2.getCode()) {


                    Map<String , Object> map = new HashMap<>();
                    map.put("productCode" , vpd.getKey());
                    map.put("AppKey" , CommonSysConst.getSysConfig().getYuShangAppKey());
                    map.put("BuyCount" , childOrder.getProductCount());
                    map.put("MOrderID" , childOrder.getChildOrderNo());
                    map.put("ChargeAccount" , childOrder.getChildOrderNo());
                    // 推送给娱尚
                   YuShangService.insertV2(map);

                } else if (vpd.getSource() == GoodsVpdSourceEnum.type4.getCode()) {
                    // 推送给汇联通
                    JSONObject returnParam = HuiLianTongCouponService.costRechargeOrder(couponNo.getChannelOrderNo());
                    if (returnParam.getString("respCode").equals("0000")) {
                        // 解密
                        JSONObject jsonObject = HuiLianTongUnionCardService.resolveResponse(returnParam.getString("data"));
                        JSONArray dataArray = JSONObject.parseObject(jsonObject.getString("data"), JSONArray.class);
                        for (Object data : dataArray) {
                            JSONObject dataObject = (JSONObject) data;
                            couponNo.setExpireTime(dataObject.getDate("validEndDate"));
                            couponNo.setDeliverTime(new Date());
                            couponNo.setGoodsVpdSourceCouNo(dataObject.getString("couNo"));
                            couponNo.setStatus(OrderCouponNoStatusEnum.status2.getCode());
                            orderCouponNoService.editData(couponNo);
                        }
                    }

                } else if (vpd.getSource() == GoodsVpdSourceEnum.type5.getCode()) {
                    // 预发码
                    JSONObject preSendCoupon = ChongQingCNPCCouponService.preSendCoupon(orderCoupon.getGoodsVpdKey(), couponNo.getOrderNo(), 1, orderCoupon.getUserPhone());
                    if (preSendCoupon.getInteger("status").equals(1)) {
                        // 给用户发码
                        JSONObject response = ChongQingCNPCCouponService.sendCNPCTicket(orderCoupon.getGoodsVpdKey(), couponNo.getOrderNo(), 1, orderCoupon.getUserPhone());
                        JSONObject couponDetail = response.getJSONObject("ticketDetail");
                        JSONArray codeList = response.getJSONArray("codeList");
                        for (Object data : codeList) {
                            couponNo.setExpireTime(DateUtil.format(couponDetail.getString("expiredDate"), "yyyy-MM-dd"));
                            couponNo.setDeliverTime(new Date());
                            couponNo.setGoodsVpdSourceCouNo(ChongQingCNPCCouponService.decryptCouponCode(String.valueOf(data)));
                            couponNo.setStatus(OrderCouponNoStatusEnum.status2.getCode());
                            orderCouponNoService.editData(couponNo);
                        }
                    }

                } else if (vpd.getSource() == GoodsVpdSourceEnum.type6.getCode()) {

                } else if (vpd.getSource() == GoodsVpdSourceEnum.type7.getCode()) {
                // 发放卡券
                JSONObject jsonObject = PetroConfig.getCoupon(orderCoupon.getGoodsVpdKey(), orderCoupon.getUserPhone());
                if (!jsonObject.getString("resultCode").equals("0000")) {
                    throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , jsonObject.getString("errMsg"));
                }
                String data = PetroConfig.decrypt(jsonObject.getString("jsonResult"));
                JSONObject object = JSONObject.parseObject(data);
                couponNo.setExpireTime(vpd.getSalesEndTime());
                couponNo.setDeliverTime(new Date());
                couponNo.setGoodsVpdSourceCouNo(object.getString("voucher"));
                couponNo.setStatus(OrderCouponNoStatusEnum.status2.getCode());
                orderCouponService.editData(orderCoupon);

                } else if (vpd.getSource() == GoodsVpdSourceEnum.type10.getCode()) {
                    // 发放卡券
                    JSONObject jsonObject = PcytCNPCCouponConfig.getCoupon(couponNo.getOrderNo() , orderCoupon.getUserPhone() , orderCoupon.getGoodsVpdKey());
                    if (!jsonObject.getString("code").equals("200")) {
                        throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , jsonObject.getString("errMsg"));
                    }
                    JSONObject object = jsonObject.getJSONObject("data");
                    couponNo.setExpireTime(vpd.getSalesEndTime());
                    couponNo.setDeliverTime(new Date());
                    couponNo.setGoodsVpdSourceCouNo(object.getString("couponCode"));
                    couponNo.setStatus(OrderCouponNoStatusEnum.status2.getCode());
                    orderCouponNoService.editData(couponNo);
                }


            } catch (Exception e) {
                couponNo.setExceptionStatus(true);
                orderCouponService.editData(orderCoupon);
            }
        }

        orderCoupon.setTotalPrice(childOrder.getProductTotalPrice());
        orderCoupon.setTotalDeductionPrice(childOrder.getTotalDeductionPrice());
        orderCoupon.setCouponDiscountPrice(childOrder.getCouponDiscountPrice());
        orderCoupon.setIntegralDiscountPrice(childOrder.getIntegralDiscountPrice());
        orderCoupon.setPayRealPrice(childOrder.getSurplusRefundPrice());
        orderCoupon.setPayChannel(order.getPayChannel());
        orderCoupon.setPayType(order.getPayType());
        orderCoupon.setPaySerialNo(order.getPaySerialNo());
        orderCoupon.setPayTime(order.getPayTime());
        orderCoupon.setStatus(OrderChildStatusEnum.status2.getCode());
        orderCouponService.editData(orderCoupon);

        /// 增加销量
        goodsMsgService.editSaleNum(childOrder.getProductId(), childOrder.getProductCount(), 1);

        // 子订单完成
        orderService.childOrderComplete(orderCoupon.getChildOrderNo());
    }
    /**
     * 实物产品
     * @param order
     */
    public void goods(OrderModel order, BsOrderChild childOrder) {
        BsOrderGoods goodsOrder = bsOrderGoodsService.findGoodsOrderByChild(childOrder.getChildOrderNo());
        try {

            if (goodsOrder == null) {
                throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "未查询到相关内容");
            }


            goodsMsgService.editSaleNum(goodsOrder.getGoodsId() , goodsOrder.getGoodsCount() , 1);

            goodsOrder.setTotalPrice(childOrder.getProductTotalPrice());
            goodsOrder.setTotalDeductionPrice(childOrder.getTotalDeductionPrice());
            goodsOrder.setCouponDiscountPrice(childOrder.getCouponDiscountPrice());
            goodsOrder.setIntegralDiscountPrice(childOrder.getIntegralDiscountPrice());
            goodsOrder.setPayRealPrice(childOrder.getSurplusRefundPrice());
            goodsOrder.setPayChannel(order.getPayChannel());
            goodsOrder.setPayType(order.getPayType());
            goodsOrder.setPaySerialNo(order.getPaySerialNo());
            goodsOrder.setPayTime(order.getPayTime());
            goodsOrder.setUpdateTime(new Date());
            goodsOrder.setStatus(childOrder.getStatus());
            bsOrderGoodsService.update(goodsOrder);
        } catch (Exception e) {
            if (goodsOrder == null) {
                goodsOrder = new BsOrderGoods();
            }
            goodsOrder.setExceptionMsg(e.getMessage());
            bsOrderGoodsService.update(goodsOrder);

        }
    }

    public void cinema(OrderModel order,BsOrderChild childOrder) {
        // 查询电影票订单
        BsOrderCinema orderCinema = bsOrderCinemaService.findGoodsOrder(order.getOrderNo());
        try {

            if (orderCinema == null) {
                throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "未查询到对应！");
            }

            //  创建订单(备用金模式)，会直接扣除账户余额，最多只能选择 4 个座位
            Map<String, Object> params = new HashMap<>();
            params.put("drawMode", orderCinema.getDrawMode());
            params.put("acceptAdjust", orderCinema.getAcceptAdjust());
            params.put("showId", orderCinema.getShowId());
            params.put("seatsCount", orderCinema.getSeatsCount());
            params.put("seats", orderCinema.getSeats());
            params.put("platformUniqueId", order.getOrderNo());
            params.put("platformOrderNo", childOrder.getChildOrderNo());
            params.put("mobile", orderCinema.getUserPhone());
            params.put("notifyUrl", CommonSysConst.getSysConfig().getQianZhuCinemaNotify());
            JSONObject jsonObject = CinemaService.createMovieOrder(params);

            if (jsonObject == null) {
                throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "上送订单失败！");
            }

            orderCinema.setStatus(jsonObject.getJSONObject("data").getInteger("status"));
            orderCinema.setChannelOrderNo(jsonObject.getJSONObject("data").getString("orderNo"));
            orderCinema.setUpdateTime(new Date());

            orderCinema.setTotalPrice(childOrder.getProductTotalPrice());
            orderCinema.setTotalDeductionPrice(childOrder.getTotalDeductionPrice());
            orderCinema.setCouponDiscountPrice(childOrder.getCouponDiscountPrice());
            orderCinema.setIntegralDiscountPrice(childOrder.getIntegralDiscountPrice());
            orderCinema.setPayRealPrice(childOrder.getSurplusRefundPrice());
            orderCinema.setPayChannel(order.getPayChannel());
            orderCinema.setPayType(order.getPayType());
            orderCinema.setPaySerialNo(order.getPaySerialNo());
            orderCinema.setPayTime(order.getPayTime());
            orderCinema.setUpdateTime(new Date());
            orderCinema.setStatus(OrderCinemaStatusEnum.status5.getCode());
            bsOrderCinemaService.update(orderCinema);

        } catch (Exception e) {
            if (orderCinema == null) {
                orderCinema = new BsOrderCinema();
            }
            orderCinema.setExceptionStatus(true);
            orderCinema.setExceptionMsg(e.getMessage());
            bsOrderCinemaService.update(orderCinema);
        }

    }

    public void starbucks(OrderModel order,BsOrderChild childOrder) {
        // 推送订单
        // 查询星巴克订单
        Map<String , Object> map = new HashMap<>();
        map.put("orderNo", childOrder.getChannelOrderNo());
        StarbucksService.starbucksOrdersPay(map);

        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", childOrder.getOrderNo());
        List<BsOrderStarbucks> orderStarbucks = bsOrderStarbucksService.getList(params);

        for (BsOrderStarbucks bsOrderStarbucks : orderStarbucks) {
            bsOrderStarbucks.setPayType(order.getPayType());
            bsOrderStarbucksService.update(bsOrderStarbucks);
        }
    }


}
