package net.lab1024.sa.admin.module.business.wms.task.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import net.lab1024.sa.admin.module.business.wms.base.item.domain.entity.ItemEntity;
import net.lab1024.sa.admin.module.business.wms.base.item.service.ItemQueryService;
import net.lab1024.sa.admin.module.business.wms.inventory.itemKey.domain.entity.ItemKeyEntity;
import net.lab1024.sa.admin.module.business.wms.inventory.itemKey.service.ItemKeyQueryService;
import net.lab1024.sa.admin.module.business.wms.task.dao.TaskDao;
import net.lab1024.sa.admin.module.business.wms.task.domain.entity.TaskEntity;
import net.lab1024.sa.admin.module.business.wms.task.domain.form.TaskQueryForm;
import net.lab1024.sa.admin.module.business.wms.task.domain.vo.TaskVO;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class TaskQueryService {

    @Resource
    private TaskDao taskDao;

    @Resource
    private ItemQueryService itemQueryService;

    @Resource
    private ItemKeyQueryService itemKeyQueryService;

    /**
     * 分页查询
     */
    public PageResult<TaskVO> queryPage(TaskQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<TaskVO> list = taskDao.queryPage(page, queryForm);

        // 查询物料属性
        List<Long> itemKeyIds = list.stream().map(TaskVO::getItemKeyId).toList();
        Map<Long, ItemKeyEntity> itemKeyMap = itemKeyQueryService.queryByItemKeyIds(itemKeyIds);

        //查询物料
        List<Long> itemIds = itemKeyMap.values().stream().map(ItemKeyEntity::getItemId).toList();
        Map<Long, ItemEntity> itemMap = itemQueryService.queryByItemIdsToMap(itemIds);

        list.forEach(TaskVO -> {
            ItemKeyEntity itemKey = itemKeyMap.get(TaskVO.getItemKeyId());
            if (itemKey != null) {
                ItemEntity item = itemMap.get(itemKey.getItemId());
                if (item != null) {
                    TaskVO.setItemCode(item.getItemCode());
                    TaskVO.setItemName(item.getItemName());
                }
            }
        });

        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 根据任务ID集合查询
     * @param taskIds 任务ID集合
     * @return List<TaskEntity>
     */
    public List<TaskEntity> queryByTaskIds(List<Long> taskIds) {
        return taskDao.selectBatchIds(taskIds);
    }


}
