package com.ruoyi.ibs.task.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ibs.task.domain.dto.MarketTaskDTO;
import com.ruoyi.ibs.task.domain.entity.MarketTask;
import com.ruoyi.ibs.task.domain.entity.MarketTaskList;
import com.ruoyi.ibs.task.domain.vo.MarketTaskVO;
import com.ruoyi.ibs.task.mapper.MarketTaskListMapper;
import com.ruoyi.ibs.task.mapper.MarketTaskMapper;
import com.ruoyi.ibs.task.service.MarketTaskService;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutorService;

/**
 * 营销任务Service业务层处理
 *
 */
@Service
@Slf4j
public class MarketTaskServiceImpl implements MarketTaskService {

    @Resource
    private MarketTaskMapper marketTaskMapper;

    @Resource
    private MarketTaskListMapper marketTaskListMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource(name = "excelImportExecutor")
    private ExecutorService executorService;

    /**
     * 异步创建营销任务
     * 1、创建营销任务，并返回营销任务ID，设置创建状态
     * 2、异步线程开启->
     *    校验：去重
     *    批量插入
     *    更新创建状态
     * 3、异常处理
     *    删除已插入的信息
     *    更新创建状态
     */
    @Override
    public String createMarketTaskAsync(MarketTaskDTO marketTaskDTO, MultipartFile file) {
        MarketTask marketTask = new MarketTask();
        String uuid = UUID.randomUUID().toString();
        marketTask.setId(uuid);
        marketTask.setMarketName(marketTaskDTO.getMarketName());
        marketTask.setIsFeedback(marketTaskDTO.getIsFeedback());
        marketTask.setEndTime(marketTaskDTO.getEndTime());
        marketTask.setCreateStatus("0");
        marketTask.setCreateBy(SecurityUtils.getUsername());
        marketTask.setCreateTime(new Date());
        marketTask.setDeptId(String.valueOf(SecurityUtils.getDeptId()));
        marketTaskMapper.insert(marketTask);
        //异步导入
        executorService.submit(() -> doImport(marketTask, file));
        return uuid;
    }

    @Override
    public String getCreateStatus(String id) {
        return marketTaskMapper.selectCreateStatus(id);
    }

    /**
     * 编辑营销任务——包括创建失败时重新导入
     */
    @Override
    public String editMarketTask(MarketTask marketTask, MultipartFile file) {
        marketTask.setUpdateBy(SecurityUtils.getUsername());
        marketTask.setUpdateTime(new Date());
        marketTaskMapper.updateById(marketTask);
        if (file == null || file.isEmpty()){
            return "编辑成功";
        }
        //文件不为空，则异步执行导入
        executorService.submit(() -> doImport(marketTask, file));
        return marketTask.getId();
    }

    /**
     * 获取营销任务列表
     */
    @Override
    public List<MarketTaskVO> getMarketTasks(String marketTaskName) {
        return marketTaskMapper.selectMarketTasks(SecurityUtils.userRole(), SecurityUtils.getDeptId(), marketTaskName);
    }

    /**
     * 异步导入
     */
    private void doImport(MarketTask marketTask, MultipartFile file) {
        try {
            List<MarketTaskList> marketTaskLists = EasyExcel.read(file.getInputStream()).head(MarketTaskList.class).sheet().doReadSync();
            //全局校验+去重
            if (marketTaskLists.isEmpty()){
                throw new ServiceException("导入列表为空！");
            }
            // 判断是否为增量导入
            boolean isIncrementalImport = checkIncrementalImport(marketTask);
            // 如果是增量导入，需要获取已存在的数据用于去重校验
            Set<String> existingRelations = new HashSet<>();
            if (isIncrementalImport) {
                existingRelations = getExistingRelations(marketTask.getId());
            }
            Set<String> uniqueRelations = new HashSet<>(existingRelations);
            List<MarketTaskList> tempList = new ArrayList<>();
            for (MarketTaskList item : marketTaskLists) {
                String relationKey = item.getCustId() + "_" + item.getUserName();
                if (uniqueRelations.add(relationKey)) {
                    tempList.add(item);
                }
            }
            marketTaskLists = tempList;
            //设置其他信息
            marketTaskLists.forEach(marketTaskList -> {
                marketTaskList.setMarketTaskId(marketTask.getId());
                if ("个人".equals(marketTaskList.getCustType())) {
                    marketTaskList.setCustType("0");
                } else if ("商户".equals(marketTaskList.getCustType())) {
                    marketTaskList.setCustType("1");
                } else if ("企业".equals(marketTaskList.getCustType())) {
                    marketTaskList.setCustType("2");
                }
                SysUser user = sysUserMapper.selectUserByUserName(marketTaskList.getUserName());
                if (user == null){
                    marketTaskList.setImportStatus("2");
                    marketTaskList.setFailureReason("该柜员不存在");
                }else {
                    marketTaskList.setDeptId(String.valueOf(user.getDeptId()));
                    marketTaskList.setImportStatus("1");
                    marketTaskList.setNickName(user.getNickName());
                }
                marketTaskList.setStatus("0");
            });
            //批量插入
            batchInsertMarketTaskList(marketTaskLists);
            marketTask.setCreateStatus("1");
            marketTaskMapper.updateById(marketTask);
        }catch (Exception e){
            marketTask.setCreateStatus("2");
            marketTaskMapper.updateById(marketTask);
            log.error("营销任务名单导入失败，任务ID：{}", marketTask.getId(), e);
            throw new ServiceException("营销任务名单导入失败: " + e.getMessage());
        }
    }

    /**
     * 检查是否为增量导入
     * @param marketTask 营销任务
     * @return true:增量导入 false:上次导入失败后重新导入
     */
    private boolean checkIncrementalImport(MarketTask marketTask) {
        String createStatus = marketTaskMapper.selectCreateStatus(marketTask.getId());
        return "1".equals(createStatus);
    }

    /**
     * 获取已存在的管户关系
     * @param marketTaskId 营销任务ID
     * @return 已存在的管户关系集合
     */
    private Set<String> getExistingRelations(String marketTaskId) {
        Set<String> existingRelations = new HashSet<>();
        QueryWrapper<MarketTaskList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("market_task_id", marketTaskId);
        queryWrapper.eq("import_status", "1");
        List<MarketTaskList> existingList = marketTaskListMapper.selectList(queryWrapper);
        for (MarketTaskList item : existingList) {
            String relationKey = item.getCustId() + "_" + item.getUserName();
            existingRelations.add(relationKey);
        }
        return existingRelations;
    }

    /**
     * 批量插入营销名单
     * @param marketTaskLists 营销名单列表
     */
    private void batchInsertMarketTaskList(List<MarketTaskList> marketTaskLists) {
        int batchSize = 1000;
        for (int i = 0; i < marketTaskLists.size(); i += batchSize){
            int endIndex = Math.min(i + batchSize, marketTaskLists.size());
            List<MarketTaskList> batchList = marketTaskLists.subList(i, endIndex);
            marketTaskListMapper.batchInsertMarketTaskList(batchList);
        }
    }

}
