package com.ruoyi.info.collection.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.CcdiCustFmyRelation;
import com.ruoyi.info.collection.domain.dto.CcdiCustFmyRelationAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiCustFmyRelationEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiCustFmyRelationQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiCustFmyRelationExcel;
import com.ruoyi.info.collection.domain.vo.CcdiCustFmyRelationVO;
import com.ruoyi.info.collection.domain.vo.CustFmyRelationImportFailureVO;
import com.ruoyi.info.collection.mapper.CcdiCustFmyRelationMapper;
import com.ruoyi.info.collection.service.ICcdiCustFmyRelationImportService;
import com.ruoyi.info.collection.service.ICcdiCustFmyRelationService;
import com.ruoyi.info.collection.utils.EasyExcelUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 信贷客户家庭关系Service实现
 *
 * @author ruoyi
 * @date 2026-02-11
 */
@Service
public class CcdiCustFmyRelationServiceImpl implements ICcdiCustFmyRelationService {

    @Resource
    private CcdiCustFmyRelationMapper mapper;

    @Resource
    private ICcdiCustFmyRelationImportService importService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Page<CcdiCustFmyRelationVO> selectRelationPage(CcdiCustFmyRelationQueryDTO query,
                                                           Integer pageNum, Integer pageSize) {
        Page<CcdiCustFmyRelationVO> page = new Page<>(pageNum, pageSize);
        return mapper.selectRelationPage(page, query);
    }

    @Override
    public CcdiCustFmyRelationVO selectRelationById(Long id) {
        return mapper.selectRelationById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertRelation(CcdiCustFmyRelationAddDTO addDTO) {
        CcdiCustFmyRelation relation = new CcdiCustFmyRelation();
        BeanUtils.copyProperties(addDTO, relation);

        // 关键设置:客户家庭关系
        relation.setIsEmpFamily(false);
        relation.setIsCustFamily(true);
        relation.setStatus(1);
        relation.setDataSource("MANUAL");

        return mapper.insert(relation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRelation(CcdiCustFmyRelationEditDTO editDTO) {
        CcdiCustFmyRelation relation = new CcdiCustFmyRelation();
        BeanUtils.copyProperties(editDTO, relation);

        return mapper.updateById(relation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRelationByIds(Long[] ids) {
        return mapper.deleteBatchIds(List.of(ids)) > 0;
    }

    @Override
    public void exportRelations(CcdiCustFmyRelationQueryDTO query, HttpServletResponse response) {
        // 查询所有符合条件的数据(不分页)
        Page<CcdiCustFmyRelationVO> page = new Page<>(1, 10000);
        Page<CcdiCustFmyRelationVO> result = mapper.selectRelationPage(page, query);

        List<CcdiCustFmyRelationExcel> excels = result.getRecords().stream()
                .map(this::convertToExcel)
                .toList();

        // 使用EasyExcelUtil导出
        EasyExcelUtil.exportExcel(response, excels, CcdiCustFmyRelationExcel.class, "信贷客户家庭关系");
    }

    @Override
    public void importTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(response, CcdiCustFmyRelationExcel.class, "信贷客户家庭关系");
    }

    @Override
    public String importRelations(List<CcdiCustFmyRelationExcel> excels) {
        if (StringUtils.isNull(excels) || excels.isEmpty()) {
            throw new RuntimeException("至少需要一条数据");
        }

        // 生成任务ID
        String taskId = UUID.randomUUID().toString();
        long startTime = System.currentTimeMillis();

        // 获取当前用户名
        String userName = SecurityUtils.getUsername();

        // 初始化Redis状态
        String statusKey = "import:custFmyRelation:" + taskId;
        Map<String, Object> statusData = new HashMap<>();
        statusData.put("taskId", taskId);
        statusData.put("status", "PROCESSING");
        statusData.put("totalCount", excels.size());
        statusData.put("successCount", 0);
        statusData.put("failureCount", 0);
        statusData.put("progress", 0);
        statusData.put("startTime", startTime);
        statusData.put("message", "正在处理...");

        redisTemplate.opsForHash().putAll(statusKey, statusData);
        redisTemplate.expire(statusKey, 7, TimeUnit.DAYS);

        // 调用异步导入服务
        importService.importRelationsAsync(excels, taskId, userName);

        return taskId;
    }

    @Override
    public List<CustFmyRelationImportFailureVO> getImportFailures(String taskId) {
        return importService.getImportFailures(taskId);
    }

    private CcdiCustFmyRelationExcel convertToExcel(CcdiCustFmyRelationVO vo) {
        CcdiCustFmyRelationExcel excel = new CcdiCustFmyRelationExcel();
        BeanUtils.copyProperties(vo, excel);
        return excel;
    }
}
