package com.zbf.quartz.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbf.system.domain.TMiStock;
import com.zbf.system.service.ITMiStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 库存库龄定时任务
 */
@Slf4j
@Component("Inventory")
public class InventoryTask {


    @Autowired
    private ITMiStockService itMiStockService;


    /**
     * 超期 过保检查
     */
    public void InventoryTask() {
        // 库存表
        LambdaQueryWrapper<TMiStock> queryWrapper = new LambdaQueryWrapper<>();
        // 查询过滤
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<TMiStock> tMiStocks = itMiStockService.list(queryWrapper);
        tMiStocks.forEach(tMiStock -> {
            Long goodsAge = tMiStock.getGoodsAge();
            String wareDateString = tMiStock.getWareDate();
            tMiStock.setCheckDate(new Date());

            if (goodsAge != null) {
                tMiStock.setGoodsAge(goodsAge + 1);
            } else if (wareDateString != null) {
                try {
                    Date wareDate = dateFormat.parse(wareDateString);
                    LocalDate wareLocalDate = wareDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    LocalDate currentLocalDate = LocalDate.now();
                    long daysBetween = ChronoUnit.DAYS.between(wareLocalDate, currentLocalDate);
                    tMiStock.setGoodsAge(daysBetween);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 批量更新库存信息
        itMiStockService.updateBatchById(tMiStocks);
        log.info("更新了: {}", tMiStocks.size());

        LambdaQueryWrapper<TMiStock> eq = new LambdaQueryWrapper<>();
        eq.isNotNull(TMiStock::getPeriod);
        List<TMiStock> tMiStock = itMiStockService.list(eq);

        // 过滤出period字段不为空且不仅包含空格的TMiStock对象
        List<TMiStock> filteredStocks = tMiStock.stream()
                .filter(t -> t.getPeriod() != null && !t.getPeriod().toString().trim().isEmpty())
                .collect(Collectors.toList());
        LocalDate today = LocalDate.now();
        filteredStocks.forEach(t -> {
            if (t.getDueDate() != null) {
                int mark = Integer.parseInt(t.getMark());
                t.setMark(String.valueOf(mark + 1));
                return;
            }

            LocalDate baseDate = t.getProductionDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            BigDecimal period = t.getPeriod();
            String periodUnit = t.getPeriodUnit();

            int fullUnits = period.intValue();
            BigDecimal fractionalUnit = period.remainder(BigDecimal.ONE);

            LocalDate dateAfterFullUnits;
            if (periodUnit.equals("月")) {
                dateAfterFullUnits = baseDate.plusMonths(fullUnits);
            } else if (periodUnit.equals("年")) {
                dateAfterFullUnits = baseDate.plusYears(fullUnits);
            } else {
                dateAfterFullUnits = baseDate.plusDays(fullUnits);
            }

            long daysForFullUnits = ChronoUnit.DAYS.between(baseDate, dateAfterFullUnits);

            double averageDaysPerUnit;
            if (periodUnit.equals("月")) {
                averageDaysPerUnit = 30.42;
            } else if (periodUnit.equals("年")) {
                averageDaysPerUnit = 365;
            } else {
                averageDaysPerUnit = 1;
            }

            double fractionalDays = fractionalUnit.doubleValue() * averageDaysPerUnit;
            long totalDays = Math.round(daysForFullUnits + fractionalDays);

            LocalDate expirationDate = baseDate.plusDays(totalDays);

            if (today.isAfter(expirationDate)) {
                log.info("超过保质期的数据有: ID={}, 商品名={}, 生产日期={}", t.getId(), t.getGoodsName(), t.getProductionDate());
                t.setDueDate(Date.from(expirationDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
                long daymark = ChronoUnit.DAYS.between(t.getProductionDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), today);
                t.setMark(String.valueOf(daymark));
            }
        });
        // 如果有需要更新的过期库存，则批量更新
        if (!filteredStocks.isEmpty()) {
            itMiStockService.updateBatchById(filteredStocks);
        }
    }
}
