package com.hai.order.service.impl;

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.security.UserCenter;
import com.hai.common.utils.IDGenerator;
import com.hai.config.HuiLianTongConfig;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.entity.*;
import com.hai.enum_type.GasClassGroupTaskStatus;
import com.hai.model.ResponseData;
import com.hai.order.model.CreateOrderChildModel;
import com.hai.order.service.OrderCreateHandleService;
import com.hai.order.service.OrderService;
import com.hai.order.service.OrderServiceExt;
import com.hai.order.type.OrderChildGoodsType;
import com.hai.order.type.OrderChildStatus;
import com.hai.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 创建订单-业务校验
 * @className: CreateOrderCheckService
 * @author: HuRui
 * @date: 2022/8/25
 **/
@Service("createOrderHandleService")
public class OrderCreateHandleServiceImpl implements OrderCreateHandleService {

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

    @Resource
    private CommonService commonService;

    @Resource
    private OrderService orderService;

    @Resource
    private HighUserService userService;

    @Resource
    private OrderServiceExt orderServiceExt;

    @Resource
    private HighCouponService couponService;

    @Resource
    private HighMerchantStoreService storeService;

    @Resource
    private HighDiscountCouponRelService discountCouponRelService;

    @Resource
    private HighCouponHandselService highCouponHandselService;

