package com.tuoheng.miniprogram.service.impl;

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.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import com.tuoheng.miniprogram.dao.*;
import com.tuoheng.miniprogram.entity.Dept;
import com.tuoheng.miniprogram.entity.Inspection;
import com.tuoheng.miniprogram.entity.InspectionFile;
import com.tuoheng.miniprogram.entity.User;
import com.tuoheng.miniprogram.entity.query.InspectionQuery;
import com.tuoheng.miniprogram.enums.DataPermissionEnum;
import com.tuoheng.miniprogram.service.IInspectionService;
import com.tuoheng.miniprogram.utils.CurrentUserUtil;
import com.tuoheng.miniprogram.vo.InspectionInfoVo;
import com.tuoheng.miniprogram.vo.PlayBackInfoVo;
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.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author ChengWang
 * @Date 2022/11/21
 */
@Service
@Slf4j
public class InspectionServiceImpl implements IInspectionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private TenantMapper tenantMapper;

    /**
     * 任务列表(分页)
     *
     * @param query
     * @return
     */
    @Override
    public JsonResult index(InspectionQuery query) {
        if (null == query.getLimit() && null == query.getPage()) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //登录用户信息
        User userInfo = CurrentUserUtil.getUserInfo();
        String username = userInfo.getUsername();
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(StringUtils.isNotEmpty(username), User::getUsername, username)
                .eq(User::getStatus, 1).eq(User::getMark, 1));
        if (ObjectUtil.isNull(user)) {
            return null;
        }
        String tenantId = user.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            return null;
        }
        query.setTenantId(tenantId);
        query.setType(1);
        //查询部门及下级部门列表
        List<Dept> list = deptMapper.selectList(Wrappers.<Dept>lambdaQuery()
                .eq(Dept::getMark, 1));
        //初始部门id
        String deptIdInt = query.getDeptId();
        //获取当前部门对应的巡检任务
        //获取分页数据
        IPage<Inspection> page = new Page<>(query.getPage(), query.getLimit());
        IPage<InspectionInfoVo> pageDataVo = new Page<>(query.getPage(), query.getLimit());
        Date startTime = null;
        Date endTime = null;
        if (StringUtils.isNotEmpty(query.getTime())) {
            startTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, query.getTime() + " 00:00:00");
            endTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, query.getTime() + " 23:59:59");
        }
        query.setStartTimeDate(startTime);
        query.setEndTimeDate(endTime);
        Integer type = user.getDataPermission();
        if (null == type) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        List<InspectionInfoVo> inspectionInfoVoList = new ArrayList<>();
        //用户角色判断 1超级管理员 2部门管理员 3普通用户
        if (DataPermissionEnum.ALL.getCode() == type) {
            IPage<InspectionInfoVo> IPageData = inspectionMapper.queryPage(page, query);
            IPageData.getRecords().stream().forEach(x -> {
                //修改执行人属性
                User user1 = userMapper.selectById(x.getCreateUser());
                x.setCreateUser(user1.getRealname());
                int problemsFoundNum = 0;
                int problemsVerifiedNum = 0;
                List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(Wrappers.<InspectionFile>lambdaQuery()
                        .eq(StringUtils.isNotEmpty(x.getId()), InspectionFile::getInspectionId, x.getId())
                        .eq(InspectionFile::getTenantId, tenantId)
                        .eq(InspectionFile::getMark, 1));
                if (StringUtils.isNotEmpty(inspectionFileList)) {
                    problemsVerifiedNum = inspectionFileList.size();
                    long count = inspectionFileList.stream().filter(t -> t.getStatus() == 15).count();
                    long count1 = inspectionFileList.stream().filter(t -> t.getStatus() == 20).count();
                    long count2 = inspectionFileList.stream().filter(t -> t.getStatus() == 25).count();
                    problemsFoundNum = (int) (count + count1 + count2);
                }
                x.setFlag(0);
                x.setProblemsFoundNum(problemsFoundNum);
                x.setProblemsVerifiedNum(problemsVerifiedNum);
            });
            List<InspectionInfoVo> records = IPageData.getRecords();
            for (InspectionInfoVo record : records) {
                inspectionInfoVoList.add(record);
            }

        }
        //登录用户角色为部门管理员或普通用户
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == type || DataPermissionEnum.DEPT.getCode() == type) {
            // 根据部门id获取此部门id和所有下级部门id封装list集合
            List<String> deptLists = deptMapper.selectAllChildListById(query.getDeptId());
            if (StringUtils.isEmpty(deptLists)) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            for (int i = 0; i < deptLists.size(); i++) {
                String deptId = deptLists.get(i);
                query.setDeptId(deptId);
                IPage<InspectionInfoVo> pageData = inspectionMapper.queryPage(page, query);
                pageData.getRecords().stream().forEach(x -> {
                    //修改执行人属性
                    User user2 = userMapper.selectById(x.getCreateUser());
                    x.setCreateUser(user2.getRealname());
                    int problemsFoundNum = 0;
                    int problemsVerifiedNum = 0;
                    List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(Wrappers.<InspectionFile>lambdaQuery()
                            .eq(StringUtils.isNotEmpty(x.getId()), InspectionFile::getInspectionId, x.getId())
                            .eq(InspectionFile::getTenantId, tenantId)
                            .eq(InspectionFile::getMark, 1));
                    if (StringUtils.isNotEmpty(inspectionFileList)) {
                        problemsVerifiedNum = inspectionFileList.size();
                        long count = inspectionFileList.stream().filter(t -> t.getStatus() == 15).count();
                        long count1 = inspectionFileList.stream().filter(t -> t.getStatus() == 20).count();
                        long count2 = inspectionFileList.stream().filter(t -> t.getStatus() == 25).count();
                        problemsFoundNum = (int) (count + count1 + count2);
                    }
                    //获取任务deptId1:1为部门任务 0为子部门任务
                    if (deptIdInt.equals(deptId)) {
                        x.setFlag(1);
                    } else {
                        x.setFlag(0);
                    }
                    x.setProblemsFoundNum(problemsFoundNum);
                    x.setProblemsVerifiedNum(problemsVerifiedNum);
                });
                List<InspectionInfoVo> records = pageData.getRecords();
                for (InspectionInfoVo record : records) {
                    inspectionInfoVoList.add(record);
                }
            }
        }

        pageDataVo.setRecords(inspectionInfoVoList);


        return JsonResult.success(pageDataVo);
    }


    @Override
    public JsonResult playback(String id) {
        //参数校验
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //获取租户id
        String tenantId = CurrentUserUtil.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            return JsonResult.error("租户id为空");
        }
        //根据任务id获取任务
        Inspection inspection = inspectionMapper.selectOne(Wrappers.<Inspection>lambdaQuery()
                .eq(Inspection::getTenantId, tenantId)
                .eq(Inspection::getMark, 1)
                .eq(Inspection::getId, id));
        PlayBackInfoVo vo = new PlayBackInfoVo();
        BeanUtils.copyProperties(inspection, vo);
        //对视频地址进行处理
        if (StringUtils.isNotEmpty(inspection.getAiVideoUrl())) {
            vo.setAiVideoUrl(CommonConfig.videoURL + inspection.getAiVideoUrl());
        }

        return JsonResult.success(vo);
    }

    @Override
    public JsonResult deleteById(String id) {
        if (id == null || StringUtils.isEmpty(id)) {
            return JsonResult.error("记录ID不能为空");
        }
        // 设置Mark=0
        Inspection inspection = inspectionMapper.selectOne(Wrappers.<Inspection>lambdaQuery()
                .eq(Inspection::getId, id));
        inspection.setMark(0);
        //判断当前任务下的问题是否存在，存在则删除
        List<InspectionFile> inspectionFiles = inspectionFileMapper.selectList(new LambdaQueryWrapper<InspectionFile>()
                .eq(InspectionFile::getInspectionId, id));
        if (StringUtils.isEmpty(inspectionFiles)) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        Integer num = 0;
        for (InspectionFile inspectionFile : inspectionFiles) {
            inspectionFile.setMark(0);
            int i = inspectionFileMapper.updateById(inspectionFile);
            num += i;
        }
        int count = inspectionMapper.updateById(inspection);
        if (count <= 0 && num != inspectionFiles.size()) {
            return JsonResult.error();
        }

        return JsonResult.success("删除成功");

    }


    /**
     * 递归获取部门的子集
     *
     * @author zhu_zishuang
     * @date 3/13/21
     */
    private List<Dept> getChildren(Dept rootDept, List<Dept> list) {
        return list.stream().filter(dept ->
                dept.getPid().equals(rootDept.getId())
        ).peek(dept -> {
            // 设置子集
            dept.setItemList(getChildren(dept, list));
        }).sorted(Comparator.comparingInt(dept -> (dept.getSort() == null ? 0 : dept.getSort()))).collect(Collectors.toList());
    }
}
