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 com.huimv.employment.service.draft.dto.DraftWorkerGroupItem;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
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));
    }

    /**
     * 转为与草稿详情一致的 {@code worker_groups} 结构（字段名 work_type / work_location / settlement_mode）。
     */
    public List<DraftWorkerGroupItem> toApiGroups(List<FeOrderWorkItem> items) {
        List<DraftWorkerGroupItem> groups = new ArrayList<>();
        if (items == null) {
            return groups;
        }
        for (FeOrderWorkItem item : items) {
            groups.add(toApiGroup(item));
        }
        return groups;
    }

    public List<DraftWorkerGroupItem> toApiGroupsByOrderId(Long orderId) {
        return toApiGroups(listByOrderId(orderId));
    }

    public DraftWorkerGroupItem toApiGroup(FeOrderWorkItem item) {
        DraftWorkerGroupItem group = new DraftWorkerGroupItem();
        if (item == null) {
            return group;
        }
        group.setGroupId(item.getGroupNo());
        group.setJobType(item.getJobType());
        group.setWorkerCount(item.getWorkerCount());
        group.setWorkDays(item.getWorkDays());
        group.setRegion(item.getWorkLocation());
        group.setSettlementCycle(item.getSettlementCycle());
        group.setUnitAmount(item.getUnitAmount());
        group.setTotalAmount(item.getTotalAmount());
        group.setWorkContent(item.getWorkContent());
        group.setWorkStartDate(item.getWorkStartDate());
        group.setWorkEndDate(item.getWorkEndDate());
        return group;
    }

    /**
     * 草稿确认时将用工明细复制到订单快照表。
     */
    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 LocalDateTime maxWorkEndDate(List<FeOrderWorkItem> items) {
        LocalDateTime 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, LocalDateTime workStartDate, LocalDateTime 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);
    }
}
