package com.tuoheng.admin.service.workorder.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.WorkOrderConverMapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.InspectionFileStatusEnum;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.code.inspection.QueryInspectionPageListCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.workorder.QueryWorkOrderPageListRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.workorder.WorkOrderPageListVo;
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.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 查询工单分页列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-06
 */
@Slf4j
@Service
public class QueryWorkOrderPageListService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private WorkOrderFileMapper workOrderFileMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    public JsonResult getPageList(QueryWorkOrderPageListRequest request) {
        log.info("进入查询工单分页列表业务, request:{}", request.toString());
        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("进入查询工单分页列表业务：校验失败：{}", result.getMsg());
            return result;
        }
        User user = CurrentUserUtil.getUserInfo();
        if (DataPermissionEnum.ALL.getCode() != user.getDataPermission()) {
            request.setUserDeptId(user.getDeptId());
        }
        String tenantId = user.getTenantId();
        request.setTenantId(tenantId);
        // 获取部门Id的查询范围
        List<String> deptIdList = this.getDeptIdList(user, request.getDeptId());
        request.setDeptIdList(deptIdList);

        // 设置分页参数
        IPage<InspectionFile> page = new Page<>(request.getPage(), request.getLimit());
        // 查询结果
        IPage<WorkOrder> pageData = workOrderMapper.selectPageList(page, request);
        if (null == pageData || pageData.getTotal() == 0) {
            log.info("获取任务分页列表为空");
            return JsonResult.success(pageData);
        }

        // 构造返回结果对象
        List<WorkOrderPageListVo> workOrderPageListVoList = this.buildPageList(pageData.getRecords());

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

        return JsonResult.success(workOrderPageListVoPageData);
    }

    /**
     * 检查参数
     *
     * @param request
     * @return
     */
    private JsonResult check(QueryWorkOrderPageListRequest request) {

        return JsonResult.success();
    }

    /**
     * 获取部门Id的查询范围
     * 1）、deptId：如果传了值，查该部门的任务
     * 2）、deptId：如果没有传值
     * 2.1）、管理员：可查全部确认问题
     * 2.2）、管理员/普通用户：本部门及子部门创建的工单
     *
     * @param deptId
     * @return
     */
    private List<String> getDeptIdList(User user, String deptId) {
        List<String> deptIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(deptId)) {
            deptIdList.add(deptId);
            return deptIdList;
        }
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            return null;
        } else {
            deptIdList = deptMapper.selectAllChildListById(user.getDeptId());
            return deptIdList;
        }
    }

    /**
     * 处理字段
     * 1)、部门名称
     * 2)、分配人员名称
     * 3)、问题总数
     * 4)、已处理问题数
     *
     * @param workOrderList
     * @return
     */
    private List<WorkOrderPageListVo> buildPageList(List<WorkOrder> workOrderList) {
        Map<String, Dept> deptMap = this.getDeptMap(workOrderList);
        Map<String, User> userMap = this.getUserMap(workOrderList);
        Map<String, User> assignUserMap = this.getAssignUserMap(workOrderList);
        Map<String, List<WorkOrderFile>> workOrderFileMap = this.getWorkOrderFileMap(workOrderList);

        List<String> inspectionFileIdList;
        List<InspectionFile> inspectionFileList;
        List<WorkOrderPageListVo> workOrderPageListVoList = WorkOrderConverMapper.INSTANCE.fromWorkOrderListToWorkOrderPageListVoList(workOrderList);
        Dept dept;
        User user;
        User assignUser;
        String assignUserNames;
        List<WorkOrderFile> workOrderFileList;
        for (WorkOrderPageListVo workOrderPageListVo : workOrderPageListVoList) {
            assignUserNames = "";
            dept = deptMap.get(workOrderPageListVo.getDeptId());
            user = userMap.get(workOrderPageListVo.getDistributionId());
            workOrderFileList = workOrderFileMap.get(workOrderPageListVo.getId());
            if (!CollectionUtil.isEmpty(workOrderFileList)) {
                inspectionFileIdList = workOrderFileList.stream().map(o -> o.getInspectionFileId()).collect(Collectors.toList());
                inspectionFileList = inspectionFileMapper.selectBatchIds(inspectionFileIdList);
                List<InspectionFile> inspectionFileListTmp = inspectionFileList.stream().filter(s -> s.getStatus() == InspectionFileStatusEnum.PROCESSED.getCode()).collect(Collectors.toList());
                workOrderPageListVo.setProblemTotalCount(workOrderFileList.size());
                workOrderPageListVo.setProcessedProblemCount(inspectionFileListTmp.size());
            }
            if (null != dept) {
                workOrderPageListVo.setDeptName(dept.getName());
            }
            if (null != user) {
                workOrderPageListVo.setDistributionName(user.getRealname());
            }

            String assignUsers = workOrderPageListVo.getAssignUser();
            if (StringUtils.isNotEmpty(assignUsers) && ObjectUtil.isNotNull(assignUserMap)) {
                String[] assignUserArr = assignUsers.split(",");
                for (String au : assignUserArr) {
                    assignUser = assignUserMap.get(au);
                    if (ObjectUtil.isNotNull(assignUser)) {
                        assignUserNames += assignUser.getRealname() + ",";
                    }
                }
            }
            if (!StringUtils.isEmpty(assignUserNames)) {
                assignUserNames = assignUserNames.substring(0, assignUserNames.length() - 1);
                workOrderPageListVo.setAssignUserNames(assignUserNames);
            }
        }
        return workOrderPageListVoList;
    }

    /**
     * 获取部门列表，放到map，减少循环次数
     *
     * @param workOrderList
     * @return
     */
    private Map<String, Dept> getDeptMap(List<WorkOrder> workOrderList) {
        List<String> deptIdList = workOrderList.stream().map(o -> o.getDeptId()).collect(Collectors.toList());
        List<Dept> deptList = deptMapper.selectList(new LambdaQueryWrapper<Dept>()
                .in(Dept::getId, deptIdList)
                .eq(Dept::getMark, 1));
        Map<String, Dept> deptMap = deptList.stream().collect(Collectors.toMap(Dept::getId, Function.identity()));
        return deptMap;
    }

    /**
     * 获取用户列表，放到map，减少循环次数
     *
     * @param workOrderList
     * @return
     */
    private Map<String, User> getUserMap(List<WorkOrder> workOrderList) {
        List<String> distributionIdList = workOrderList.stream().map(o -> o.getDistributionId()).collect(Collectors.toList());
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>()
                .in(User::getId, distributionIdList)
                .eq(User::getMark, 1));
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        return userMap;
    }

    /**
     * 获取指派用户列表，放到map，减少循环次数
     *
     * @param workOrderList
     * @return
     */
    private Map<String, User> getAssignUserMap(List<WorkOrder> workOrderList) {
        List<String> assignUserIdList = workOrderList.stream().map(o -> o.getDistributionId()).collect(Collectors.toList());
        List<String> tmpList;
        for (WorkOrder workOrder : workOrderList) {
            String assignUser = workOrder.getAssignUser();
            if (!StringUtils.isEmpty(assignUser)) {
                String[] arr = assignUser.split(",");
                tmpList = Arrays.asList(arr);
                assignUserIdList.addAll(tmpList);
            }
        }
        List<User> userList = null;
        if (CollectionUtil.isNotEmpty(assignUserIdList)) {
            userList = userMapper.selectList(new LambdaQueryWrapper<User>()
                    .in(User::getId, assignUserIdList)
                    .eq(User::getMark, 1));
        }
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        return userMap;
    }

    private Map<String, List<WorkOrderFile>> getWorkOrderFileMap(List<WorkOrder> workOrderList) {
        List<String> workOrderIdList = workOrderList.stream().map(o -> o.getId()).collect(Collectors.toList());
        List<WorkOrderFile> workOrderFileList = workOrderFileMapper.selectList(new LambdaQueryWrapper<WorkOrderFile>()
                .in(WorkOrderFile::getWorkOrderId, workOrderIdList));
        Map<String, List<WorkOrderFile>> workOrderFileMap = workOrderFileList.stream().collect(Collectors.groupingBy(WorkOrderFile::getWorkOrderId));
        return workOrderFileMap;
    }

}
