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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.conver.InspectionConverMapper;
import com.tuoheng.admin.entity.Dept;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.code.inspection.QueryInspectionPageListCodeEnum;
import com.tuoheng.admin.mapper.DeptMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.request.inspection.QueryInspectionPageListRequest;
import com.tuoheng.admin.service.inspection.query.handle.GenerateInspectionFieldHander;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.inspection.InspectionVo;
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.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 查询巡检任务分页列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-22
 */
@Slf4j
@Service
public class QueryInspectionPageListService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    @Qualifier("executeHandle")
    private GenerateInspectionFieldHander executeHandle;

    @Autowired
    @Qualifier("liveHandle")
    private GenerateInspectionFieldHander liveHandle;

    @Autowired
    @Qualifier("playBackHandle")
    private GenerateInspectionFieldHander playBackHandle;

    @Autowired
    @Qualifier("problemVerifyHandleHandle")
    private GenerateInspectionFieldHander problemVerifyHandleHandle;

    @Autowired
    @Qualifier("problemDetailsHandleHandle")
    private GenerateInspectionFieldHander problemDetailsHandleHandle;

    @Autowired
    @Qualifier("problemCountHandle")
    private GenerateInspectionFieldHander problemCountHandle;

    @Autowired
    @Qualifier("resubmitHandle")
    private GenerateInspectionFieldHander resubmitHandle;

    @Autowired
    @Qualifier("deleteHandle")
    private GenerateInspectionFieldHander deleteHandle;

    @Autowired
    @Qualifier("editHandle")
    private GenerateInspectionFieldHander editHandle;

    @PostConstruct
    public void start() {
        executeHandle.setNextHandler(liveHandle);
        liveHandle.setNextHandler(playBackHandle);
        playBackHandle.setNextHandler(problemVerifyHandleHandle);
        problemVerifyHandleHandle.setNextHandler(problemDetailsHandleHandle);
        problemDetailsHandleHandle.setNextHandler(problemCountHandle);
        problemCountHandle.setNextHandler(deleteHandle);
        deleteHandle.setNextHandler(editHandle);
        editHandle.setNextHandler(resubmitHandle);
    }

    public JsonResult getPageList(QueryInspectionPageListRequest request) {
//        log.info("进入查询巡检任务分页列表业务");
        String userId = CurrentUserUtil.getUserId();
        String tenantId = CurrentUserUtil.getTenantId();
        request.setTenantId(tenantId);

        // 不查应急任务
        request.setType(1);

        JsonResult result = this.check(tenantId, request);
        if (0 != result.getCode()) {
            log.info("进入查询巡检任务分页列表业务：校验失败：{}", result.getMsg());
            return result;
        }

        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getTenantId, tenantId)
                .eq(User::getId, userId)
                .eq(User::getMark, 1));

        Dept dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId, tenantId)
                .eq(Dept::getId, user.getDeptId())
                .eq(Dept::getMark, 1));

        IPage<Inspection> pageData = null;
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            pageData = this.getAllList(request);
        } else if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()) {
            pageData = this.getListByDept(request, user);
        } else if (DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
            pageData = this.getListByDept(request, user);
        }

        if (null == pageData || pageData.getTotal() == 0) {
            log.info("获取任务分页列表为空");
            return JsonResult.success(pageData);
        }

        // 构造返回结果对象
        List<InspectionVo> inspectionVoList = this.buildIspectionVoList(user, dept, pageData.getRecords());

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

        return JsonResult.success(inspectionVoPageData);
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param queryInspectionRequest
     * @return
     */
    private JsonResult check(String tenantId, QueryInspectionPageListRequest queryInspectionRequest) {
        // 判断部门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 request
     * @return
     */
    private IPage<Inspection> getAllList(QueryInspectionPageListRequest request) {
        // 设置分页参数
        IPage<Inspection> page = new Page<>(request.getPage(), request.getLimit());
        // 查询结果
        IPage<Inspection> pageData = inspectionMapper.selectPageList(page, request);
        return pageData;
    }

    /**
     * 管理员和普通用户可查本部门及子部门的任务
     *      1)、如果前端检索条件，传了部门Id，则根据deptId来查
     *      2)、如果前端检索条件，部门Id为空，则表示查本部门及子部门的任务
     *
     * @param request
     * @return
     */
    private IPage<Inspection> getListByDept(QueryInspectionPageListRequest request, User user) {
        // 获取本部门及子孙部门id列表
        if (StringUtils.isEmpty(request.getDeptId())) {
            List<String> deptIdList = deptMapper.selectAllChildListById(user.getDeptId());
            request.setDeptIdList(deptIdList);
        }

        // 设置分页参数
        IPage<Inspection> page = new Page<>(request.getPage(), request.getLimit());
        // 查询结果
        IPage<Inspection> pageData = inspectionMapper.selectPageList(page, request);
        return pageData;
    }

    /**
     *  1）、查找已确认问题数、发现问题数字段
     *  2）、判断是否有操作权限：立即执行、直播、回放、问题详情、问题核实、重新提交
     *
     * @param user
     * @param dept
     * @param inspectionList
     * @return
     */
    private List<InspectionVo> buildIspectionVoList(User user, Dept dept, List<Inspection> inspectionList) {
        Map<String, String> deptMap = this.getDeptMap(inspectionList);
        List<InspectionVo> inspectionVoList = InspectionConverMapper.INSTANCE.fromInspectionListToInspectionVoList(inspectionList);
        String deptName;
        for (InspectionVo inspectionVo : inspectionVoList) {
            deptName = deptMap.get(inspectionVo.getDeptId());
            inspectionVo.setDeptName(deptName);
            if (StringUtils.isNotEmpty(inspectionVo.getAiVideoUrl())) {
                inspectionVo.setAiVideoUrl(CommonConfig.videoURL + inspectionVo.getAiVideoUrl());
            }
            executeHandle.handler(user, dept, inspectionVo);
        }
        return inspectionVoList;
    }

    /**
     *  设置任务列表中每一个任务的部门名称
     *      查询到的任务列表中的部门Id，作为部门id列表，查询所有的部门，该结果数据量不会太大，放到map中
     *
     * @param inspectionList
     * @return
     */
    private Map<String, String> getDeptMap(List<Inspection> inspectionList) {
        Map<String, String> map = new HashMap<>();
        List<String> deptIdList = inspectionList.stream().map(o -> o.getDeptId()).collect(Collectors.toList());
        List<Dept> deptList = deptMapper.selectListByIdList(deptIdList);
        for (Dept dept : deptList) {
            map.put(dept.getId(), dept.getName());
        }
        return map;
    }

}
