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

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.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;
    /**
     * 查询技术鉴定
     * 
     * @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);
    }

    /**
     * 删除技术鉴定信息
     * 
     * @param id 技术鉴定主键
     * @return 结果
     */
    @Override
    public int deleteWornTechnicalAppraisalById(Long id)
    {
        return wornTechnicalAppraisalMapper.deleteWornTechnicalAppraisalById(id);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int 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();
        if (appraisalId == null)
        {
            throw new RuntimeException("技术鉴定表新增失败，ID未回填");
        }

        /* ================== 6. 保存附件 ================== */
        List<WornTechnicalAppraisalFile> fileList = wornTechnicalAppraisal.getFileList();
        if (fileList != null && !fileList.isEmpty())
        {
             Long sortNum = 1L;
            for (WornTechnicalAppraisalFile file : fileList)
            {
                if (file == null || StringUtils.isEmpty(file.getFileUrl()))
                {
                    continue;
                }

                file.setAppraisalId(appraisalId);
                file.setSortNum(sortNum++);
                file.setCreateBy(String.valueOf(userId));
                file.setCreateTime(now);
                file.setIsDelete("0");

                int fileRows = wornTechnicalAppraisalFileMapper.insertWornTechnicalAppraisalFile(file);
                if (fileRows <= 0)
                {
                    throw new RuntimeException("技术鉴定附件保存失败：" + file.getFileName());
                }
            }
        }

        return 1;
    }
    @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;
    }
}
