package com.shzg.project.worn.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.shzg.common.utils.DateUtils;
import com.shzg.common.utils.SecurityUtils;
import com.shzg.common.utils.StringUtils;
import com.shzg.framework.web.page.TableDataInfo;
import com.shzg.project.worn.domain.FileUploadConfig;
import com.shzg.project.worn.domain.WornOutboundBill;
import com.shzg.project.worn.domain.WornTechnicalAppraisalFile;
import com.shzg.project.worn.domain.dto.AppraisalFileDTO;
import com.shzg.project.worn.domain.dto.WornTechnicalAppraisalSimpleDTO;
import com.shzg.project.worn.mapper.WornOutboundBillMapper;
import com.shzg.project.worn.mapper.WornTechnicalAppraisalFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shzg.project.worn.mapper.WornTechnicalAppraisalMapper;
import com.shzg.project.worn.domain.WornTechnicalAppraisal;
import com.shzg.project.worn.service.IWornTechnicalAppraisalService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 技术鉴定Service业务层处理
 * 
 * @author shzg
 * @date 2026-04-10
 */
@Service
public class WornTechnicalAppraisalServiceImpl implements IWornTechnicalAppraisalService 
{
    @Autowired
    private WornTechnicalAppraisalMapper wornTechnicalAppraisalMapper;
    @Autowired
    private WornOutboundBillMapper wornOutboundBillMapper;
    @Autowired
    private WornTechnicalAppraisalFileMapper wornTechnicalAppraisalFileMapper;
    @Autowired
    private FileUploadConfig fileUploadConfig;
    /**
     * 查询技术鉴定
     * 
     * @param id 技术鉴定主键
     * @return 技术鉴定
     */
    @Override
    public WornTechnicalAppraisal selectWornTechnicalAppraisalById(Long id)
    {
        return wornTechnicalAppraisalMapper.selectWornTechnicalAppraisalById(id);
    }

    /**
     * 查询技术鉴定列表
     * 
     * @param wornTechnicalAppraisal 技术鉴定
     * @return 技术鉴定
     */
    @Override
    public List<WornTechnicalAppraisal> selectWornTechnicalAppraisalList(WornTechnicalAppraisal wornTechnicalAppraisal)
    {
        return wornTechnicalAppraisalMapper.selectWornTechnicalAppraisalList(wornTechnicalAppraisal);
    }

    /**
     * 新增技术鉴定
     * 
     * @param wornTechnicalAppraisal 技术鉴定
     * @return 结果
     */
    @Override
    public int insertWornTechnicalAppraisal(WornTechnicalAppraisal wornTechnicalAppraisal)
    {
        wornTechnicalAppraisal.setCreateTime(DateUtils.getNowDate());
        return wornTechnicalAppraisalMapper.insertWornTechnicalAppraisal(wornTechnicalAppraisal);
    }

    /**
     * 修改技术鉴定
     * 
     * @param wornTechnicalAppraisal 技术鉴定
     * @return 结果
     */
    @Override
    public int updateWornTechnicalAppraisal(WornTechnicalAppraisal wornTechnicalAppraisal)
    {
        wornTechnicalAppraisal.setUpdateTime(DateUtils.getNowDate());
        return wornTechnicalAppraisalMapper.updateWornTechnicalAppraisal(wornTechnicalAppraisal);
    }

