package com.huimv.employment.service.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huimv.employment.common.exception.BizException;
import com.huimv.employment.common.exception.ErrorCode;
import com.huimv.employment.dao.entity.FeEmploymentDraft;
import com.huimv.employment.dao.entity.FeEmploymentOrder;
import com.huimv.employment.dao.entity.FeEnterprise;
import com.huimv.employment.dao.mapper.FeEmploymentDraftMapper;
import com.huimv.employment.dao.mapper.FeEmploymentOrderMapper;
import com.huimv.employment.service.conversation.ConversationService;
import com.huimv.employment.service.enterprise.EnterpriseService;
import com.huimv.employment.service.order.dto.EmploymentOrderItemResponse;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 企业端用工订单查询。
 */
@Service
public class EmploymentOrderService {

    private final FeEmploymentOrderMapper feEmploymentOrderMapper;
    private final FeEmploymentDraftMapper feEmploymentDraftMapper;
    private final ConversationService conversationService;
    private final EnterpriseService enterpriseService;

    public EmploymentOrderService(FeEmploymentOrderMapper feEmploymentOrderMapper,
                                  FeEmploymentDraftMapper feEmploymentDraftMapper,
                                  ConversationService conversationService,
                                  EnterpriseService enterpriseService) {
        this.feEmploymentOrderMapper = feEmploymentOrderMapper;
        this.feEmploymentDraftMapper = feEmploymentDraftMapper;
        this.conversationService = conversationService;
        this.enterpriseService = enterpriseService;
    }

    /**
     * 按会话查询其下草稿已转成正式订单的列表。
     * <p>仅返回已存在订单的草稿；无订单的草稿不出现在结果中。</p>
     */
    public List<EmploymentOrderItemResponse> listByConversation(Long userId, Long conversationId) {
        conversationService.requireOwned(userId, conversationId);
        FeEnterprise enterprise = enterpriseService.findEnterpriseByUserId(userId);
        if (enterprise == null) {
            throw new BizException(ErrorCode.BAD_REQUEST, "请先完成企业登记");
        }

        List<FeEmploymentDraft> drafts = feEmploymentDraftMapper.selectList(
                new LambdaQueryWrapper<FeEmploymentDraft>()
                        .eq(FeEmploymentDraft::getConversationId, conversationId)
                        .eq(FeEmploymentDraft::getEnterpriseId, enterprise.getId())
                        .orderByAsc(FeEmploymentDraft::getId));
        if (drafts == null || drafts.isEmpty()) {
            return Collections.emptyList();
        }

        List<Long> draftIds = new ArrayList<>(drafts.size());
        for (FeEmploymentDraft draft : drafts) {
            if (draft.getId() != null) {
                draftIds.add(draft.getId());
            }
        }
        if (draftIds.isEmpty()) {
            return Collections.emptyList();
        }

        List<FeEmploymentOrder> orders = feEmploymentOrderMapper.selectList(
                new LambdaQueryWrapper<FeEmploymentOrder>()
                        .eq(FeEmploymentOrder::getEnterpriseId, enterprise.getId())
                        .in(FeEmploymentOrder::getDraftId, draftIds)
                        .orderByDesc(FeEmploymentOrder::getCreateTime)
                        .orderByDesc(FeEmploymentOrder::getId));
        if (orders == null || orders.isEmpty()) {
            return Collections.emptyList();
        }

        List<EmploymentOrderItemResponse> result = new ArrayList<>(orders.size());
        for (FeEmploymentOrder order : orders) {
            result.add(toItem(order));
        }
        return result;
    }

    private static EmploymentOrderItemResponse toItem(FeEmploymentOrder order) {
        EmploymentOrderItemResponse item = new EmploymentOrderItemResponse();
        item.setDraftId(order.getDraftId());
        item.setOrderId(order.getId());
        item.setOrderNo(order.getOrderNo());
        item.setTitle(order.getTitle());
        item.setWorkerCount(order.getWorkerCount());
        item.setWorkDays(order.getWorkDays());
        item.setWorkType(order.getWorkType());
        item.setWorkLocation(order.getWorkLocation());
        item.setWorkStartDate(order.getWorkStartDate());
        item.setWorkEndDate(order.getWorkEndDate());
        item.setOrderStatus(order.getOrderStatus());
        item.setCurrentStepCode(order.getCurrentStepCode());
        item.setRegisteredCount(order.getRegisteredCount());
        item.setPendingCount(order.getPendingCount());
        item.setAbnormalCount(order.getAbnormalCount());
        item.setTotalOutflow(order.getTotalOutflow());
        item.setSelectedPlanId(order.getSelectedPlanId());
        item.setCreateTime(order.getCreateTime());
        item.setUpdateTime(order.getUpdateTime());
        return item;
    }
}
