package com.zg.project.information.service.impl;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.zg.common.exception.ServiceException;
import com.zg.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zg.project.information.mapper.ConstructionTeamMapper;
import com.zg.project.information.domain.ConstructionTeam;
import com.zg.project.information.service.IConstructionTeamService;

import static com.zg.common.utils.SecurityUtils.getUsername;

/**
 * 施工队信息Service业务层处理
 * 
 * @author zg
 * @date 2025-06-09
 */
@Service
public class ConstructionTeamServiceImpl implements IConstructionTeamService 
{
    @Autowired
    private ConstructionTeamMapper constructionTeamMapper;

    /**
     * 查询施工队信息
     * 
     * @param id 施工队信息主键
     * @return 施工队信息
     */
    @Override
    public ConstructionTeam selectConstructionTeamById(Long id)
    {
        return constructionTeamMapper.selectConstructionTeamById(id);
    }

    /**
     * 查询施工队信息列表
     * 
     * @param constructionTeam 施工队信息
     * @return 施工队信息
     */
    @Override
    public List<ConstructionTeam> selectConstructionTeamList(ConstructionTeam constructionTeam)
    {
        return constructionTeamMapper.selectConstructionTeamList(constructionTeam);
    }

    /**
     * 新增施工队信息
     * 
     * @param constructionTeam 施工队信息
     * @return 结果
     */
    @Override
    public int insertConstructionTeam(ConstructionTeam constructionTeam)
    {
        // 1️⃣ 自动生成施工队编号（6 位）
        String teamCode = generateTeamCode();
        constructionTeam.setTeamCode(teamCode);

        // 2️⃣ 补充若依通用字段（如果你没用 BaseEntity 自动处理）
        constructionTeam.setCreatedBy(getUsername());
        constructionTeam.setCreatedAt(new Date());
        constructionTeam.setIsDelete("0");

        return constructionTeamMapper.insertConstructionTeam(constructionTeam);
    }

    /**
     * 生成施工队编号（CT + 6位数字）
     * 示例：CT000001
     */
    private String generateTeamCode() {
        String maxCode = constructionTeamMapper.selectMaxTeamCode();

        if (maxCode == null) {
            return "CT000001";
        }

        // 取数字部分
        int num = Integer.parseInt(maxCode.substring(2));
        num++;

        return String.format("CT%06d", num);
    }

    /**
     * 修改施工队信息
     * 
     * @param constructionTeam 施工队信息
     * @return 结果
     */
    @Override
    public int updateConstructionTeam(ConstructionTeam constructionTeam)
    {
        return constructionTeamMapper.updateConstructionTeam(constructionTeam);
    }

    /**
     * 批量删除施工队信息
     * 
     * @param ids 需要删除的施工队信息主键
     * @return 结果
     */
    @Override
    public int deleteConstructionTeamByIds(Long[] ids)
    {
        return constructionTeamMapper.deleteConstructionTeamByIds(ids);
    }

    /**
     * 删除施工队信息信息
     * 
     * @param id 施工队信息主键
     * @return 结果
     */
    @Override
    public int deleteConstructionTeamById(Long id)
    {
        return constructionTeamMapper.deleteConstructionTeamById(id);
    }

    /**
     * 导入施工队信息列表（名称 / 编号 去重）
     *
     * @param teamList 导入的施工队信息列表
     * @param operName 操作人员
     * @return 结果
     */
    @Override
    public String importConstructionTeamList(List<ConstructionTeam> teamList, String operName)
    {
        if (teamList == null || teamList.isEmpty())
        {
            throw new ServiceException("导入数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        Date now = new Date();

        // ===== ① Excel 内去重 =====
        Set<String> teamCodeSet = new HashSet<>();
        Set<String> teamNameSet = new HashSet<>();

        for (ConstructionTeam team : teamList)
        {
            String teamCode = team.getTeamCode();
            String teamName = team.getTeamName();

            if (StringUtils.isBlank(teamCode) || StringUtils.isBlank(teamName))
            {
                failureNum++;
                failureMsg.append("<br/>施工队名称/编号不能为空，已跳过。");
                continue;
            }

            if (!teamCodeSet.add(teamCode))
            {
                failureNum++;
                failureMsg.append("<br/>施工队编号重复（Excel 内）：").append(teamCode);
                continue;
            }

            if (!teamNameSet.add(teamName))
            {
                failureNum++;
                failureMsg.append("<br/>施工队名称重复（Excel 内）：").append(teamName);
                continue;
            }
        }

        // ===== ② 数据库内去重 =====
        for (ConstructionTeam team : teamList)
        {
            try
            {
                // 跳过前面校验失败的数据
                if (StringUtils.isBlank(team.getTeamCode()) || StringUtils.isBlank(team.getTeamName()))
                {
                    continue;
                }

                // 按编号查
                ConstructionTeam existByCode =
                        constructionTeamMapper.selectByTeamCode(team.getTeamCode());
                if (existByCode != null)
                {
                    failureNum++;
                    failureMsg.append("<br/>施工队编号已存在：").append(team.getTeamCode());
                    continue;
                }

                // 按名称查
                ConstructionTeam existByName =
                        constructionTeamMapper.selectByTeamName(team.getTeamName());
                if (existByName != null)
                {
                    failureNum++;
                    failureMsg.append("<br/>施工队名称已存在：").append(team.getTeamName());
                    continue;
                }

                // ===== 新增 =====
                team.setCreatedBy(operName);
                team.setCreatedAt(now);
                team.setUpdatedBy(operName);
                team.setUpdatedAt(now);

                if (StringUtils.isBlank(team.getIsDelete()))
                {
                    team.setIsDelete("0");
                }

                constructionTeamMapper.insertConstructionTeam(team);
                successNum++;

            }
            catch (Exception e)
            {
                failureNum++;
                failureMsg.append("<br/>施工队编号：")
                        .append(team.getTeamCode())
                        .append("，施工队名称：")
                        .append(team.getTeamName())
                        .append(" 导入失败：")
                        .append(e.getMessage());
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0,
                    "导入完成，成功 " + successNum + " 条，失败 " + failureNum + " 条：");
            throw new ServiceException(failureMsg.toString());
        }

        return "导入成功，共 " + successNum + " 条数据";
    }


}
