package com.tuoheng.admin.service.inspectionfile;

import cn.hutool.core.collection.CollectionUtil;
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.code.inspectionfile.ListByDeptUserTypeEnum;
import com.tuoheng.admin.enums.code.questiontype.QuestionTypeEnum;
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.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.QueryInspectionFileDistributionListService;
import com.tuoheng.admin.service.inspectionfile.query.QueryInspectionFilePageListByInspectionIdService;
import com.tuoheng.admin.service.inspectionfile.query.QueryInspectionFilePageListByWorkOrderIdService;
import com.tuoheng.admin.service.inspectionfile.query.QueryInspectionFilePageListService;
import com.tuoheng.admin.service.inspectionfile.update.UpdateInspectionFileQuestionTypeService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.inspection.InspectionFileVo;
import com.tuoheng.admin.vo.ListByDeptUserTypeVo;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.enums.ServiceExceptionEnum;
import com.tuoheng.common.core.exception.ServiceException;
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 java.util.ArrayList;
import java.util.Collections;
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 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;

    /**
     * 问题类型和任务名称
     *
     * @return
     */
    @Override
    public JsonResult getQuestionList() {
        //获取当前登录人租户id
        String tenantId = CurrentUserUtil.getTenantId();
        //获取当前登录人信息
        User user = CurrentUserUtil.getUserInfo();
        //获取用户角色
        Integer type = user.getDataPermission();
        if (type == null) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //查询区域范范围问题
        List<InspectionFile> inspectionFileLists = new ArrayList<>();
        //超级管理员
        if (DataPermissionEnum.ALL.getCode() == type) {
            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);
                }
            }
        }
        //部门管理员及普通用户 本部门的问题
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == type || DataPermissionEnum.DEPT.getCode() == type) {
            //根据用户查询对应的巡检任务id
            List<Inspection> inspectionList = inspectionMapper.selectList(new LambdaQueryWrapper<Inspection>()
                    .eq(Inspection::getTenantId, tenantId)
                    .eq(Inspection::getMark, 1)
                    .eq(Inspection::getDeptId, user.getDeptId()));
            //查询对应的问题
            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) {
        User user = CurrentUserUtil.getUserInfo();
        //用户角色判断 1超级管理员 2部门管理员 3普通用户
        if (null == user.getDataPermission()) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        List<ListByDeptUserTypeVo> list = new ArrayList<>();
        ListByDeptUserTypeVo vo = new ListByDeptUserTypeVo();
        ListByDeptUserTypeVo vo1 = new ListByDeptUserTypeVo();
        ListByDeptUserTypeVo vo2 = new ListByDeptUserTypeVo();
        ListByDeptUserTypeVo vo3 = new ListByDeptUserTypeVo();
        ListByDeptUserTypeVo vo4 = new ListByDeptUserTypeVo();
        ListByDeptUserTypeVo vo5 = new ListByDeptUserTypeVo();
        //坑槽 积水 裂缝
        //0纵向裂缝
        Integer longitudinalCrackNum = 0;
        //4坑槽
        Integer pitGrooveNum = 0;
        //6积水
        Integer ponDingNum = 0;
        //1横向裂缝
        Integer abeamCrackNum = 0;
        //3网状裂纹
        Integer reticularCrackNum = 0;
        //5块状裂纹
        Integer massiveCrack = 0;
        //若角色为超级管理员，查看状态为已生成工单和和问题已处理
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            //直接查问题列表
            List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(Wrappers.<InspectionFile>lambdaQuery()
                    .eq(InspectionFile::getMark, 1)
                    .eq(InspectionFile::getTenantId, user.getTenantId())
                    .in(InspectionFile::getStatus, 20, 25));
            //根据状态类型分类
            if (null == inspectionFileList) {
                JsonResult.error(ListByDeptUserTypeEnum.INSPECTION_TYPE_LIST_IS_NULL.getCode(), ListByDeptUserTypeEnum.INSPECTION_TYPE_LIST_IS_NULL.getMsg());
            }
            for (InspectionFile inspectionFile : inspectionFileList) {
                if (StringUtils.isEmpty(inspectionFile.getQuestionCode())) {
                    JsonResult.error(ListByDeptUserTypeEnum.QUESTION_ID_IS_NULL.getCode(), ListByDeptUserTypeEnum.QUESTION_ID_IS_NULL.getMsg());
                }
                //查找问题类型
                QuestionType questionType = questionTypeMapper.selectOne(Wrappers.<QuestionType>lambdaQuery()
                        .eq(QuestionType::getMark, 1)
                        .eq(QuestionType::getCode, inspectionFile.getQuestionCode()));
                if (ObjectUtil.isNull(questionType)) {
                    throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                }
                Integer name = questionType.getName();
                if (name == QuestionTypeEnum.ABEAM_CRACK_NAME.getCode()) {
                    //1横向裂缝
                    abeamCrackNum += 1;
                } else if (name == QuestionTypeEnum.RETICULAR_CRACK_NAME.getCode()) {
                    //3网状裂纹
                    reticularCrackNum += 1;
                } else if (name == QuestionTypeEnum.PIT_GROOVE_NAME.getCode()) {
                    //4坑槽
                    pitGrooveNum += 1;
                } else if (name == QuestionTypeEnum.MASSIVE_CRACK_NAME.getCode()) {
                    //5块状裂纹
                    massiveCrack += 1;
                } else if (name == QuestionTypeEnum.PON_DING_NAME.getCode()) {
                    //6积水
                    ponDingNum += 1;
                } else if (name == QuestionTypeEnum.LONGITUDINAL_CRACK_NAME.getCode()) {
                    //0纵向裂缝
                    longitudinalCrackNum += 1;
                }
            }
            vo.setType(QuestionTypeEnum.ABEAM_CRACK_NAME.getCode());
            vo.setNum(abeamCrackNum);
            vo1.setType(QuestionTypeEnum.RETICULAR_CRACK_NAME.getCode());
            vo1.setNum(reticularCrackNum);
            vo2.setType(QuestionTypeEnum.PIT_GROOVE_NAME.getCode());
            vo2.setNum(pitGrooveNum);
            vo3.setType(QuestionTypeEnum.MASSIVE_CRACK_NAME.getCode());
            vo3.setNum(massiveCrack);
            vo4.setType(QuestionTypeEnum.PON_DING_NAME.getCode());
            vo4.setNum(ponDingNum);
            vo5.setType(QuestionTypeEnum.LONGITUDINAL_CRACK_NAME.getCode());
            vo5.setNum(longitudinalCrackNum);
            Collections.addAll(list, vo, vo1, vo2, vo3, vo4, vo5);
        }
        //若角色为部门管理员或普通用户
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission() || DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
            //获取用户对应的部门
            String deptId = user.getDeptId();
            if (StringUtils.isEmpty(deptId)) {
                JsonResult.error(ListByDeptUserTypeEnum.DEPT_ID_IS_NULL.getCode(), ListByDeptUserTypeEnum.DEPT_ID_IS_NULL.getMsg());
            }
            //根据部门id获取部门id列表
            List<String> deptIdList = deptMapper.selectAllChildListById(deptId);
            if (CollectionUtil.isEmpty(deptIdList)) {
                return null;
            }
            //根据部门id列表查多条任务
            List<Inspection> inspectionList = inspectionMapper.selectListByDeptIdList(deptIdList);
            if (null == inspectionList) {
                JsonResult.error(ListByDeptUserTypeEnum.INSPECTION_LIST_IS_NULL.getCode(), ListByDeptUserTypeEnum.INSPECTION_LIST_IS_NULL.getMsg());
            }
            List<String> inspectionIdList = inspectionList.stream().map(o -> o.getId()).collect(Collectors.toList());
            //根据任务id列表查找多条问题
            List<InspectionFile> inspectionFileList = inspectionFileMapper.selectListByInspectIdList(inspectionIdList);
            //根据状态类型分类
            if (null == inspectionFileList) {
                JsonResult.error(ListByDeptUserTypeEnum.INSPECTION_TYPE_LIST_IS_NULL.getCode(), ListByDeptUserTypeEnum.INSPECTION_TYPE_LIST_IS_NULL.getMsg());
            }
            for (InspectionFile inspectionFile : inspectionFileList) {
                if (StringUtils.isEmpty(inspectionFile.getQuestionCode())) {
                    JsonResult.error(ListByDeptUserTypeEnum.QUESTION_ID_IS_NULL.getCode(), ListByDeptUserTypeEnum.QUESTION_ID_IS_NULL.getMsg());
                }
                //查找问题类型
                QuestionType questionType = questionTypeMapper.selectOne(Wrappers.<QuestionType>lambdaQuery()
                        .eq(QuestionType::getMark, 1)
                        .eq(QuestionType::getCode, inspectionFile.getQuestionCode()));
                if (ObjectUtil.isNull(questionType)) {
                    throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
                }
                Integer name = questionType.getName();
                if (name == QuestionTypeEnum.ABEAM_CRACK_NAME.getCode()) {
                    //1横向裂缝
                    abeamCrackNum += 1;
                } else if (name == QuestionTypeEnum.RETICULAR_CRACK_NAME.getCode()) {
                    //3网状裂纹
                    reticularCrackNum += 1;
                } else if (name == QuestionTypeEnum.PIT_GROOVE_NAME.getCode()) {
                    //4坑槽
                    pitGrooveNum += 1;
                } else if (name == QuestionTypeEnum.MASSIVE_CRACK_NAME.getCode()) {
                    //5块状裂纹
                    massiveCrack += 1;
                } else if (name == QuestionTypeEnum.PON_DING_NAME.getCode()) {
                    //6积水
                    ponDingNum += 1;
                } else if (name == QuestionTypeEnum.LONGITUDINAL_CRACK_NAME.getCode()) {
                    //0纵向裂缝
                    longitudinalCrackNum += 1;
                }
            }
            vo.setType(QuestionTypeEnum.ABEAM_CRACK_NAME.getCode());
            vo.setNum(abeamCrackNum);
            vo1.setType(QuestionTypeEnum.RETICULAR_CRACK_NAME.getCode());
            vo1.setNum(reticularCrackNum);
            vo2.setType(QuestionTypeEnum.PIT_GROOVE_NAME.getCode());
            vo2.setNum(pitGrooveNum);
            vo3.setType(QuestionTypeEnum.MASSIVE_CRACK_NAME.getCode());
            vo3.setNum(massiveCrack);
            vo4.setType(QuestionTypeEnum.PON_DING_NAME.getCode());
            vo4.setNum(ponDingNum);
            vo5.setType(QuestionTypeEnum.LONGITUDINAL_CRACK_NAME.getCode());
            vo5.setNum(longitudinalCrackNum);
            Collections.addAll(list, vo, vo1, vo2, vo3, vo4, vo5);

        }

        return JsonResult.success(list);
    }

    /**
     * 根据任务ID查询任务问题分页列表
     *
     * @return
     */
    @Override
    public JsonResult getPageListByInspectionId(QueryInspectionFilePageListByInspectionIdRequest request) {
        return queryInspectionFilePageListByInspectionIdService.getPageListByInspectionId(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);
    }
}
