package com.younike.system.task;

import com.younike.common.core.domain.entity.SysUser;
import com.younike.system.domain.Merchant;
import com.younike.system.domain.Order;
import com.younike.system.domain.PersonalMerchantSettle;
import com.younike.system.domain.TaskLog;
import com.younike.system.domain.vo.OrderVo;
import com.younike.system.enums.PersonalSettleStatusEnum;
import com.younike.system.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * 个体户账单结算统计任务
 *
 * @author dail
 */
/**
 * 2022/4/18 定时任务改为统计账单结算
 */
@Component("personalSettleTask")
public class PersonalSettleTask {
    @SuppressWarnings("all")
    private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(PersonalSettleTask.class);
    /**
     * 任务日志
     */
    @Autowired
    private ITaskLogService taskLogService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IPersonalMerchantSettleService personalMerchantSettleService;

    public void settle() {
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskName("账单结算信息统计");
        taskLog.setExecutionTime(LocalDateTime.now());
        try {
            LocalDate currentDate = LocalDate.now();
            LocalDate lastMonthCurrentDate = currentDate.minusMonths(1);
            LocalDate settleStartDate = lastMonthCurrentDate.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate settleEndDate = lastMonthCurrentDate.with(TemporalAdjusters.lastDayOfMonth());
            log.info("账单结算期间:" + settleStartDate + "~" + settleEndDate);
            // 查询所有「已完成」「已拒绝退款」预定订单，以商家进行分组
           // Map<Long, List<Order>> reserveSettledOrders = orderService.listMerchantReserveSettleOrder(settleStartDate, settleEndDate);
            //查询所有[当月核销次数],以及团购订单金额,以商家进行分组
            Map<Long, List<OrderVo>> groupSettledOrders = orderService.listMerchantGroupSettleOrder(settleStartDate, settleEndDate);
            // 查询所有「已完成」「已拒绝退款」「已退款，部分退款」预定订单，以商家进行分组
            Map<Long, List<Order>>  reserveSettledOrders = orderService.listMerchantReserveRefundSettleOrder(settleStartDate, settleEndDate);

            //创建要更新或者编辑的数据集合
            List<PersonalMerchantSettle> addSettleList = new ArrayList<>();
            List<PersonalMerchantSettle> updateSettleList = new ArrayList<>();
            //是否操作数据标志
            Boolean aBoolean = new Boolean(true);
            if (reserveSettledOrders != null && reserveSettledOrders.size() > 0) {
                for (Map.Entry<Long, List<Order>> entry : reserveSettledOrders.entrySet()) {
                    // 遍历各商家待结算订单金额
                    BigDecimal reserveIncome = entry.getValue().stream().map(Order::getShopAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
                    // 查询商家信息
                    Merchant merchant = merchantService.selectMerchantByMerchantId(entry.getKey());
                    if (merchant == null) {
                        log.error("账单结算统计错误 -- 待结算商家信息异常（缺失）" + entry.getKey().toString());
                    } else {
                        // 查询商家该月是否已存在未结算账单记录，若存在，则更新
                        String dateStr = String.valueOf(settleStartDate);
                        PersonalMerchantSettle byMerchantIdAndYearMonth = personalMerchantSettleService.getByMerchantIdAndYearMonth(entry.getKey(), dateStr.substring(0, dateStr.lastIndexOf("-")));
                        if (byMerchantIdAndYearMonth == null) {
                            PersonalMerchantSettle personalMerchantSettle = new PersonalMerchantSettle();
                            personalMerchantSettle.setMerchantId(entry.getKey());
                            personalMerchantSettle.setYearMonth(dateStr.substring(0, dateStr.lastIndexOf("-")));
                            personalMerchantSettle.setMerchantName(merchant.getMerchantName());
                            if (merchant.getMerchantType() == 1) {
                                SysUser sysUser = sysUserService.selectSysUserById(merchant.getAdminId());
                                if (ObjectUtils.isNotEmpty(sysUser)) {
                                    personalMerchantSettle.setMerchantName(sysUser.getNickName());
                                }
                            }
                            personalMerchantSettle.setMerchantIndex(merchant.getMerchantIndex());
                            personalMerchantSettle.setMerchantType(merchant.getMerchantType());
//                            实际收入
                            personalMerchantSettle.setActualIncome(reserveIncome);
//                            预定服务收入
                            personalMerchantSettle.setReserveIncome(reserveIncome);
                            personalMerchantSettle.setSettleStatus(PersonalSettleStatusEnum.PENDING_SETTLEMENT.getCode());
                            personalMerchantSettle.setCreateBy("1");
                            personalMerchantSettle.setUpdateBy("1");
                            personalMerchantSettle.setCreateTime(LocalDateTime.now());
                            personalMerchantSettle.setUpdateTime(LocalDateTime.now());
                            personalMerchantSettle.setGroupIncome(new BigDecimal(0));
                            //核销次数
                            personalMerchantSettle.setGroupTimes(0);
                            addSettleList.add(personalMerchantSettle);
                        } else {
                            // 更新实际收入(元)
                            byMerchantIdAndYearMonth.setActualIncome(reserveIncome);
//                            预定收入
                            byMerchantIdAndYearMonth.setReserveIncome(reserveIncome);
                            byMerchantIdAndYearMonth.setUpdateTime(LocalDateTime.now());
                            updateSettleList.add(byMerchantIdAndYearMonth);
                        }
                    }
                }
            }
            if (groupSettledOrders != null && groupSettledOrders.size() > 0) {
                //遍历团购数据
                for (Map.Entry<Long, List<OrderVo>> entry : groupSettledOrders.entrySet()) {
                    // 遍历各商家待结算订单金额
                    BigDecimal groupIncome = entry.getValue().stream().map(OrderVo::getGroupIncome).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
                    //核销数量
                    int groupTimes = entry.getValue().stream().mapToInt(OrderVo::getGroupTimes).sum();
                    // 查询商家信息
                    Merchant merchant = merchantService.selectMerchantByMerchantId(entry.getKey());
                    if (merchant == null) {
                        log.error("账单结算统计错误 -- 待结算商家信息异常（缺失）" + entry.getKey().toString());
                    } else {
                        // 查询商家该月是否已存在结算账单记录，若存在，则更新
                        String dateStr = String.valueOf(settleStartDate);
                        PersonalMerchantSettle byMerchantIdAndYearMonth = personalMerchantSettleService.getByMerchantIdAndYearMonth(entry.getKey(), dateStr.substring(0, dateStr.lastIndexOf("-")));
                        if (byMerchantIdAndYearMonth == null) {
                            aBoolean = true;
                            if (addSettleList.size() > 0) {
                                for (PersonalMerchantSettle pm : addSettleList) {
                                    if (pm.getMerchantId().equals(entry.getKey())) {
                                        pm.setGroupIncome(groupIncome);
                                        pm.setActualIncome(pm.getActualIncome().add(groupIncome));
                                        pm.setGroupTimes(groupTimes);
                                        aBoolean = false;
                                    }
                                }
                            }
                            if (aBoolean) {
                                PersonalMerchantSettle personalMerchantSettle = new PersonalMerchantSettle();
                                personalMerchantSettle.setMerchantId(entry.getKey());
                                personalMerchantSettle.setYearMonth(dateStr.substring(0, dateStr.lastIndexOf("-")));
                                personalMerchantSettle.setMerchantName(merchant.getMerchantName());
                                if (merchant.getMerchantType() == 1) {
                                    SysUser sysUser = sysUserService.selectSysUserById(merchant.getAdminId());
                                    if (ObjectUtils.isNotEmpty(sysUser)) {
                                        personalMerchantSettle.setMerchantName(sysUser.getNickName());
                                    }
                                }
                                personalMerchantSettle.setMerchantIndex(merchant.getMerchantIndex());
                                personalMerchantSettle.setMerchantType(merchant.getMerchantType());
//                              实际收入
                                personalMerchantSettle.setActualIncome(groupIncome);
                                personalMerchantSettle.setReserveIncome(new BigDecimal(0));
//                              团购服务核销收入
                                personalMerchantSettle.setGroupIncome(groupIncome);
//                              核销次数
                                personalMerchantSettle.setGroupTimes(groupTimes);
                                personalMerchantSettle.setSettleStatus(PersonalSettleStatusEnum.PENDING_SETTLEMENT.getCode());
                                personalMerchantSettle.setCreateBy("1");
                                personalMerchantSettle.setUpdateBy("1");
                                personalMerchantSettle.setCreateTime(LocalDateTime.now());
                                personalMerchantSettle.setUpdateTime(LocalDateTime.now());
                                personalMerchantSettle.setRemark("定时任务统计月度账单");
                                addSettleList.add(personalMerchantSettle);
                            }
                        } else {
                            Integer integer = new Integer(0);
                            if (updateSettleList.size() > 0) {
                                aBoolean = true;
                                for (PersonalMerchantSettle pms : updateSettleList) {
                                    if (byMerchantIdAndYearMonth.getPersonalMerchantSettleId().equals(pms.getPersonalMerchantSettleId())) {
                                        // 更新实际收入(元)
                                        pms.setActualIncome(pms.getActualIncome().add(groupIncome));
                                        //团购收入
                                        pms.setGroupIncome(groupIncome);
                                        //核销次数
                                        pms.setGroupTimes(groupTimes);
                                        aBoolean = false;
                                    }
                                }
                            }
                            if (aBoolean) {
                                // 更新实际收入(元)
                                byMerchantIdAndYearMonth.setActualIncome(groupIncome);
                                //团购收入
                                byMerchantIdAndYearMonth.setGroupIncome(groupIncome);
                                //核销次数
                                byMerchantIdAndYearMonth.setGroupTimes(groupTimes);
                                byMerchantIdAndYearMonth.setUpdateTime(LocalDateTime.now());
                                updateSettleList.add(byMerchantIdAndYearMonth);
                            }
                        }
                    }
                }
            }
            Boolean aBoolean1 = new Boolean(false);
            // 插入/更新账单结算信息
            if (addSettleList.size() > 0) {
                aBoolean1 = personalMerchantSettleService.saveBatch(addSettleList) != addSettleList.size();
            }
            if (updateSettleList.size() > 0) {
                aBoolean1 = personalMerchantSettleService.updateBatchById(updateSettleList) != updateSettleList.size();
            }
            if (aBoolean1) {
                throw new RuntimeException("个体户账单结算统计失败 -- 批量插入结算记录失败");
            } else {
                log.info("本次无可结算个体户订单");
            }
            taskLog.setTaskResult(1);
        } catch (Exception e) {
            taskLog.setTaskResult(0);
            taskLog.setErrorLog(e.getMessage());
        } finally {
            taskLogService.insertTaskLog(taskLog);
        }
    }
//    public void settle() {
//        TaskLog taskLog = new TaskLog();
//        taskLog.setTaskName("个体户账单结算信息统计");
//        taskLog.setExecutionTime(LocalDateTime.now());
//
//        try {
//            LocalDate currentDate = LocalDate.now();
//            LocalDate lastMonthCurrentDate = currentDate.minusMonths(1);
//            LocalDate settleStartDate = lastMonthCurrentDate.with(TemporalAdjusters.firstDayOfMonth());
//            LocalDate settleEndDate = lastMonthCurrentDate.with(TemporalAdjusters.lastDayOfMonth());
//            log.info("个体户账单结算期间:" + settleStartDate + "~" + settleEndDate);
//            // 查询所有「已完成」「已拒绝退款」订单，以商家进行分组
//            Map<Long, List<Order>> personalSettledOrders = orderService.listPersonalMerchantSettleOrder(settleStartDate, settleEndDate);
//            if (personalSettledOrders != null && personalSettledOrders.size() > 0) {
//                Set<Long> merchantIds = personalSettledOrders.keySet();
//
//                List<PersonalMerchantSettle> addSettleList = new ArrayList<>();
//                List<PersonalMerchantSettle> updateSettleList = new ArrayList<>();
//                List<Long> orderList =  new ArrayList<>();
//                for (Map.Entry<Long, List<Order>> entry : personalSettledOrders.entrySet()) {
//                    // 遍历各商家待结算订单
//                    BigDecimal settleAmount = entry.getValue().stream().map(Order::getShopAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
//                    // 查询商家信息
//                    Merchant merchant = merchantService.selectMerchantByMerchantId(entry.getKey());
//                    if (merchant == null) {
//                        log.error("个体户账单结算统计错误 -- 待结算商家信息异常（缺失）" + entry.getKey().toString());
//                    } else {
//                        // 查询商家该月是否已存在未结算账单记录，若存在，则更新
//                        String dateStr = String.valueOf(settleStartDate);
//                        PersonalMerchantSettle byMerchantIdAndYearMonth = personalMerchantSettleService.getByMerchantIdAndYearMonth(entry.getKey(), dateStr.substring(0, dateStr.lastIndexOf("-")));
//                        if (byMerchantIdAndYearMonth == null) {
//                            PersonalMerchantSettle personalMerchantSettle = new PersonalMerchantSettle();
//                            personalMerchantSettle.setMerchantId(entry.getKey());
//                            personalMerchantSettle.setYearMonth(dateStr.substring(0, dateStr.lastIndexOf("-")));
//                            personalMerchantSettle.setMerchantName(merchant.getMerchantName());
//                            personalMerchantSettle.setMerchantIndex(merchant.getMerchantIndex());
//                            personalMerchantSettle.setActualIncome(settleAmount);
//                            personalMerchantSettle.setSettleStatus(PersonalSettleStatusEnum.PENDING_SETTLEMENT.getCode());
//                            personalMerchantSettle.setCreateBy("1");
//                            personalMerchantSettle.setUpdateBy("1");
//                            addSettleList.add(personalMerchantSettle);
//                        } else {
//                            // 更新实际收入(元)
//                            byMerchantIdAndYearMonth.setActualIncome(settleAmount);
//                            updateSettleList.add(byMerchantIdAndYearMonth);
//                        }
//                    }
//                }
//
//                // 插入/更新个体户账单结算信息
//                if (personalMerchantSettleService.saveBatch(addSettleList) != addSettleList.size()
//                        || personalMerchantSettleService.updateBatchById(updateSettleList) != updateSettleList.size()) {
//                    throw new RuntimeException("个体户账单结算统计失败 -- 批量插入结算记录失败");
//                }
//            } else {
//                log.info("本次无可结算个体户订单");
//            }
//            taskLog.setTaskResult(1);
//        } catch (Exception e) {
//            taskLog.setTaskResult(0);
//            taskLog.setErrorLog(e.getMessage());
//        } finally {
//            taskLogService.insertTaskLog(taskLog);
//        }
//    }
}
