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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.conver.ReportConverMapper;
import com.tuoheng.admin.entity.InspectionFile;
import com.tuoheng.admin.entity.InspectionFileHandle;
import com.tuoheng.admin.entity.Report;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.report.QueryReportPageListRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.ReportPageListVo;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 查询报告分页列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-09
 */
@Slf4j
@Service
public class QueryReportPageListService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private InspectionFileHandleMapper inspectionFileHandleMapper;

    /**
     * 查询报告分页列表
     * 用户只能查看自己生成的报告
     *
     * @param request
     * @return
     */
    public JsonResult getPageList(QueryReportPageListRequest request) {
//        log.info("进入查询报告分页列表业务");
        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        String tenantId = user.getTenantId();
        request.setTenantId(tenantId);

        JsonResult result = this.check(tenantId, request);
        if (0 != result.getCode()) {
            log.info("查询报告分页列表：校验失败：{}", result.getMsg());
            return result;
        }

        // 设置分页参数
        IPage<Report> page = new Page<>(request.getPage(), request.getLimit());
        // 用户只能查看自己生成的报告
        request.setCreateUser(userId);
        // 查询结果
        IPage<Report> pageData = reportMapper.selectPageList(page, request);

        // 构造返回结果对象
        List<ReportPageListVo> reportPageListVoList = this.buildReportPageListVoList(pageData.getRecords());

        // 重写返回结果对象
        IPage<ReportPageListVo> reportVoPageData = new Page<>();
        reportVoPageData.setPages(pageData.getPages());
        reportVoPageData.setCurrent(pageData.getCurrent());
        reportVoPageData.setSize(pageData.getSize());
        reportVoPageData.setTotal(pageData.getTotal());
        reportVoPageData.setRecords(reportPageListVoList);

        return JsonResult.success(reportVoPageData);
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param request
     * @return
     */
    private JsonResult check(String tenantId, QueryReportPageListRequest request) {
        // 判断部门id是否为空
//        if (StringUtils.isEmpty(queryInspectionRequest.getDeptId())) {
//            return JsonResult.error(QueryInspectionPageListCodeEnum.DEPT_ID_IS_NULL.getCode(), QueryInspectionPageListCodeEnum.DEPT_ID_IS_NULL.getMsg());
//        }
//
//        // 判断部门是否存在
//        Dept dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
//                .eq(Dept::getTenantId, tenantId)
//                .eq(Dept::getId, queryInspectionRequest.getDeptId())
//                .eq(Dept::getMark, 1));
//        if (null == dept) {
//            return JsonResult.error(QueryInspectionPageListCodeEnum.DEPT_IS_NOT_EXIST.getCode(), QueryInspectionPageListCodeEnum.DEPT_IS_NOT_EXIST.getMsg());
//        }
        return JsonResult.success();
    }

    /**
     * 构造返回的数据列表
     *
     * @param reportList
     * @return
     */
    private List<ReportPageListVo> buildReportPageListVoList(List<Report> reportList) {
        List<ReportPageListVo> reportPageListVoList = ReportConverMapper.INSTANCE.fromReportListToReportPageListList(reportList);
        for (ReportPageListVo reportPageListVo : reportPageListVoList) {
            List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(Wrappers.<InspectionFile>lambdaQuery()
                    .eq(InspectionFile::getInspectionId, reportPageListVo.getInspectionId())
                    .in(InspectionFile::getStatus, GetInspectionFileStatusList.getStatusList())
                    .eq(InspectionFile::getMark, MarkEnum.VALID.getCode()));
            List<String> inspectionFileIdList = null;
            if (!CollectionUtil.isEmpty(inspectionFileList)) {
                reportPageListVo.setProblemTotalCount(inspectionFileList.size());
                inspectionFileIdList = inspectionFileList.stream().map(o -> o.getId()).collect(Collectors.toList());
            }
            if (!CollectionUtil.isEmpty(inspectionFileIdList)) {
                List<InspectionFileHandle> inspectionFileHandleList = inspectionFileHandleMapper.selectList(Wrappers.<InspectionFileHandle>lambdaQuery()
                        .in(InspectionFileHandle::getInspectionFileId, inspectionFileIdList)
                        .eq(InspectionFileHandle::getMark, MarkEnum.VALID.getCode()));
                if (!CollectionUtil.isEmpty(inspectionFileHandleList)) {
                    reportPageListVo.setProblemHandleCount(inspectionFileHandleList.size());
                }
            }
        }
        return reportPageListVoList;
    }
}
