package net.lab1024.sa.admin.module.business.wms.base.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import net.lab1024.sa.admin.module.business.wms.base.address.domain.vo.AddressExcelVO;
import net.lab1024.sa.admin.module.business.wms.base.address.domain.vo.AddressVO;
import net.lab1024.sa.admin.module.business.wms.base.item.dao.ItemDao;
import net.lab1024.sa.admin.module.business.wms.base.item.domain.entity.ItemEntity;
import net.lab1024.sa.admin.module.business.wms.base.item.domain.form.ItemQueryForm;
import net.lab1024.sa.admin.module.business.wms.base.item.domain.form.ItemSelect;
import net.lab1024.sa.admin.module.business.wms.base.item.domain.vo.ItemVO;
import net.lab1024.sa.admin.module.business.wms.base.item.domain.vo.ItemsExcelVO;
import net.lab1024.sa.admin.module.business.wms.base.item.manager.ItemManager;
import net.lab1024.sa.admin.module.business.wms.base.item.service.ItemQueryService;
import net.lab1024.sa.admin.module.business.wms.excel.ExportTaskService;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.util.SmartExcelUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.module.support.dict.constant.DictConst;
import net.lab1024.sa.base.module.support.dict.service.DictService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ItemQueryServiceImpl implements ItemQueryService {

    @Resource
    private ItemDao itemDao;

    @Resource
    private ItemManager itemManager;

    @Resource
    private DictService dictService;

    @Resource
    private ExportTaskService exportTaskService;

    /**
     * 分页查询
     *
     * @param queryForm 入参
     * @return PageResult<ItemVO>
     */
    public PageResult<ItemVO> queryPage(ItemQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<ItemVO> list = itemDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 物料下拉查询
     *
     * @param itemSelect 入参
     * @return List<ItemEntity>
     */
    public List<ItemEntity> queryItem(ItemSelect itemSelect) {
        LambdaQueryWrapper<ItemEntity> queryWrapper = new LambdaQueryWrapper<>();
        //是否启用
        if (itemSelect.getDisabledFlag() != null) {
            queryWrapper.eq(ItemEntity::getDisabledFlag, itemSelect.getDisabledFlag());
        }
        return itemManager.list(queryWrapper);
    }

    /**
     * 根据物料id集合查询物料信息
     *
     * @param itemIdList 客户id集合
     * @return Map<Long, AreaEntity>
     */
    public Map<Long, ItemEntity> queryByItemIdsToMap(List<Long> itemIdList) {
        if (CollectionUtils.isEmpty(itemIdList)) {
            return Collections.emptyMap();
        }
        itemIdList = itemIdList.stream().filter(Objects::nonNull).distinct().toList();
        Map<Long, ItemEntity> itemMap = Maps.newHashMap();
        for (Long itemId : itemIdList) {
            ItemEntity item = itemManager.queryItem(itemId);
            if (item != null) {
                itemMap.put(itemId, item);
            }
        }
        return itemMap;
    }

    /**
     * 根据物料编码查询
     *
     * @param itemCode 物料编码
     * @return ItemEntity
     */
    public ItemEntity queryByItemCode(String itemCode) {
        if (StringUtils.isBlank(itemCode)) {
            return null;
        }
        LambdaQueryWrapper<ItemEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ItemEntity::getItemCode, itemCode);
        return itemManager.getOne(queryWrapper);
    }

    /**
     * 根据物料编码集合查询物料信息
     *
     * @param itemCodes 物料编码集合
     * @return List<ItemEntity>
     */
    public List<ItemEntity> queryByItemCodes(List<String> itemCodes) {
        if (CollectionUtils.isEmpty(itemCodes)) {
            return Collections.emptyList();
        }
        //去重
        itemCodes = itemCodes.stream().filter(Objects::nonNull).distinct().toList();
        //查询物料
        LambdaQueryWrapper<ItemEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ItemEntity::getItemCode, itemCodes);
        return itemManager.list(queryWrapper);
    }

    /**
     * 根据物料编码集合查询物料信息
     *
     * @param itemCodes 物料集合
     * @return Map<String, ItemEntity>
     */
    public Map<String, ItemEntity> queryByItemCodesToMap(List<String> itemCodes) {
        if (CollectionUtils.isEmpty(itemCodes)) {
            return Collections.emptyMap();
        }
        //查询物料
        List<ItemEntity> itemList = queryByItemCodes(itemCodes);
        //封装成map
        Map<String, ItemEntity> itemMap = Maps.newHashMap();
        for (ItemEntity item : itemList) {
            itemMap.put(item.getItemCode(), item);
        }
        return itemMap;
    }

    /**
     * 物料导出
     *
     * @return List<LocationsExcelVO>
     */
    public List<ItemsExcelVO> queryItemsExcelVO() {
        List<ItemEntity> itemsList = itemManager.list();
        return itemsList.stream()
                .map(item ->
                        ItemsExcelVO.builder()
                                .itemCode(item.getItemCode())
                                .itemName(item.getItemName())
                                .itemType(dictService.getDictDataLabel(DictConst.ITEM_TYPE.getValue(), item.getItemType()))
                                .unit(dictService.getDictDataLabel(DictConst.ITEM_UNIT.getValue(), item.getUnit()))
                                .disabledFlag(item.getDisabledFlag() ? "启用" : "禁用")
                                .build()
                )
                .collect(Collectors.toList());
    }

    @Override
    public long itemCount(ItemQueryForm queryForm) {
        LambdaQueryWrapper<ItemEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (queryForm.getDisabledFlag() != null) {
            queryWrapper.eq(ItemEntity::getDisabledFlag, queryForm.getDisabledFlag());
        }
        if (queryForm.getItemId() != null) {
            queryWrapper.eq(ItemEntity::getItemId, queryForm.getItemId());
        }
        return itemManager.count(queryWrapper);
    }

    public void exportItem(String taskId, ItemQueryForm queryForm, HttpServletResponse response) {
        try {
            SmartExcelUtil.batchExportExcel(
                    response,
                    "物料信息.xlsx",
                    "物料信息",
                    ItemsExcelVO.class,
                    taskId,
                    itemCount(queryForm),
                    (lastId, pageSize) -> itemDao.listByCursor(lastId, pageSize, queryForm),
                    item -> ItemsExcelVO.builder()
                            .itemCode(item.getItemCode())
                            .itemName(item.getItemName())
                            .itemType(dictService.getDictDataLabel(DictConst.ITEM_TYPE.getValue(), item.getItemType()))
                            .unit(dictService.getDictDataLabel(DictConst.ITEM_UNIT.getValue(), item.getUnit()))
                            .disabledFlag(item.getDisabledFlag() ? "启用" : "禁用")
                            .build(),
                    ItemVO::getItemId,
                    2000,
                    (processed, progress) -> exportTaskService.updateProgress(taskId, progress)
            );
        } catch (Exception e) {
            exportTaskService.updateProgress(taskId, -1);
        } finally {
            exportTaskService.updateProgress(taskId, 100);
        }
    }
}
