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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.InspectionFile;
import com.tuoheng.admin.entity.Report;
import com.tuoheng.admin.entity.Tenant;
import com.tuoheng.admin.enums.InspectionFileStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.report.ExportInspectionReportReportCodeEnum;
import com.tuoheng.admin.mapper.InspectionFileHandleMapper;
import com.tuoheng.admin.mapper.InspectionFileMapper;
import com.tuoheng.admin.mapper.ReportMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.service.report.query.GetInspectionFileStatusList;
import com.tuoheng.admin.utils.DownloadUtil;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.config.UploadFileConfig;
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 javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 导出巡检报告业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-09
 */
@Slf4j
@Service
public class ExportInspectionReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private InspectionFileHandleMapper inspectionFileHandleMapper;

    @Autowired
    private GenerateReportWordService generateReportWordService;

    public JsonResult exportReport(HttpServletResponse response, String reportId) {
        String tenantId = CurrentUserUtil.getTenantId();

        JsonResult result = this.check(reportId);
        if (0 != result.getCode()) {
            log.info("导出巡检报告业务：校验失败：{}", result.getMsg());
            return result;
        }

        //查询报告
        Report report = (Report) result.getData();

        //  查询问题清单
        List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(new LambdaQueryWrapper<InspectionFile>()
                                                    .eq(InspectionFile::getTenantId, tenantId)
                                                    .in(InspectionFile::getStatus, GetInspectionFileStatusList.getStatusList())
                                                    .eq(InspectionFile::getInspectionId, report.getInspectionId()));

        String filename = report.getReportCode() + ".doc";
        String filePath = UploadFileConfig.uploadFolder + "/doc/" + filename;
        File fd = new File(UploadFileConfig.uploadFolder + "/doc");
        if (!fd.exists()) {
            fd.mkdirs();
        }

        // 生成word
        String areaName = this.getAreaName();
        String titleName = areaName + "高速巡检报告";
        File f = new File(filePath);
        if (!f.exists() || f.length() < 1000) {
            result = generateReportWordService.buildWord(filePath, titleName, report, inspectionFileList, null);
            if (0 != result.getCode()) {
                log.info("导出巡检报告业务：生成word失败：{}", result.getMsg());
                return result;
            }
        }

        // 下载
        String fileName = this.getAreaName() + "高速巡检报告【" + report.getReportCode() + "】.doc";
        DownloadUtil.download(response, filePath, fileName);

        return JsonResult.success();
    }

    /**
     * 检查
     *
     * @param id
     * @return
     */
    private JsonResult check(String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(ExportInspectionReportReportCodeEnum.REPORT_ID_IS_NULL.getCode(), ExportInspectionReportReportCodeEnum.REPORT_ID_IS_NULL.getMsg());
        }
        Report report = reportMapper.selectOne(Wrappers.<Report>lambdaQuery()
                .eq(Report::getId, id)
                .eq(Report::getMark, MarkEnum.VALID.getCode()));
        if (null == report) {
            return JsonResult.error(ExportInspectionReportReportCodeEnum.REPORT_IS_NOT_EXIST.getCode(), ExportInspectionReportReportCodeEnum.REPORT_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(report);
    }

    /**
     * 获取区域名称
     *
     * @return
     */
    private String getAreaName() {
        Tenant tenant = tenantMapper.selectById(CurrentUserUtil.getTenantId());
        String areaName = "";
        if (ObjectUtil.isNotNull(tenant)) {
            if (!StringUtils.isEmpty(tenant.getProvinceName())) {
                areaName += tenant.getProvinceName();
            }
            if (!StringUtils.isEmpty(tenant.getCityName())) {
                areaName += tenant.getCityName();
            }
            if (!StringUtils.isEmpty(tenant.getDistrictName())) {
                areaName += tenant.getDistrictName();
            }
        }
        return areaName;
    }
}
