package com.gxwebsoft.apps.task;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.annotation.SqlParser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gxwebsoft.apps.entity.Equipment;
import com.gxwebsoft.apps.entity.EquipmentOrderGoods;
import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.apps.service.EquipmentOrderGoodsService;
import com.gxwebsoft.apps.service.EquipmentService;
import com.gxwebsoft.common.core.config.MybatisPlusConfig;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.love.entity.UserPlanLog;
import com.gxwebsoft.love.param.UserPlanLogParam;
import com.gxwebsoft.shop.entity.Manager;
import com.gxwebsoft.shop.entity.Merchant;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.ProfitLog;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.service.ManagerService;
import com.gxwebsoft.shop.service.MerchantService;
import com.gxwebsoft.shop.service.OrderService;
import com.gxwebsoft.shop.service.ProfitLogService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.NumberUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.gxwebsoft.common.core.constants.OrderConstants.*;

/**
 * 定时任务：订单处理
 */
@Component
@Slf4j
public class OrderTask {

    @Resource
    private OrderService orderService;

    @Resource
    private EquipmentService equipmentService;

    @Resource
    private EquipmentGoodsService equipmentGoodsService;

    @Resource
    private EquipmentOrderGoodsService orderGoodsService;

    @Resource
    private UserService userService;


    @Resource
    private MerchantService merchantService;

    @Resource
    private ProfitLogService profitLogService;

    @Resource
    private ManagerService managerService;

    /**
     * 删除30分钟未下单的订单
     */
//    @Scheduled(cron="0 0/30 * * * ? ")
    public void removeTimeoutOrder() {
        Date newDate = DateUtil.offset(DateUtil.date(), DateField.MINUTE, -30);
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery(Order.class)
                .eq(Order::getPayStatus, PAY_STATUS_NO_PAY)
                .lt(Order::getCreateTime, newDate);

        boolean remove = orderService.remove(wrapper);

    }

    /**
     * 计算分润
     */
    @Scheduled(cron="0 0/1 * * * ? ")
    @Transactional
    public void CalcProfit() {
        log.info("开始计算分润");
        // 查询所有未结算订单
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery(Order.class)
                .eq(Order::getIsSettled, ORDER_SETTLED_NO)
                .eq(Order::getPayStatus, PAY_STATUS_SUCCESS)
                .eq(Order::getOrderStatus, ORDER_STATUS_COMPLETED);

        List<Order> orderList = orderService.list(wrapper);
        if(CollectionUtils.isEmpty(orderList)){
            return;
        }


        Set<Integer> equipmentIds = new HashSet<>();
        Set<Integer> orderIds = new HashSet<>();
        Set<String> tuijianUserPhones = new HashSet<>();
        Set<String> mendianCodes = new HashSet<>();


        for (Order order : orderList) {
            equipmentIds.add(order.getEquipmentId());
            mendianCodes.add(order.getMerchantCode());
            orderIds.add(order.getOrderId());
            if (order.getDealerPhone() != null) {
                tuijianUserPhones.add(order.getDealerPhone());
            }
        }
        // 查询所有订单商品
        List<EquipmentOrderGoods> orderGoodsList = orderGoodsService.list(Wrappers.lambdaQuery(EquipmentOrderGoods.class).in(EquipmentOrderGoods::getOrderId, orderIds));
        Map<Integer, List<EquipmentOrderGoods>> orderGoodsMap = orderGoodsList.stream().collect(Collectors.groupingBy(EquipmentOrderGoods::getOrderId));


        // 查询所有关联的设备
        List<Equipment> equipmentList = equipmentService.list(Wrappers.lambdaQuery(Equipment.class).in(Equipment::getEquipmentId, equipmentIds));
        Map<Integer, Equipment> equipmentMap = new HashMap<>();
        Set<Integer> touziUserIds = new HashSet<>();
        for (Equipment equipment : equipmentList) {
            equipmentMap.put(equipment.getEquipmentId(), equipment);
            if (equipment.getTouziUserId() != null) {
                touziUserIds.add(equipment.getTouziUserId());
            }
        }

        // 查询所有投资人
        Map<Integer, User> touziUserMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(touziUserIds)) {
            List<User> list = userService.list(Wrappers.lambdaQuery(User.class).in(User::getUserId, touziUserIds));
            for (User user : list) {
                touziUserMap.put(user.getUserId(), user);
            }
        }

        // 查询所有推荐人
        Map<String, User> tuijianUserMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(tuijianUserPhones)) {
            List<User> tuijianUserList = userService.list(Wrappers.lambdaQuery(User.class).in(User::getPhone, tuijianUserPhones));
            for (User user : tuijianUserList) {
                tuijianUserMap.put(user.getPhone(), user);
            }
        }

        // 查询所有门店
        Map<String, Merchant> mendianMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(mendianCodes)) {
            List<Merchant> merchantList = merchantService.list(Wrappers.lambdaQuery(Merchant.class).in(Merchant::getMerchantCode, mendianCodes));
            for (Merchant merchant : merchantList) {
                mendianMap.put(merchant.getMerchantCode(), merchant);
            }
        }

        // 查询所有区域经理
