package com.tuoheng.admin.service.inspectionfile;

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.Inspection;
import com.tuoheng.admin.entity.InspectionFile;
import com.tuoheng.admin.entity.QuestionType;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.SectionEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.query.InspectionFileQuery;
import com.tuoheng.admin.request.inspectionfile.*;
import com.tuoheng.admin.service.inspectionfile.confirm.InspectionFileConfirmService;
import com.tuoheng.admin.service.inspectionfile.delete.DeleteInspectionFileByIdListService;
import com.tuoheng.admin.service.inspectionfile.export.ExportInspectionFileByIdListService;
import com.tuoheng.admin.service.inspectionfile.handle.QueryInspectionFileHandleByInspectionFileIdService;
import com.tuoheng.admin.service.inspectionfile.ignore.InspectionFileIgnoreService;
import com.tuoheng.admin.service.inspectionfile.processing.InspectionFileProcessingService;
import com.tuoheng.admin.service.inspectionfile.query.*;
import com.tuoheng.admin.service.inspectionfile.update.UpdateInspectionFileQuestionTypeService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.inspection.InspectionFileVo;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务问题管理 前端控制器
 *
 * @Author ChengWang
 * @Date 2022/11/29
 */
@Service
@Slf4j
public class InspectionFileServiceImpl implements IInspectionFileService {

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private QuestionTypeMapper questionTypeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private QueryInspectionFilePageListByInspectionIdService queryInspectionFilePageListByInspectionIdService;

    @Autowired
    private QueryInspectionFileListByInspectionIdService queryInspectionFileListByInspectionIdService;

    @Autowired
    private QueryInspectionFilePageListService queryInspectionFilePageListService;

    @Autowired
    private InspectionFileIgnoreService inspectionFileIgnoreService;

    @Autowired
    private InspectionFileConfirmService inspectionFileConfirmService;

    @Autowired
    private QueryInspectionFileHandleByInspectionFileIdService queryInspectionFileHandleByInspectionFileIdService;

    @Autowired
    private QueryInspectionFileDistributionListService queryInspectionFileDistributionListService;

    @Autowired
    private QueryInspectionFilePageListByWorkOrderIdService queryInspectionFilePageListByWorkOrderIdService;

    @Autowired
    private InspectionFileProcessingService inspectionFileProcessingService;

    @Autowired
    private UpdateInspectionFileQuestionTypeService updateInspectionFileQuestionTypeService;

    @Autowired
    private QueryInspectionFileListByDeptUserTypeService queryInspectionFileListByDeptUserTypeService;

    @Autowired
    private DeleteInspectionFileByIdListService deleteInspectionFileByIdListService;

    @Autowired
    private ExportInspectionFileByIdListService exportInspectionFileByIdListService;

