package com.fs.project.service.impl;

import com.fs.common.BeanCopyUtils;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.DictUtils;
import com.fs.project.domain.Project;
import com.fs.project.domain.ProjectContract;
import com.fs.project.domain.ProjectTaskType;
import com.fs.project.mapper.ProjectContractMapper;
import com.fs.project.mapper.ProjectMapper;
import com.fs.project.mapper.ProjectTaskTypeMapper;
import com.fs.project.service.IProjectService;
import com.fs.project.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 项目主Service业务层处理
 *
 * @author fs
 * @date 2025-12-30
 */
@Service
public class ProjectServiceImpl implements IProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectTaskTypeMapper projectTaskTypeMapper;
    @Autowired
    private ProjectContractMapper projectContractMapper;


    /**
     * 查询项目主
     *
     * @param id 项目主主键
     * @return 项目主
     */
    @Override
    public Project selectProjectById(Long id) {
        return projectMapper.selectProjectById(id);
    }

    /**
     * 查询项目主列表
     *
     * @param project 项目主
     * @return 项目主
     */
    @Override
    public List<Project> selectProjectList(Project project) {

        List<Project> projects = projectMapper.selectProjectList(project);
        for (Project project1 : projects) {
            Long projectTypeId = project1.getProjectTypeId();
            project1.setProjectTypeName(DictUtils.getDictLabel("project_type", String.valueOf(projectTypeId)));
        }
        return projects;
    }

    /**
     * 新增项目主
     *
     * @param project 项目主
     * @return 结果
     */
    @Override
    public int insertProject(Project project) {
        project.setCreateTime(DateUtils.getNowDate());
        return projectMapper.insertProject(project);
    }




    /**
     * 批量删除项目主
     *
     * @param ids 需要删除的项目主主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProjectByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return 0;
        }

        // 1) 先删子表（任务类型、合同）——按 projectId 批量删
        projectTaskTypeMapper.deleteByProjectIds(ids);
        projectContractMapper.deleteByProjectIds(ids);

        // 2) 再删主表
        return projectMapper.deleteProjectByIds(ids);
    }

    /**
     * 删除项目主信息
     *
     * @param id 项目主主键
     * @return 结果
     */
    @Override
    public int deleteProjectById(Long id) {
        return projectMapper.deleteProjectById(id);
    }

    @Override
    public List<ProjectOptionVO> selectProjectOptions(String projectName) {
        return projectMapper.selectProjectOptions(projectName);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int add(AddProjectReqVO req) {
        if (req == null || req.getProjectVO() == null) {
            throw new RuntimeException("projectVO不能为空");
        }

        Project project = BeanCopyUtils.copy(req.getProjectVO(), Project.class);

        // 1) 插入主表，必须拿到自增ID
        int rows = projectMapper.insertProject(project); // 确保这里能回填 project.id
        if (rows <= 0 || project.getId() == null) {
            throw new RuntimeException("新增项目失败，未获取到项目ID");
        }
        Long projectId = project.getId();
        Long companyId = project.getCompanyId();

        // 2) 子表：任务类型
        List<ProjectTaskTypeVO> typeVOList = req.getProjectTaskTypeVOList();
        if (typeVOList != null && !typeVOList.isEmpty()) {
            List<ProjectTaskType> types = BeanCopyUtils.copyList(typeVOList, ProjectTaskType.class);
            for (ProjectTaskType t : types) {
                t.setProjectId(projectId);
                t.setCompanyId(companyId);
                rows += projectTaskTypeMapper.insertProjectTaskType(t);
            }
        }

        // 3) 子表：合同
        List<ProjectContractVO> contractVOList = req.getProjectContractVOList();
        if (contractVOList != null && !contractVOList.isEmpty()) {
            List<ProjectContract> contracts = BeanCopyUtils.copyList(contractVOList, ProjectContract.class);
            for (ProjectContract c : contracts) {
                c.setProjectId(projectId);
                c.setCompanyId(companyId);
                rows += projectContractMapper.insertProjectContract(c);
            }
        }

        return rows;
    }

    @Transactional
    @Override
    public int edit(AddProjectReqVO addProjectReqVO) {
        ProjectVO projectVO = addProjectReqVO.getProjectVO();
        if (projectVO == null || projectVO.getId() == null) {
            throw new RuntimeException("项目ID不能为空");
        }

        Long projectId = projectVO.getId();
        Long companyId = projectVO.getCompanyId();

        // 1) 更新主表
        Project project = BeanCopyUtils.copy(projectVO, Project.class);
        int rows = projectMapper.updateProject(project); // 你自己的 update 方法
        if (rows <= 0) {
            return 0;
        }

        // 2) 先删旧的子表数据（按 projectId）
        projectTaskTypeMapper.deleteByProjectId(projectId);
        projectContractMapper.deleteByProjectId(projectId);

        // 3) 再插入新的子表数据（记得补 companyId/projectId/delFlag）
        List<ProjectTaskTypeVO> taskList = addProjectReqVO.getProjectTaskTypeVOList();
        if (taskList != null && !taskList.isEmpty()) {
            List<ProjectTaskType> entities = BeanCopyUtils.copyList(taskList, ProjectTaskType.class);
            for (ProjectTaskType e : entities) {
                e.setId(null);                 // 重建：防止传了旧 id 导致更新/主键冲突
                e.setProjectId(projectId);
                e.setCompanyId(companyId);
                e.setDelFlag(0L);
                projectTaskTypeMapper.insertProjectTaskType(e);
            }
        }

        List<ProjectContractVO> contractList = addProjectReqVO.getProjectContractVOList();
        if (contractList != null && !contractList.isEmpty()) {
            List<ProjectContract> entities = BeanCopyUtils.copyList(contractList, ProjectContract.class);
            for (ProjectContract e : entities) {
                e.setId(null);
                e.setProjectId(projectId);
                e.setCompanyId(companyId);
                e.setDelFlag(0L);
                projectContractMapper.insertProjectContract(e);
            }
        }

        return 1;
    }

    @Override
    public ProjectDetailRespVO selectProjectDetailById(Long id) {
        // 1) 主表
        Project project = projectMapper.selectProjectById(id); // 记得and del_flag=0
        if (project == null) return null;

        ProjectVO projectVO = BeanCopyUtils.copy(project, ProjectVO.class);

        // 2) 子表：任务类型、合同（建议都加del_flag=0）
        List<ProjectTaskType> taskTypes = projectTaskTypeMapper.selectByProjectId(id);
        List<ProjectContract> contracts = projectContractMapper.selectByProjectId(id);

        List<ProjectTaskTypeVO> taskTypeVOList = BeanCopyUtils.copyList(taskTypes, ProjectTaskTypeVO.class);
        List<ProjectContractVO> contractVOList = BeanCopyUtils.copyList(contracts, ProjectContractVO.class);

        ProjectDetailRespVO resp = new ProjectDetailRespVO();
        resp.setProjectVO(projectVO);
        resp.setProjectTaskTypeVOList(taskTypeVOList);
        resp.setProjectContractVOList(contractVOList);
        return resp;
    }

    @Override
    public int changeStatus(Long id, Integer status) {
        return projectMapper.updateStatus(id, status);
    }

    @Override
    public List<Project> getAllData(GetAllDataVO dataVO) {

        return projectMapper.getAllData(dataVO);
    }
}