//        Wrappers.lambdaQuery(Manager.class)
        List<Manager> jingliList = managerService.list();


        // 开始结算
        for (Order order : orderList) {
            // 计算投资人收益
            List<EquipmentOrderGoods> equipmentOrderGoods = orderGoodsMap.get(order.getOrderId());
            if (CollectionUtils.isNotEmpty(equipmentOrderGoods)) {
                EquipmentOrderGoods orderGoods = equipmentOrderGoods.get(0);
                BigDecimal touziProfit;
                BigDecimal tuijianProfit;
                BigDecimal mendianProfit;
                BigDecimal jingliProfit;
                Merchant merchant = mendianMap.get(order.getMerchantCode());
                // 是否分期首期
                if ("20".equals(orderGoods.getEquipmentCategory()) && order.getIsRenew() == 0) {
                    touziProfit = orderGoods.getTouziFirstProfit();
                    tuijianProfit = orderGoods.getTuijianFirstProfit();
                    mendianProfit = orderGoods.getMendianFirstProfit();
                    jingliProfit = orderGoods.getJingliFirstProfit();
                } else {
                    touziProfit = orderGoods.getTouziProfit();
                    tuijianProfit = orderGoods.getTuijianProfit();
                    mendianProfit = orderGoods.getMendianProfit();
                    jingliProfit = orderGoods.getJingliProfit();
                }
                // 投资人收益
                if (touziProfit.compareTo(BigDecimal.ZERO) > 0) {
                    Equipment equipment = equipmentMap.get(order.getEquipmentId());
                    User touziUser = touziUserMap.get(equipment.getTouziUserId());
                    if (touziUser != null) {
                        userService.updateBalanceByUserId(touziUser.getUserId(), touziProfit);
                        ProfitLog profitLog = new ProfitLog();
                        profitLog.setUserId(touziUser.getUserId());
                        profitLog.setMoney(touziProfit);
                        profitLog.setScene(1);
                        profitLog.setMerchantCode(merchant.getMerchantCode());
                        profitLog.setOrderId(order.getOrderId());
                        profitLog.setOrderNo(order.getOrderNo());
                        profitLog.setComments("投资设备：" + equipment.getEquipmentCode());
                        profitLogService.save(profitLog);
                    }
                }

                //推荐人收益
                if (tuijianProfit.compareTo(BigDecimal.ZERO) > 0) {
                    User tuijianUser = tuijianUserMap.get(order.getDealerPhone());
                    if (tuijianUser != null) {
                        userService.updateBalanceByUserId(tuijianUser.getUserId(), tuijianProfit);
                        ProfitLog profitLog = new ProfitLog();
                        profitLog.setUserId(tuijianUser.getUserId());
                        profitLog.setMoney(tuijianProfit);
                        profitLog.setScene(3);
                        profitLog.setMerchantCode(merchant.getMerchantCode());
                        profitLog.setOrderId(order.getOrderId());
                        profitLog.setOrderNo(order.getOrderNo());
                        profitLog.setComments("推广收益：" + order.getUserId());

                        profitLogService.save(profitLog);
                    }
                }

                // 计算门店收益

                if (mendianProfit.compareTo(BigDecimal.ZERO) > 0) {
                    Integer mendianUserId = merchant.getMerchantOwner();
                    if (mendianUserId != null) {
                        userService.updateBalanceByUserId(mendianUserId, mendianProfit);
                        ProfitLog profitLog = new ProfitLog();
                        profitLog.setUserId(mendianUserId);
                        profitLog.setMoney(mendianProfit);
                        profitLog.setScene(4);
                        profitLog.setMerchantCode(merchant.getMerchantCode());
                        profitLog.setOrderId(order.getOrderId());
                        profitLog.setOrderNo(order.getOrderNo());
                        profitLog.setComments("门店收益：" + order.getMerchantCode());
                        profitLogService.save(profitLog);
                    }
                }
                // 计算区域经理收益

                if (jingliProfit.compareTo(BigDecimal.ZERO) > 0) {
                    Manager manager = null;
                    if (merchant.getManagerId() != null) {
                        manager = jingliList.stream().filter(d -> {
                            return d.getUserId().equals(merchant.getManagerId());
                        }).findFirst().orElse(null);
                    } else {
                        manager = jingliList.stream().filter(d -> {
                            return d.getProvince().equals(merchant.getProvince()) && d.getCity().equals(merchant.getCity()) && d.getArea().equals(merchant.getRegion());
                        }).findFirst().orElse(null);
                    }
                    if (manager != null) {
                        userService.updateBalanceByUserId(manager.getUserId(), jingliProfit);
                        ProfitLog profitLog = new ProfitLog();
                        profitLog.setUserId(manager.getUserId());
                        profitLog.setMoney(jingliProfit);
                        profitLog.setMerchantCode(merchant.getMerchantCode());
                        profitLog.setScene(5);
                        profitLog.setOrderId(order.getOrderId());
                        profitLog.setOrderNo(order.getOrderNo());
                        profitLog.setComments("门店业绩：" + order.getMerchantCode());
                        profitLogService.save(profitLog);
                    }
                }
            }


        }
        LambdaUpdateWrapper<Order> updateWrapper = Wrappers.lambdaUpdate(Order.class).in(Order::getOrderId, orderIds).set(Order::getIsSettled, 1);
        orderService.update(updateWrapper);

    }
}
