package com.ruoyi.ems.service.impl;

import com.alibaba.fastjson2.JSON;
import com.huashe.common.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ems.domain.CheckItemResult;
import com.ruoyi.ems.domain.InspectionReport;
import com.ruoyi.ems.domain.InspectionReportDetail;
import com.ruoyi.ems.domain.ManualReportSubmit;
import com.ruoyi.ems.mapper.InspectionReportDetailMapper;
import com.ruoyi.ems.mapper.InspectionReportMapper;
import com.ruoyi.ems.service.IInspectionReportService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 巡检报告Service实现
 */
@Service
public class InspectionReportServiceImpl implements IInspectionReportService {

    private static final Logger log = LoggerFactory.getLogger(InspectionReportServiceImpl.class);

    @Autowired
    private InspectionReportMapper reportMapper;

    @Autowired
    private InspectionReportDetailMapper detailMapper;

    @Override
    public InspectionReport selectById(Long id) {
        InspectionReport report = reportMapper.selectById(id);
        if (report != null) {
            fillDetails(report);
        }
        return report;
    }

    @Override
    public InspectionReport selectByReportCode(String reportCode) {
        InspectionReport report = reportMapper.selectByReportCode(reportCode);
        if (report != null) {
            fillDetails(report);
        }
        return report;
    }

    @Override
    public List<InspectionReport> selectList(InspectionReport report) {
        return reportMapper.selectList(report);
    }

    @Override
    public int update(InspectionReport report) {
        report.setUpdateBy(SecurityUtils.getUsername());
        return reportMapper.update(report);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Long[] ids) {
        for (Long id : ids) {
            InspectionReport report = reportMapper.selectById(id);
            if (report != null) {
                detailMapper.deleteByReportCode(report.getReportCode());
            }
        }
        return reportMapper.deleteByIds(ids);
    }

    @Override
    public int submitManualReport(InspectionReport report) {
        InspectionReport dbReport = reportMapper.selectById(report.getId());
        if (dbReport == null) {
            throw new RuntimeException("报告不存在");
        }
        // 更新内容
        dbReport.setManualRemark(report.getManualRemark());
        dbReport.setResultStatus(report.getResultStatus());
        dbReport.setFinishTime(new Date());
        dbReport.setUpdateBy(SecurityUtils.getUsername());

        return reportMapper.update(dbReport);
    }

    /**
     * 更新手动巡检报告
     * 用于编辑已提交的手动巡检报告
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateManualReport(ManualReportSubmit submit) {
        log.info("更新手动巡检报告: id={}, reportCode={}", submit.getId(), submit.getReportCode());

        // 参数校验
        if (submit.getId() == null && StringUtils.isBlank(submit.getReportCode())) {
            throw new RuntimeException("报告ID或报告代码不能为空");
        }

        // 查询原报告
        InspectionReport dbReport;
        if (submit.getId() != null) {
            dbReport = reportMapper.selectById(submit.getId());
        } else {
            dbReport = reportMapper.selectByReportCode(submit.getReportCode());
        }

        if (dbReport == null) {
            throw new RuntimeException("巡检报告不存在");
        }

        // 只允许编辑手动巡检报告（planType=1）
        if (dbReport.getPlanType() != null && dbReport.getPlanType() != 1) {
            throw new RuntimeException("只能编辑手动巡检报告");
        }

        // 更新报告内容
        dbReport.setResultStatus(submit.getResultStatus());
        dbReport.setManualRemark(submit.getManualRemark());
        dbReport.setUpdateBy(submit.getSubmitter());

        // 更新结果摘要（包含图片和备注）
        Map<String, Object> summary = new HashMap<>();

        // 尝试保留原有的摘要信息
        if (StringUtils.isNotBlank(dbReport.getResultSummary())) {
            try {
                Map<String, Object> oldSummary = JSON.parseObject(dbReport.getResultSummary(), Map.class);
                if (oldSummary != null) {
                    summary.putAll(oldSummary);
                }
            } catch (Exception e) {
                log.warn("解析原报告摘要失败: {}", e.getMessage());
            }
        }

        // 更新摘要字段
        summary.put("type", "manual");
        summary.put("updateBy", submit.getSubmitter());
        summary.put("updateTime", DateUtils.dateTimeNow());

        if (StringUtils.isNotBlank(submit.getRemark())) {
            summary.put("remark", submit.getRemark());
        } else {
            summary.remove("remark");
        }

        dbReport.setResultSummary(JSON.toJSONString(summary));

        int result = reportMapper.update(dbReport);
        log.info("手动巡检报告更新成功: reportCode={}", dbReport.getReportCode());

        return result;
    }

    /**
     * 填充报告明细
     */
    private void fillDetails(InspectionReport report) {
        List<InspectionReportDetail> details = detailMapper.selectByReportCode(report.getReportCode());
        if (CollectionUtils.isNotEmpty(details)) {
            for (InspectionReportDetail detail : details) {
                if (StringUtils.isNotBlank(detail.getCheckItems())) {
                    try {
                        detail.setCheckItemList(JSON.parseArray(detail.getCheckItems(), CheckItemResult.class));
                    } catch (Exception e) {
                        log.warn("解析检查项失败: {}", e.getMessage());
                    }
                }
            }
        }
        report.setDetails(details);
    }
}