package com.ruoyi.dpc.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dpc.domain.DpcIntermediaryBlacklist;
import com.ruoyi.dpc.domain.dto.DpcIntermediaryBlacklistAddDTO;
import com.ruoyi.dpc.domain.dto.DpcIntermediaryBlacklistEditDTO;
import com.ruoyi.dpc.domain.dto.DpcIntermediaryBlacklistQueryDTO;
import com.ruoyi.dpc.domain.vo.DpcIntermediaryBlacklistVO;
import com.ruoyi.dpc.mapper.DpcIntermediaryBlacklistMapper;
import com.ruoyi.dpc.service.IDpcIntermediaryBlacklistService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 中介人员黑名单 服务层处理
 *
 * @author ruoyi
 * @date 2026-01-27
 */
@Service
public class DpcIntermediaryBlacklistServiceImpl implements IDpcIntermediaryBlacklistService {

    @Resource
    private DpcIntermediaryBlacklistMapper intermediaryMapper;

    /**
     * 查询中介黑名单列表
     *
     * @param queryDTO 查询条件
     * @return 中介黑名单集合
     */
    @Override
    public List<DpcIntermediaryBlacklistVO> selectIntermediaryList(DpcIntermediaryBlacklistQueryDTO queryDTO) {
        List<DpcIntermediaryBlacklist> list = intermediaryMapper.selectIntermediaryList(queryDTO);
        List<DpcIntermediaryBlacklistVO> voList = new ArrayList<>();
        for (DpcIntermediaryBlacklist intermediary : list) {
            voList.add(convertToVO(intermediary));
        }
        return voList;
    }

    /**
     * 查询中介黑名单列表（用于导出）
     *
     * @param queryDTO 查询条件
     * @return 中介黑名单实体集合
     */
    @Override
    public List<DpcIntermediaryBlacklist> selectIntermediaryListForExport(DpcIntermediaryBlacklistQueryDTO queryDTO) {
        return intermediaryMapper.selectIntermediaryList(queryDTO);
    }

    /**
     * 查询中介黑名单详细
     *
     * @param intermediaryId 中介ID
     * @return 中介黑名单VO
     */
    @Override
    public DpcIntermediaryBlacklistVO selectIntermediaryById(Long intermediaryId) {
        DpcIntermediaryBlacklist intermediary = intermediaryMapper.selectIntermediaryById(intermediaryId);
        return convertToVO(intermediary);
    }

    /**
     * 新增中介黑名单
     *
     * @param addDTO 新增DTO
     * @return 结果
     */
    @Override
    public int insertIntermediary(DpcIntermediaryBlacklistAddDTO addDTO) {
        DpcIntermediaryBlacklist intermediary = new DpcIntermediaryBlacklist();
        BeanUtils.copyProperties(addDTO, intermediary);
        intermediary.setCreateBy(SecurityUtils.getUsername());
        return intermediaryMapper.insertIntermediary(intermediary);
    }

    /**
     * 修改中介黑名单
     *
     * @param editDTO 编辑DTO
     * @return 结果
     */
    @Override
    public int updateIntermediary(DpcIntermediaryBlacklistEditDTO editDTO) {
        DpcIntermediaryBlacklist intermediary = new DpcIntermediaryBlacklist();
        BeanUtils.copyProperties(editDTO, intermediary);
        intermediary.setUpdateBy(SecurityUtils.getUsername());
        return intermediaryMapper.updateIntermediary(intermediary);
    }

    /**
     * 批量删除中介黑名单
     *
     * @param intermediaryIds 需要删除的中介ID
     * @return 结果
     */
    @Override
    public int deleteIntermediaryByIds(Long[] intermediaryIds) {
        return intermediaryMapper.deleteIntermediaryByIds(intermediaryIds);
    }

    /**
     * 导入中介黑名单数据
     *
     * @param addDTOList     新增DTO列表
     * @param isUpdateSupport 是否更新支持
     * @return 结果
     */
    @Override
    public String importIntermediary(List<DpcIntermediaryBlacklistAddDTO> addDTOList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(addDTOList) || addDTOList.isEmpty()) {
            return "至少需要一条数据";
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (DpcIntermediaryBlacklistAddDTO addDTO : addDTOList) {
            try {
                // 验证数据
                validateIntermediaryData(addDTO);

                DpcIntermediaryBlacklist intermediary = new DpcIntermediaryBlacklist();
                BeanUtils.copyProperties(addDTO, intermediary);
                intermediary.setCreateBy(SecurityUtils.getUsername());

                intermediaryMapper.insertIntermediary(intermediary);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、").append(addDTO.getName()).append(" 导入成功");
            } catch (Exception e) {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、").append(addDTO.getName()).append(" 导入失败：");
                failureMsg.append(e.getMessage());
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
            return successMsg.toString();
        }
    }

    /**
     * 验证中介数据
     */
    private void validateIntermediaryData(DpcIntermediaryBlacklistAddDTO addDTO) {
        // 验证中介类型
        if (!"1".equals(addDTO.getIntermediaryType()) && !"2".equals(addDTO.getIntermediaryType())) {
            throw new RuntimeException("中介类型只能填写'个人'或'机构'");
        }

        // 验证状态
        if (!"0".equals(addDTO.getStatus()) && !"1".equals(addDTO.getStatus())) {
            throw new RuntimeException("状态只能填写'正常'或'停用'");
        }
    }

    /**
     * 转换为VO对象
     */
    private DpcIntermediaryBlacklistVO convertToVO(DpcIntermediaryBlacklist intermediary) {
        if (intermediary == null) {
            return null;
        }

        DpcIntermediaryBlacklistVO vo = new DpcIntermediaryBlacklistVO();
        BeanUtils.copyProperties(intermediary, vo);

        // 设置中介类型名称
        if ("1".equals(intermediary.getIntermediaryType())) {
            vo.setIntermediaryTypeName("个人");
        } else if ("2".equals(intermediary.getIntermediaryType())) {
            vo.setIntermediaryTypeName("机构");
        }

        // 设置状态名称
        if ("0".equals(intermediary.getStatus())) {
            vo.setStatusName("正常");
        } else if ("1".equals(intermediary.getStatus())) {
            vo.setStatusName("停用");
        }

        return vo;
    }
}