    @Override
    public List<HighChildOrder> couponHandle(HighDiscountUserRel discountUserRel, CreateOrderChildModel createOrderChild) throws Exception {
            if (createOrderChild.getSaleCount() != 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "卡卷只能购买一张");
            }
            // 查询卡卷信息
            HighCoupon coupon = couponService.getCouponDetail(createOrderChild.getGoodsId());
            if (coupon == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
            }
            // 是否需要预约
            if (coupon.getReserveStatus() == true) {
                if (createOrderChild.getStoreId() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未选择门店");
                }
                // 查询门店信息
                HighMerchantStore merchantStore = storeService.getDetailById(createOrderChild.getStoreId());
                if (merchantStore == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店信息");
                }
                if (!merchantStore.getMerchantId().equals(coupon.getMerchantId())) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "卡券无法在此门店消费");
                }
            }

            // 是否达到限购数量
            if (orderServiceExt.userBuyCouponNum(createOrderChild.getMemId(), coupon.getId()) > coupon.getLimitNumber()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + ",已达到限购数量");
            }

            // 生成子订单编号
            String childOrderNo = generateChildOrderNo();

            // 如果不是来源不是贵州中石化，需要校验库存
            if (!coupon.getCouponSource().equals(4)) {
                if (couponService.assignOrderStock(coupon.getId(), childOrderNo) == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "库存不足");
                }
            }

            List<HighChildOrder> childOrderList = new ArrayList<>();
            HighChildOrder childOrder;
            childOrder = new HighChildOrder();
            childOrder.setMemId(createOrderChild.getMemId());
            childOrder.setMemName(createOrderChild.getMemName());
            childOrder.setMemPhone(createOrderChild.getMemPhone());
            childOrder.setChildOrderNo(childOrderNo);
            childOrder.setGoodsType(OrderChildGoodsType.TYPE1.getNumber());
            childOrder.setGoodsId(coupon.getId());
            childOrder.setGoodsName(coupon.getCouponName());
            childOrder.setGoodsImg(coupon.getCouponImg());
            childOrder.setGoodsSpecName("默认");
            childOrder.setGoodsPrice(coupon.getSalesPrice());
            childOrder.setGoodsActualPrice(coupon.getDiscountPrice());
            childOrder.setSaleCount(createOrderChild.getSaleCount());
            childOrder.setGiveawayType(false);
            childOrder.setChildOrderStatus(OrderChildStatus.STATUS1.getNumber());
            childOrder.setPraiseStatus(0);
            childOrder.setCreateTime(new Date());

            // 贵州中石化
            if (coupon.getCouponSource().equals(4)) {
                // 下单请求
                JSONObject jsonObject = HuiLianTongConfig.recharge(createOrderChild.getOrderNo(),
                        childOrder.getSaleCount(),
                        coupon.getCouponKey(),
                        createOrderChild.getMemPhone());
                if (!jsonObject.getString("respCode").equals("0000")) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "下单失败");
                }
                JSONObject response = HuiLianTongUnionCardConfig.resolveResponse(jsonObject.getString("data"));
                if (!response.getString("respCode").equals("0000")) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response.getString("msg"));
                }
                childOrder.setChannelOrderNo(response.getJSONObject("data").getString("rechargeOrderId"));
            }

            // 校验优惠券是否可用  如果使用优惠券就只能使用卡券的原价
            if (discountUserRel != null) {
                List<HighDiscountCouponRel> discountCouponRelList = discountCouponRelService.getRelByCoupon(coupon.getId());
                List<HighDiscountCouponRel> collect = discountCouponRelList.stream().filter(o -> o.getDiscountId().equals(discountUserRel.getDiscountId())).collect(Collectors.toList());
                if (collect == null || collect.size() == 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法使用优惠券");
                }
                childOrder.setGoodsActualPrice(coupon.getSalesPrice());
            }

            childOrder.setTotalPrice(childOrder.getGoodsPrice().multiply(new BigDecimal(childOrder.getSaleCount().toString())));
            childOrder.setTotalActualPrice(childOrder.getGoodsActualPrice().multiply(new BigDecimal(childOrder.getSaleCount().toString())));
            childOrderList.add(childOrder);

            // 是否赠送卡卷
            if (coupon.getIsPresent() == true) {
                // 查询赠送卡券信息
                List<HighCouponHandsel> handselCouponList = highCouponHandselService.getHandselListByCoupon(childOrder.getGoodsId());
                for (HighCouponHandsel handsel : handselCouponList) {
                    // 查询卡卷信息
                    HighCoupon handselCoupon = couponService.getCouponDetail(handsel.getHandselCouponId());
                    if (handselCoupon == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
                    }
                    String handselChildOrderNo = generateChildOrderNo();

                    // 赠送卡卷是否有库存，没有就不赠送
                    if (couponService.assignOrderStock(handselCoupon.getId(), handselChildOrderNo) != null) {
                        childOrder= new HighChildOrder();
                        childOrder.setMemId(createOrderChild.getMemId());
                        childOrder.setChildOrderNo(handselChildOrderNo);
                        childOrder.setGoodsType(OrderChildGoodsType.TYPE1.getNumber());
                        childOrder.setGoodsId(handselCoupon.getId());
                        childOrder.setGoodsName(handselCoupon.getCouponName());
                        childOrder.setGoodsImg(handselCoupon.getCouponImg());
                        childOrder.setGoodsSpecName("默认");
                        childOrder.setGoodsPrice(handselCoupon.getSalesPrice());
                        childOrder.setGoodsActualPrice(new BigDecimal("0"));
                        childOrder.setSaleCount(1);
                        childOrder.setGiveawayType(true);
                        childOrder.setChildOrderStatus(OrderChildStatus.STATUS1.getNumber());
                        childOrder.setPraiseStatus(0);
                        childOrder.setTotalPrice(childOrder.getGoodsPrice().multiply(new BigDecimal(childOrder.getSaleCount().toString())));
                        childOrder.setTotalActualPrice(childOrder.getGoodsActualPrice().multiply(new BigDecimal(childOrder.getSaleCount().toString())));
                        childOrderList.add(childOrder);
                    }
                }
            }

            return childOrderList;
    }

    @Override
    public HighChildOrder integralRecharge(CreateOrderChildModel createOrderChild) {
        // 查询用户信息
        HighUser user = userService.getDetailDataByUser(createOrderChild.getGoodsId());
        if (user == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到用户信息");
        }
        HighChildOrder childOrder = new HighChildOrder();
        childOrder.setChildOrderNo(generateChildOrderNo());
        childOrder.setGoodsType(OrderChildGoodsType.TYPE1.getNumber());
        childOrder.setGoodsId(user.getId());
        childOrder.setGoodsName(user.getName());
        childOrder.setGoodsImg(user.getHeaderImg());
        childOrder.setGoodsSpecName("默认");
        childOrder.setGoodsPrice(createOrderChild.getGoodsPrice());
        childOrder.setGoodsActualPrice(createOrderChild.getGoodsPrice());
        childOrder.setSaleCount(1);
        childOrder.setTotalPrice(childOrder.getGoodsPrice().multiply(new BigDecimal(childOrder.getSaleCount().toString())));
        childOrder.setTotalActualPrice(childOrder.getGoodsActualPrice().multiply(new BigDecimal(childOrder.getSaleCount().toString())));
        childOrder.setChildOrderStatus(OrderChildStatus.STATUS1.getNumber());
        childOrder.setGiveawayType(false);
        childOrder.setPraiseStatus(0);
        return childOrder;
    }

    @Override
    public HighChildOrder oilHandle(HighOrder order,HighDiscountUserRel discountUserRel, CreateOrderChildModel createOrderChild) {
        // 查询油品类型
        SecDictionary gasOilType = commonService.mappingSysCode("GAS_OIL_TYPE", createOrderChild.getGasOilNo());
        if (gasOilType == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知油品类型");
        }

        // 加油限制
        if (gasOilType.getExt1().equals("1")) {
            SecDictionary refuelLimit = commonService.mappingSysName("REFUEL_LIMIT", "汽油");
            if (refuelLimit != null && createOrderChild.getGoodsPrice().compareTo(new BigDecimal(refuelLimit.getCodeValue()))  == 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "汽油加油金额不能超过" + refuelLimit.getCodeValue()+"元");
            }
        } else if (gasOilType.getExt1().equals("2")) {
            SecDictionary refuelLimit = commonService.mappingSysName("REFUEL_LIMIT", "柴油");
            if (refuelLimit != null && createOrderChild.getGoodsPrice().compareTo(new BigDecimal(refuelLimit.getCodeValue()))  == 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "柴油加油金额不能超过" + refuelLimit.getCodeValue()+"元");
            }
        }

        if (StringUtils.isNotBlank(createOrderChild.getGasStaffCode())) {
            String qrCodeSignKey = commonService.getDictionaryCodeName("QR_CODE_SIGN_KEY", "1");
            if (StringUtils.isBlank(qrCodeSignKey)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知秘钥");
            }
            String staffId;
            try {
                staffId = AESEncodeUtil.aesDecryptByBytes(AESEncodeUtil.base64Decode(URLDecoder.decode(createOrderChild.getGasStaffCode(),"UTF-8")), qrCodeSignKey);
            } catch (Exception e) {
                log.error("HighOrderController --> addOrder() error!", "收银员code解析失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "收银员code解析失败");
            }
/*            // 查询员工
            HighGasStaff gasStaff = gasStaffService.getStaffDetailById(Long.parseLong(staffId));
            if (gasStaff == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知收银员");
            }
            if (gasStaff.getMerchantStoreId().equals(childOrder.getGoodsId())) {
                childOrder.setGasStaffId(gasStaff.getId());
                childOrder.setGasStaffName(gasStaff.getName());
            }*/
        }


  /*      // 查询加油站是否开启班组
        Map<String, Object> classGroup = new HashMap<>();
        classGroup.put("merchantStoreId", createOrderChild.getGoodsId());
        classGroup.put("status", GasClassGroupTaskStatus.status1.getStatus());
        List<HighGasClassGroupTask> groupTaskList = gasClassGroupTaskService.getGroupTaskList(classGroup);
        if (groupTaskList.size() > 0) {
            HighGasClassGroupTask groupTask = groupTaskList.get(0);
            childOrder.setGasClassGroupId(groupTask.getGasClassGroupId());
            childOrder.setGasClassGroupName(groupTask.getGasClassGroupName());
            childOrder.setGasClassGroupTaskId(groupTask.getId());
        }*/

        return null;
    }

    @Override
    public ResponseData couponPackage(CreateOrderChildModel createOrderChild) {
        return null;
    }

    @Override
    public ResponseData hltUnionCardRecharge(CreateOrderChildModel createOrderChild) {
        return null;
    }

    /**
     * 生成子订单号
     * @return
     * @throws Exception
     */
    public static String generateChildOrderNo() {
        // 生成子订单号
        return IDGenerator.nextId(16);
    }
}