    /**
     * 批量删除技术鉴定
     * 
     * @param ids 需要删除的技术鉴定主键
     * @return 结果
     */
    @Override
    public int deleteWornTechnicalAppraisalByIds(Long[] ids)
    {
        return wornTechnicalAppraisalMapper.deleteWornTechnicalAppraisalByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteWornTechnicalAppraisalById(Long id)
    {
        if (id == null)
        {
            throw new RuntimeException("技术鉴定表ID不能为空");
        }

        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Date now = DateUtils.getNowDate();

        /* ================== 1. 查询主表 ================== */
        WornTechnicalAppraisal appraisal = wornTechnicalAppraisalMapper.selectWornTechnicalAppraisalById(id);
        if (appraisal == null)
        {
            throw new RuntimeException("技术鉴定表不存在");
        }

        if ("1".equals(appraisal.getIsDelete()))
        {
            throw new RuntimeException("技术鉴定表已删除，请勿重复操作");
        }

        /* ================== 2. 查询附件 ================== */
        List<WornTechnicalAppraisalFile> fileList =
                wornTechnicalAppraisalFileMapper.selectWornTechnicalAppraisalFileByAppraisalId(id);

        /* ================== 3. 删除物理文件 + 逻辑删除附件 ================== */
        if (fileList != null && !fileList.isEmpty())
        {
            for (WornTechnicalAppraisalFile file : fileList)
            {
                if (file == null)
                {
                    continue;
                }

                if (StringUtils.isNotEmpty(file.getFileUrl()))
                {
                    deletePhysicalFile(file.getFileUrl());
                }

                WornTechnicalAppraisalFile updateFile = new WornTechnicalAppraisalFile();
                updateFile.setId(file.getId());
                updateFile.setIsDelete("1");

                int fileRows = wornTechnicalAppraisalFileMapper.removeWornTechnicalAppraisalFileById(updateFile);
                if (fileRows <= 0)
                {
                    throw new RuntimeException("删除技术鉴定附件失败，附件ID：" + file.getId());
                }
            }
        }

        /* ================== 4. 逻辑删除主表 ================== */
        WornTechnicalAppraisal updateAppraisal = new WornTechnicalAppraisal();
        updateAppraisal.setId(id);
        updateAppraisal.setIsDelete("1");
        updateAppraisal.setUpdateBy(String.valueOf(userId));
        updateAppraisal.setUpdateTime(now);

        int rows = wornTechnicalAppraisalMapper.removeWornTechnicalAppraisalById(updateAppraisal);
        if (rows <= 0)
        {
            throw new RuntimeException("删除技术鉴定表失败");
        }

        return 1;
    }
    /**
     * 删除物理文件
     */
    private void deletePhysicalFile(String fileUrl)
    {
        try
        {
            if (StringUtils.isEmpty(fileUrl))
            {
                return;
            }

            String uploadPath = fileUploadConfig.getUploadPath();

            // 只处理 /profile/ 开头的路径
            int index = fileUrl.indexOf("/profile/");
            if (index < 0)
            {
                return;
            }

            String relativePath = fileUrl.substring(index + "/profile/".length());
            File physicalFile = new File(uploadPath, relativePath);

            if (physicalFile.exists() && physicalFile.isFile())
            {
                boolean deleted = physicalFile.delete();
                if (!deleted)
                {
                    throw new RuntimeException("物理文件删除失败：" + physicalFile.getAbsolutePath());
                }
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException("删除物理文件失败：" + e.getMessage());
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WornTechnicalAppraisalSimpleDTO insertWornTechnicalAppraisalWithFiles(WornTechnicalAppraisal wornTechnicalAppraisal)
    {
        /* ================== 1. 参数校验 ================== */
        if (wornTechnicalAppraisal == null)
        {
            throw new RuntimeException("技术鉴定表参数不能为空");
        }
        if (StringUtils.isEmpty(wornTechnicalAppraisal.getBillNo()))
        {
            throw new RuntimeException("出库单号不能为空");
        }

        /* ================== 2. 当前用户 ================== */
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String userName = SecurityUtils.getLoginUser().getUser().getNickName();
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        Date now = DateUtils.getNowDate();

        /* ================== 3. 校验唯一 ================== */
        WornTechnicalAppraisal query = new WornTechnicalAppraisal();
        query.setBillNo(wornTechnicalAppraisal.getBillNo());
        List<WornTechnicalAppraisal> oldList =
                wornTechnicalAppraisalMapper.selectWornTechnicalAppraisalList(query);

        if (oldList != null && !oldList.isEmpty())
        {
            throw new RuntimeException("该出库单已存在技术鉴定表，请勿重复新增");
        }

        /* ================== 4. 查询出库单 ================== */
        WornOutboundBill outboundBill =
                wornOutboundBillMapper.selectWornOutboundBillByBillNo(wornTechnicalAppraisal.getBillNo());

        if (outboundBill == null)
        {
            throw new RuntimeException("关联出库单不存在：" + wornTechnicalAppraisal.getBillNo());
        }

        /* ================== 5. 主表赋值 ================== */
        if (StringUtils.isEmpty(wornTechnicalAppraisal.getAppraisalNo()))
        {
            wornTechnicalAppraisal.setAppraisalNo("TAR" + DateUtils.dateTimeNow("yyyyMMddHHmmssSSS"));
        }

        wornTechnicalAppraisal.setBillId(outboundBill.getId());
        wornTechnicalAppraisal.setProjectId(deptId);
        wornTechnicalAppraisal.setUserId(userId);
        wornTechnicalAppraisal.setUserName(userName);
        wornTechnicalAppraisal.setStatus("1");
        wornTechnicalAppraisal.setCreateBy(String.valueOf(userId));
        wornTechnicalAppraisal.setCreateTime(now);
        wornTechnicalAppraisal.setIsDelete("0");

        int rows = wornTechnicalAppraisalMapper.insertWornTechnicalAppraisal(wornTechnicalAppraisal);
        if (rows <= 0)
        {
            throw new RuntimeException("技术鉴定表新增失败");
        }

        Long appraisalId = wornTechnicalAppraisal.getId();

        /* ================== 6. 保存附件 ================== */
        List<AppraisalFileDTO> fileList = wornTechnicalAppraisal.getFileList();
        if (fileList != null && !fileList.isEmpty())
        {
            Long sortNum = 1L;

            for (AppraisalFileDTO files : fileList){
                if (files == null || StringUtils.isEmpty(files.getUrl()))
                {
                    continue;
                }
                WornTechnicalAppraisalFile wornTechnicalAppraisalFile = new WornTechnicalAppraisalFile();
                wornTechnicalAppraisalFile.setAppraisalId(appraisalId);
                wornTechnicalAppraisalFile.setSortNum(sortNum++);
                wornTechnicalAppraisalFile.setCreateBy(String.valueOf(userId));
                wornTechnicalAppraisalFile.setCreateTime(now);
                wornTechnicalAppraisalFile.setIsDelete("0");
                wornTechnicalAppraisalFile.setFileName(files.getName());
                wornTechnicalAppraisalFile.setFileUrl(files.getUrl());
                String fileName = files.getName(); // 或从url截取
                String fileType = "";

                if (StringUtils.isNotEmpty(fileName) && fileName.contains(".")) {
                    fileType = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                }

                wornTechnicalAppraisalFile.setFileType(fileType);
                int fileRows = wornTechnicalAppraisalFileMapper.insertWornTechnicalAppraisalFile(wornTechnicalAppraisalFile);
                if (fileRows <= 0)
                {
                    throw new RuntimeException("附件保存失败：" + wornTechnicalAppraisalFile.getFileName());
                }
            }
        }

        /* ================== 7. 组装返回 DTO ================== */
        WornTechnicalAppraisal saved =
                wornTechnicalAppraisalMapper.selectWornTechnicalAppraisalById(appraisalId);

        List<WornTechnicalAppraisalFile> savedFiles =
                wornTechnicalAppraisalFileMapper.selectWornTechnicalAppraisalFileByAppraisalId(appraisalId);

        WornTechnicalAppraisalSimpleDTO dto = new WornTechnicalAppraisalSimpleDTO();
        dto.setId(saved.getId());
        dto.setAppraisalNo(saved.getAppraisalNo());
        dto.setCreateTime(saved.getCreateTime());
        dto.setAppraisalDesc(saved.getAppraisalDesc());
        dto.setRemark(saved.getRemark());

        List<AppraisalFileDTO> fileDtoList = new ArrayList<>();

        if (savedFiles != null && !savedFiles.isEmpty())
        {
            for (WornTechnicalAppraisalFile file : savedFiles)
            {
                if (file == null) continue;

                AppraisalFileDTO fileDTO = new AppraisalFileDTO();
                fileDTO.setName(file.getFileName());
                fileDTO.setUrl(file.getFileUrl());

                fileDtoList.add(fileDTO);
            }
        }

        dto.setFileUrlList(fileDtoList);

        return dto;
    }
    @Override
    public TableDataInfo selectMyTechnicalAppraisalSimplePageList()
    {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();

        WornTechnicalAppraisal query = new WornTechnicalAppraisal();
        query.setUserId(userId);

        // 这里的分页由 Controller 里的 startPage() 生效
        List<WornTechnicalAppraisal> list =
                wornTechnicalAppraisalMapper.selectMyTechnicalAppraisalList(query);

        // 保留原始分页信息
        PageInfo<WornTechnicalAppraisal> pageInfo = new PageInfo<>(list);

        List<WornTechnicalAppraisalSimpleDTO> result = new ArrayList<>();

        if (list != null && !list.isEmpty())
        {
            for (WornTechnicalAppraisal appraisal : list)
            {
                WornTechnicalAppraisalSimpleDTO dto = new WornTechnicalAppraisalSimpleDTO();
                dto.setId(appraisal.getId());
                dto.setAppraisalNo(appraisal.getAppraisalNo());
                dto.setCreateTime(appraisal.getCreateTime());
                dto.setAppraisalDesc(appraisal.getAppraisalDesc());
                dto.setRemark(appraisal.getRemark());
                // 查询附件
                List<WornTechnicalAppraisalFile> fileList =
                        wornTechnicalAppraisalFileMapper.selectWornTechnicalAppraisalFileByAppraisalId(appraisal.getId());

                List<AppraisalFileDTO> fileDtoList = new ArrayList<>();

                if (fileList != null && !fileList.isEmpty())
                {
                    for (WornTechnicalAppraisalFile file : fileList)
                    {
                        if (file == null)
                        {
                            continue;
                        }

                        AppraisalFileDTO fileDTO = new AppraisalFileDTO();
                        fileDTO.setName(file.getFileName());
                        fileDTO.setUrl(file.getFileUrl());
                        fileDtoList.add(fileDTO);
                    }
                }

                dto.setFileUrlList(fileDtoList);
                result.add(dto);
            }
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(result);
        rspData.setTotal(pageInfo.getTotal());
        return rspData;
    }
}
