package com.tuoheng.admin.service.report.generate;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.conver.ReportConverMapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.InspectionFileStatusEnum;
import com.tuoheng.admin.enums.code.report.GenerateReportCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.service.report.query.GetInspectionFileStatusList;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 生成报告业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-09
 */
@Slf4j
@Service
public class GenerateReportService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private InspectionFileHandleMapper inspectionFileHandleMapper;

    @Autowired
    private ReportMapper reportMapper;

    /**
     * 生成报告
     *
     * @return
     */
    public JsonResult generate(String id) {
        log.info("进入生成报告业务");
        String userId = CurrentUserUtil.getUserId();
        String tenantId = CurrentUserUtil.getTenantId();

        JsonResult result = this.check(id);
        if (0 != result.getCode()) {
            log.info("生成报告业务：校验参数失败：{}", result.getMsg());
            return result;
        }
        Inspection inspection = (Inspection) result.getData();

        Report report = this.buildReport(userId, tenantId, inspection);

        result = this.addReport(report);
        if (0 != result.getCode()) {
            log.info("生成报告业务：添加报告记录失败：{}", result.getMsg());
            return result;
        }

        return JsonResult.success(report);
    }

    /**
     * 检查
     *
     * @param id
     * @return
     */
    private JsonResult check(String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(GenerateReportCodeEnum.INSPECTION_ID_IS_NULL.getCode(), GenerateReportCodeEnum.INSPECTION_ID_IS_NULL.getMsg());
        }
        Inspection inspection = inspectionMapper.selectOne(Wrappers.<Inspection>lambdaQuery()
                                    .eq(Inspection::getId, id)
                                    .eq(Inspection::getMark, 1));
        if (null == inspection) {
            return JsonResult.error(GenerateReportCodeEnum.INSPECTION_IS_NOT_EXIST.getCode(), GenerateReportCodeEnum.INSPECTION_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(inspection);
    }

    /**
     *
     * 生成报告实体
     *
     * @param inspection
     */
    private Report buildReport(String userId, String tenantId, Inspection inspection) {
        Report report = ReportConverMapper.INSTANCE.fromInspectionToReport(inspection);
        // 任务编号：XJBG+日期+3位排序数字
        String code = DateUtils.generateCode("XJBG");
        report.setId("");
        report.setReportCode(code);
        report.setTenantId(tenantId);
        report.setInspectionId(inspection.getId());
        report.setInspectionCode(inspection.getCode());
        report.setInspectionName(inspection.getName());
        report.setCreateUser(userId);
        report.setCreateTime(DateUtils.now());
        return report;
    }

    /**
     *
     * 添加报告
     *  每次生成报告，将上一次生成的报告给覆盖，因此直接将上次的删除，重新添加一条
     *
     * @param report
     */
    private JsonResult addReport(Report report) {
        Report reportTmp = reportMapper.selectOne(Wrappers.<Report>lambdaQuery()
                            .eq(Report::getInspectionId, report.getInspectionId())
                            .eq(Report::getMark, 1));
        if (null != reportTmp) {
            reportMapper.deleteById(reportTmp.getId());

        }
        Integer rowCount = reportMapper.insert(report);
        if (rowCount <= 0) {
            log.info("生成报告业务：添加报告记录失败");
            return JsonResult.error(GenerateReportCodeEnum.GENERATE_IS_FAILED.getCode(), GenerateReportCodeEnum.GENERATE_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }
}
