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

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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.conver.InspectionConverMapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.inspection.QueryInspectionPageListRequest;
import com.tuoheng.admin.service.inspection.query.handle.GenerateInspectionFieldHander;
import com.tuoheng.admin.service.third.airport.AirportService;
import com.tuoheng.admin.service.third.airport.GetAirportListByAirportIds;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.AirportInfoVo;
import com.tuoheng.admin.vo.AirportLineVo;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
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;

    @Autowired
    private RoadInformationMapper roadInformationMapper;

    @Autowired
    private SectionMapper sectionMapper;

    @Autowired
    private AirportService airportService;

    @Autowired
    private GetAirportListByAirportIds getAirportListByAirportIds;

    @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("进入查询巡检任务分页列表业务");
        User user = CurrentUserUtil.getUserInfo();
        String tenantId = user.getTenantId();

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

        if (StringUtils.isEmpty(request.getDeptId())) {
            List<String> deptIdList = new ArrayList<>();
            if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            } else if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()) {
                deptIdList = deptMapper.selectAllChildListById(user.getDeptId());
            } else if (DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
                deptIdList.add(user.getDeptId());
            }
            request.setDeptIdList(deptIdList);
        }

        request.setTenantId(tenantId);

        IPage<Inspection> page = new Page<>(request.getPage(), request.getLimit());
        IPage<Inspection> pageData = inspectionMapper.selectPageList(page, request);

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

        // 构造返回结果对象
        List<InspectionVo> inspectionVoList = this.buildIspectionVoList(user, null, 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);
        Map<String, RoadInformation> roadInformationMap = this.getRoadInformationMap(inspectionList);
        Map<String, Section> sectionMap = this.getSectionMap(inspectionList);
        Map<Integer, AirportLineVo> airportLineMap = this.getAirportLineMap(inspectionList);
        Map<String, AirportInfoVo> airportMap = this.getAirportMap(inspectionList);
        Map<String, User> userMap = this.getUserMap(inspectionList);

        String deptName;
        RoadInformation roadInformation;
        Section section;
        User createUser;

        for (InspectionVo inspectionVo : inspectionVoList) {
            deptName = deptMap.get(inspectionVo.getDeptId());
            inspectionVo.setDeptName(deptName);
            if (StringUtils.isNotEmpty(inspectionVo.getAiVideoUrl())) {
                inspectionVo.setAiVideoUrl(CommonConfig.videoURL + inspectionVo.getAiVideoUrl());
            }
            if (ObjectUtil.isNotEmpty(roadInformationMap)) {
                roadInformation = roadInformationMap.get(inspectionVo.getRoadId());
                if (ObjectUtil.isNotEmpty(roadInformation)) {
                    inspectionVo.setRoadName(roadInformation.getName());
                }
            }
            if (ObjectUtil.isNotEmpty(sectionMap)) {
                section = sectionMap.get(inspectionVo.getSectionId());
                if (ObjectUtil.isNotEmpty(section)) {
                    inspectionVo.setSectionName(section.getSectionRange());
                }
            }
            //机场名称
            if (CollectionUtil.isNotEmpty(airportMap)) {
                if (ObjectUtil.isNotEmpty(airportMap.get(String.valueOf(inspectionVo.getAirportId())))) {
                    inspectionVo.setAirportName(airportMap.get(String.valueOf(inspectionVo.getAirportId())).getName());
                }
            }
            //航线名称
            if (CollectionUtil.isNotEmpty(airportLineMap)) {
                if (ObjectUtil.isNotEmpty(airportLineMap.get(inspectionVo.getInspectionLine()))) {
                    inspectionVo.setInspectionLineName(airportLineMap.get(inspectionVo.getInspectionLine()).getFileName());
                }
            }
            //创建人名称
            if (CollectionUtil.isNotEmpty(userMap)) {
                createUser = userMap.get(inspectionVo.getCreateUser());
                if (ObjectUtil.isNotEmpty(userMap.get(inspectionVo.getCreateUser()))) {
                    inspectionVo.setCreateUserName(createUser.getRealname());
                }
            }

            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;
    }

    private Map<String, User> getUserMap(List<Inspection> inspectionList) {
        List<String> userIdList = inspectionList.stream().map(o -> o.getCreateUser()).collect(Collectors.toList());
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>()
                .in(User::getId, userIdList)
                .eq(User::getMark, MarkEnum.VALID.getCode()));
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        return userMap;
    }

    /**
     * 获取公路列表，放到map，减少循环次数
     *
     * @param inspectionList
     * @return
     */
    private Map<String, RoadInformation> getRoadInformationMap(List<Inspection> inspectionList) {
        List<String> roadInformationIdList = inspectionList.stream().map(o -> o.getRoadId()).collect(Collectors.toList());
        List<RoadInformation> roadInformationList = roadInformationMapper.selectList(new LambdaQueryWrapper<RoadInformation>()
                .in(RoadInformation::getId, roadInformationIdList)
                .eq(RoadInformation::getMark, MarkEnum.VALID.getCode()));
        Map<String, RoadInformation> roadInformationMap = roadInformationList.stream().collect(Collectors.toMap(RoadInformation::getId, Function.identity()));
        return roadInformationMap;
    }

    /**
     * 获取路段列表，放到map，减少循环次数
     *
     * @param inspectionList
     * @return
     */
    private Map<String, Section> getSectionMap(List<Inspection> inspectionList) {
        List<String> sectionIdList = inspectionList.stream().map(o -> o.getSectionId()).collect(Collectors.toList());
        List<Section> sectionList = sectionMapper.selectList(new LambdaQueryWrapper<Section>()
                .in(Section::getId, sectionIdList)
                .eq(Section::getMark, MarkEnum.VALID.getCode()));
        Map<String, Section> sectionMap = sectionList.stream().collect(Collectors.toMap(Section::getId, Function.identity()));
        return sectionMap;
    }


    private Map<String, AirportInfoVo> getAirportMap(List<Inspection> inspectionList) {
        List<Integer> airportIdList = inspectionList.stream().map(o -> o.getAirportId()).collect(Collectors.toList());
        String airportIds = airportIdList.stream().distinct().map(x -> String.valueOf(x)).collect(Collectors.joining(",", "", ""));
        List<AirportInfoVo> airportInfoVoList = airportService.getAirportInfoList(airportIds);
        if (CollectionUtil.isEmpty(airportInfoVoList)) {
            return null;
        }
        Map<String, AirportInfoVo> airportMap = airportInfoVoList.stream().collect(Collectors.toMap(AirportInfoVo::getId, Function.identity()));
        return airportMap;
    }

    private Map<Integer, AirportLineVo> getAirportLineMap(List<Inspection> inspectionList) {
        List<Integer> airportLineIdList = inspectionList.stream().map(o -> o.getInspectionLine()).collect(Collectors.toList());
        List<AirportLineVo> airportLineVoList = airportService.getAirportLineListByAirportIdAndLineIdList(null, airportLineIdList);
        if (CollectionUtil.isEmpty(airportLineVoList)) {
            return null;
        }
        Map<Integer, AirportLineVo> airportLineMap = airportLineVoList.stream().collect(Collectors.toMap(AirportLineVo::getId, Function.identity()));
        return airportLineMap;
    }


}