    /**
     * 问题类型和任务名称
     *
     * @return
     */
    @Override
    public JsonResult getQuestionList() {
        //获取当前登录人租户id
        String tenantId = CurrentUserUtil.getTenantId();
        //获取当前登录人信息
        User user = CurrentUserUtil.getUserInfo();
        //查询区域范范围问题
        List<InspectionFile> inspectionFileLists = new ArrayList<>();
        //超级管理员
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(Wrappers.<InspectionFile>lambdaQuery()
                    .eq(InspectionFile::getMark, 1)
                    .eq(InspectionFile::getTenantId, tenantId));
            for (InspectionFile inspectionFile : inspectionFileList) {
                //任务状态判断
                if (20 == inspectionFile.getStatus()) {
                    //任务状态判断，已生成工单，问题未解决
                    Inspection inspection = inspectionMapper.selectById(inspectionFile.getInspectionId());
                    if (ObjectUtil.isNull(inspection)) {
                        JsonResult.error("问题所属的任务不存在");
                    }
                    inspectionFileLists.add(inspectionFile);
                }
            }
        }
        //部门管理员及普通用户 本部门的问题
        else if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()
                || DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
            String deptId = user.getDeptId();
            if (StringUtils.isEmpty(deptId)) {
                return JsonResult.error(SectionEnum.DEPT_IS_NOT_EXIST.getCode(), SectionEnum.DEPT_IS_NOT_EXIST.getMsg());
            }
            List<String> deptList = new ArrayList<>();
            // 本部门及子部门权限
            if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()) {
                List<String> deptAndSubList = deptMapper.selectAllChildListById(deptId);
                if (StringUtils.isEmpty(deptAndSubList) && deptAndSubList.size() <= 0) {
                    return JsonResult.error(SectionEnum.DEPT_ID_IS_NULL.getCode(), SectionEnum.DEPT_ID_IS_NULL.getMsg());
                }
                deptList.addAll(deptAndSubList);
            }
            // 本部门权限
            else {
                deptList.add(deptId);
            }
            //根据用户查询对应的巡检任务id
            List<Inspection> inspectionList = inspectionMapper.selectList(new LambdaQueryWrapper<Inspection>()
                    .eq(Inspection::getTenantId, tenantId)
                    .eq(Inspection::getMark, 1)
                    .in(Inspection::getDeptId, deptList));
            //查询对应的问题
            for (Inspection inspection : inspectionList) {
                List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(Wrappers.<InspectionFile>lambdaQuery()
                        .eq(InspectionFile::getMark, 1)
                        .eq(InspectionFile::getTenantId, tenantId)
                        .eq(InspectionFile::getInspectionId, inspection.getId()));
                for (InspectionFile inspectionFile : inspectionFileList) {
                    //任务状态判断
                    if (20 == inspectionFile.getStatus()) {
                        //任务状态判断，已生成工单，问题未解决
                        Inspection inspections = inspectionMapper.selectById(inspectionFile.getInspectionId());
                        if (ObjectUtil.isNull(inspections)) {
                            JsonResult.error("问题所属的任务不存在");
                        }
                        inspectionFileLists.add(inspectionFile);
                    }
                }
            }
        }

        List<InspectionFileVo> list = inspectionFileLists.stream().map(x -> {
            InspectionFileVo vo = new InspectionFileVo();
            BeanUtils.copyProperties(x, vo);
            //标记图片
            vo.setFileImage(CommonConfig.imageURL + x.getFileImage());
            //任务名称
            if (StringUtils.isNotEmpty(x.getInspectionId())) {
                Inspection inspection = inspectionMapper.selectById(x.getInspectionId());
                if (ObjectUtil.isNull(inspection)) {
                    JsonResult.error();
                }
                vo.setName(inspection.getName());
                //问题类型
                if (StringUtils.isNotEmpty(x.getQuestionCode())) {
                    QuestionType questionType = questionTypeMapper.selectOne(new LambdaQueryWrapper<QuestionType>()
                            .eq(QuestionType::getMark, 1)
                            .eq(QuestionType::getCode, x.getQuestionCode()));
                    if (null != questionType) {
                        vo.setCode(questionType.getCode());
                        vo.setContent(questionType.getContent());
                        vo.setType(questionType.getName());
                    }
                }
            }

            return vo;
        }).collect(Collectors.toList());
        return JsonResult.success(list);
    }

    @Override
    public JsonResult getListByDeptUserType(InspectionFileQuery query) {
        return queryInspectionFileListByDeptUserTypeService.getListByDeptUserType(query);
    }

    /**
     * 根据任务ID查询任务问题分页列表
     *
     * @return
     */
    @Override
    public JsonResult getPageListByInspectionId(QueryInspectionFilePageListByInspectionIdRequest request) {
        return queryInspectionFilePageListByInspectionIdService.getPageListByInspectionId(request);
    }

    /**
     * 根据任务id查询问题列表
     * @param request
     * @return
     */
    @Override
    public JsonResult getListByInspectionId(QueryInspectionFileListByInspectionIdRequest request) {
        return queryInspectionFileListByInspectionIdService.getListByInspectionId(request);
    }

    /**
     * 查询任务问题分页列表
     *
     * @param request
     * @return
     */
    @Override
    public JsonResult getPageList(QueryInspectionFilePageListRequest request) {
        return queryInspectionFilePageListService.getPageList(request);
    }

    /**
     * 确认
     *
     * @param idList
     * @return
     */
    @Override
    public JsonResult confirm(List<String> idList) {
        return inspectionFileConfirmService.confirm(idList);
    }

    /**
     * 忽略
     *
     * @param idList
     * @return
     */
    @Override
    public JsonResult ignore(List<String> idList) {
        return inspectionFileIgnoreService.ignore(idList);
    }

    /**
     * 获取任务问题处理结果
     *
     * @param id
     * @return
     */
    @Override
    public JsonResult getHandle(String id) {
        return queryInspectionFileHandleByInspectionFileIdService.handle(id);
    }

    /**
     * 查询任务问题分布列表
     *
     * @param request
     * @return
     */
    @Override
    public JsonResult getDistributionList(QueryInspectionFileDistributionListRequest request) {
        return queryInspectionFileDistributionListService.getList(request);
    }

    /**
     * 根据工单ID查询工单问题列表
     *
     * @param request
     * @return
     */
    @Override
    public JsonResult getPageListByWorkOrderId(QueryInspectionFileWorkOrderPageListRequest request) {
        return queryInspectionFilePageListByWorkOrderIdService.getPageList(request);
    }

    /**
     * 处理任务问题
     *
     * @param request
     * @return
     */
    @Override
    public JsonResult processing(InspectionFileProcessingRresultRequest request) {
        return inspectionFileProcessingService.processing(request);
    }

    /**
     * 修改巡检任务问题类型
     *
     * @param id
     * @param questionCode
     * @return
     */
    @Override
    public JsonResult editQuestionType(String id, String questionCode) {
        return updateInspectionFileQuestionTypeService.update(id, questionCode);
    }

    /**
     * 删除问题
     *
     * @param idList
     * @return
     */
    @Override
    public JsonResult deletedByIdList(List<String> idList) {
        return deleteInspectionFileByIdListService.deletedByIdList(idList);
    }

    /**
     * 导出问题清单
     *
     * @param request
     * @return
     */
    @Override
    public JsonResult exportExcle(HttpServletResponse response, ExportInspectionFileRequest request) {
        return exportInspectionFileByIdListService.exportExcle(response, request);
    }

}
