package com.huimv.employment.service.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huimv.employment.dao.entity.FeDraftWorkItem;
import com.huimv.employment.dao.entity.FeOrderWorkItem;
import com.huimv.employment.dao.mapper.FeOrderWorkItemMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 订单用工明细读写（确认快照 fe_order_work_item）。
 */
@Service
public class OrderWorkItemService {

    private final FeOrderWorkItemMapper feOrderWorkItemMapper;

    public OrderWorkItemService(FeOrderWorkItemMapper feOrderWorkItemMapper) {
        this.feOrderWorkItemMapper = feOrderWorkItemMapper;
    }

    public List<FeOrderWorkItem> listByOrderId(Long orderId) {
        if (orderId == null) {
            return Collections.emptyList();
        }
        return feOrderWorkItemMapper.selectList(new LambdaQueryWrapper<FeOrderWorkItem>()
                .eq(FeOrderWorkItem::getOrderId, orderId)
                .orderByAsc(FeOrderWorkItem::getSortOrder)
                .orderByAsc(FeOrderWorkItem::getId));
    }

    /**
     * 草稿确认时将用工明细复制到订单快照表。
     */
    public List<FeOrderWorkItem> copyFromDraftItems(Long orderId, List<FeDraftWorkItem> draftItems, LocalDateTime now) {
        if (orderId == null) {
            return Collections.emptyList();
        }
        List<FeOrderWorkItem> saved = new ArrayList<>();
        if (draftItems == null || draftItems.isEmpty()) {
            return saved;
        }
        int sort = 0;
        for (FeDraftWorkItem draftItem : draftItems) {
            FeOrderWorkItem item = new FeOrderWorkItem();
            item.setOrderId(orderId);
            item.setDraftItemId(draftItem.getId());
            item.setGroupNo(StringUtils.hasText(draftItem.getGroupNo())
                    ? draftItem.getGroupNo()
                    : String.format("grp_%02d", sort + 1));
            item.setSortOrder(draftItem.getSortOrder() != null ? draftItem.getSortOrder() : sort);
            item.setJobType(draftItem.getJobType());
            item.setWorkerCount(draftItem.getWorkerCount());
            item.setWorkDays(draftItem.getWorkDays());
            item.setWorkLocation(draftItem.getWorkLocation());
            item.setSettlementCycle(draftItem.getSettlementCycle());
            item.setUnitAmount(draftItem.getUnitAmount());
            item.setTotalAmount(draftItem.getTotalAmount());
            item.setWorkContent(draftItem.getWorkContent());
            item.setWorkStartDate(draftItem.getWorkStartDate());
            item.setWorkEndDate(draftItem.getWorkEndDate());
            item.setCreateTime(now);
            item.setUpdateTime(now);
            item.setDelFlag(0);
            feOrderWorkItemMapper.insert(item);
            saved.add(item);
            sort++;
        }
        return saved;
    }

    public int sumWorkerCount(List<FeOrderWorkItem> items) {
        int sum = 0;
        if (items == null) {
            return 0;
        }
        for (FeOrderWorkItem item : items) {
            if (item.getWorkerCount() != null && item.getWorkerCount() > 0) {
                sum += item.getWorkerCount();
            }
        }
        return sum;
    }

    public int sumWorkerCountByOrderId(Long orderId) {
        return sumWorkerCount(listByOrderId(orderId));
    }

    public BigDecimal sumTotalAmount(List<FeOrderWorkItem> items) {
        BigDecimal sum = BigDecimal.ZERO;
        if (items == null) {
            return sum;
        }
        for (FeOrderWorkItem item : items) {
            if (item.getTotalAmount() != null) {
                sum = sum.add(item.getTotalAmount());
            }
        }
        return sum;
    }

    public FeOrderWorkItem firstItem(List<FeOrderWorkItem> items) {
        return items != null && !items.isEmpty() ? items.get(0) : null;
    }

    public FeOrderWorkItem firstByOrderId(Long orderId) {
        return firstItem(listByOrderId(orderId));
    }

    public LocalDate maxWorkEndDate(List<FeOrderWorkItem> items) {
        LocalDate max = null;
        if (items == null) {
            return null;
        }
        for (FeOrderWorkItem item : items) {
            if (item.getWorkEndDate() == null) {
                continue;
            }
            if (max == null || item.getWorkEndDate().isAfter(max)) {
                max = item.getWorkEndDate();
            }
        }
        return max;
    }

    public BigDecimal primaryWorkDays(List<FeOrderWorkItem> items) {
        FeOrderWorkItem first = firstItem(items);
        return first != null ? first.getWorkDays() : null;
    }

    /**
     * 更新单条用工明细的计划起止日。
     */
    public void updateWorkDates(Long itemId, LocalDate workStartDate, LocalDate workEndDate, LocalDateTime now) {
        if (itemId == null) {
            return;
        }
        FeOrderWorkItem update = new FeOrderWorkItem();
        update.setId(itemId);
        update.setWorkStartDate(workStartDate);
        update.setWorkEndDate(workEndDate);
        update.setUpdateTime(now != null ? now : LocalDateTime.now());
        feOrderWorkItemMapper.updateById(update);
    }
}
