package net.lab1024.sa.admin.module.business.wms.base.address.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 lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.business.wms.base.address.dao.AddressDao;
import net.lab1024.sa.admin.module.business.wms.base.address.domain.entity.AddressEntity;
import net.lab1024.sa.admin.module.business.wms.base.address.domain.form.AddressQueryForm;
import net.lab1024.sa.admin.module.business.wms.base.address.domain.form.AddressSelect;
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.address.manager.AddressManager;
import net.lab1024.sa.admin.module.business.wms.base.address.service.AddressQueryService;
import net.lab1024.sa.admin.module.business.wms.excel.ExportTaskService;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartExcelUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AddressQueryServiceImpl implements AddressQueryService {

    @Resource
    private AddressDao addressDao;

    @Resource
    private AddressManager addressManager;

    @Resource
    private ExportTaskService exportTaskService;

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

    /**
     * 地址下拉分页查询
     *
     * @param addressSelect 入参
     * @return List<AddressEntity>
     */
    public PageResult<AddressVO> queryAddress(AddressSelect addressSelect) {
        Page<?> page = SmartPageUtil.convert2PageQuery(addressSelect);
        List<AddressVO> list = addressDao.queryAddress(page, addressSelect);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 根据地址id集合查询地址信息
     *
     * @param addressIdList 地址id集合
     * @return Map<Long, AreaEntity>
     */
    public Map<Long, AddressEntity> queryByAddressIdsToMap(List<Long> addressIdList) {
        if (CollectionUtils.isEmpty(addressIdList)) {
            return Collections.emptyMap();
        }
        // 去重
        addressIdList = addressIdList.stream().filter(Objects::nonNull).distinct().toList();
        //封装map
        Map<Long, AddressEntity> addressMap = Maps.newHashMap();
        for (Long addressId : addressIdList) {
            AddressEntity address = addressManager.queryAddress(addressId);
            if (address != null) {
                addressMap.put(addressId, address);
            }
        }
        return addressMap;
    }

    /**
     * 根据地址name集合查询地址信息
     *
     * @param addressNameList 地址name集合
     * @return List<AddressEntity>
     */
    public List<AddressEntity> queryByNames(List<String> addressNameList) {
        if (CollectionUtils.isEmpty(addressNameList)) {
            return Collections.emptyList();
        }
        //去重
        addressNameList = addressNameList.stream().filter(Objects::nonNull).distinct().toList();
        //查询收获单位
        LambdaQueryWrapper<AddressEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(AddressEntity::getName, addressNameList);
        return addressManager.list(queryWrapper);
    }


    /**
     * 根据地址name集合查询地址信息
     *
     * @param addressNameList 地址name集合
     * @return Map<Long, AddressEntity>
     */
    public Map<String, AddressEntity> queryByNamesToMap(List<String> addressNameList) {
        if (CollectionUtils.isEmpty(addressNameList)) {
            return Collections.emptyMap();
        }
        //查询收获单位
        List<AddressEntity> addressList = queryByNames(addressNameList);
        //封装map
        Map<String, AddressEntity> addressMap = Maps.newHashMap();
        for (AddressEntity address : addressList) {
            addressMap.put(address.getName(), address);
        }
        return addressMap;
    }

    public List<AddressExcelVO> queryAddressExcel() {
        System.out.println("开始读取数据...");
        long startTime = System.currentTimeMillis();
        List<AddressEntity> addressList = addressManager.list();
        List<AddressExcelVO> excelData = addressList.stream()
                .map(address ->
                        AddressExcelVO.builder()
                                .name(address.getName())
                                .person(address.getPerson())
                                .telephone(address.getTelephone())
                                .address(address.getAddress())
                                .build()
                )
                .collect(Collectors.toList());
        long endTime = System.currentTimeMillis();
        System.out.println("查询，共" + excelData.size() + "条数据，耗时：" + (endTime - startTime) + "ms");
        return excelData;
    }

    public List<AddressExcelVO> queryAddressExcel2(String taskId) {
        System.out.println("开始读取地址数据...");
        long startTime = System.currentTimeMillis();
        List<AddressExcelVO> excelData = new ArrayList<>();
        //总条数
        long total = addressManager.count();
        long lastId = 0;  // 初始化为最小ID-1
        int pageSize = 2000;  // 根据测试调整
        //进度条
        long processed = 0;
        while (true) {
            List<AddressVO> batch = addressDao.listByCursor(lastId, pageSize,null);
            if (batch.isEmpty()) {
                break;
            }
            for (AddressVO address : batch) {
                AddressExcelVO excelVO = AddressExcelVO.builder()
                        .name(address.getName())
                        .person(address.getPerson())
                        .telephone(address.getTelephone())
                        .address(address.getAddress())
                        .build();
                excelData.add(excelVO);
            }
            lastId = batch.stream().mapToLong(AddressVO::getAddressId).max().orElse(0);
            processed += batch.size();

            //计算进度条
            long progress = processed * 100 / total;
            exportTaskService.updateProgress(taskId, progress);
            System.out.println("已处理：" + processed + "条数据，进度：" + progress + "%");
        }
        exportTaskService.updateProgress(taskId, 100);
        long endTime = System.currentTimeMillis();
        System.out.println("查询，共" + excelData.size() + "条数据，耗时：" + (endTime - startTime) + "ms");
        return excelData;
    }

    /**
     * 导出收货地址
     */
    @Transactional(readOnly = true)
    public List<AddressExcelVO> queryAddressExcel3() {
        List<AddressExcelVO> list = new ArrayList<>();
        try {
            try (Cursor<AddressVO> cursor = addressDao.selectAllByCursor()) {
                cursor.forEach(address -> {
                    AddressExcelVO excelVO = AddressExcelVO.builder()
                            .name(address.getName())
                            .person(address.getPerson())
                            .telephone(address.getTelephone())
                            .address(address.getAddress())
                            .build();
                    list.add(excelVO);
                });
            }
        } catch (Exception e) {
            throw new BusinessException("导出失败");
        }
        return list;
    }

    @Override
    public long addressCount(AddressQueryForm queryForm) {
        LambdaQueryWrapper<AddressEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (queryForm.getAddressId() != null) {
            queryWrapper.eq(AddressEntity::getAddressId, queryForm.getAddressId());
        }
        return addressManager.count(queryWrapper);
    }

    public void exportAddress(String taskId,AddressQueryForm queryForm, HttpServletResponse response){
        try {
            SmartExcelUtil.batchExportExcel(
                    response,
                    "收货地址信息.xlsx",
                    "收货地址信息",
                    AddressExcelVO.class,
                    taskId,
                    addressCount(queryForm),
                    (lastId, pageSize) -> addressDao.listByCursor(lastId, pageSize,queryForm),
                    address -> AddressExcelVO.builder()
                            .name(address.getName())
                            .person(address.getPerson())
                            .telephone(address.getTelephone())
                            .address(address.getAddress())
                            .build(),
                    AddressVO::getAddressId,
                    2000,
                    (processed, progress) -> exportTaskService.updateProgress(taskId, progress)
            );
        } catch (Exception e) {
            exportTaskService.updateProgress(taskId, -1);
        } finally {
            exportTaskService.updateProgress(taskId, 100);
        }
    }
}
