package com.jeeplus.test.garbageClearance.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.security.jwt.TokenProvider;
import com.jeeplus.sys.constant.CacheNames;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.garbageClearance.domain.LookOver;
import com.jeeplus.test.garbageClearance.mapper.LookOverMapper;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.domain.WorkAttachmentInfo;
import com.jeeplus.test.oss.service.OssService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.jeeplus.test.garbageClearance.service.DTO.LookOverDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王强
 * @version 1.0
 * @date 2024-08-29 10:51
 */
@Service
@Transactional
public class LookOverService extends ServiceImpl<LookOverMapper, LookOver> {

    @Autowired
    private OssService ossService;
    @Autowired
    private OfficeService officeService;

    public String getMaxNo() {
        // 创建查询条件构造器
        QueryWrapper<LookOver> queryWrapper = new QueryWrapper<>();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        queryWrapper.in("year",year);
        // 按no字段降序排列
        queryWrapper.orderByDesc("number");
        queryWrapper.last("limit 1");

        // 只获取第一条记录
        LookOver lookOver = baseMapper.selectOne(queryWrapper);

        // 返回最大的no值
        return lookOver != null ? lookOver.getNo() : null;
    }

    public LookOver selectOne() {
        //获取当前人所属部门信息
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        Office office = officeService.getById(currentUserDTO.getOfficeDTO().getId());

        // 创建查询条件构造器
        QueryWrapper<LookOver> queryWrapper = new QueryWrapper<>();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        queryWrapper.in("year",year);
        queryWrapper.eq("office_code",office.getCode());
        // 按no字段降序排列
        queryWrapper.orderByDesc("number");
        queryWrapper.last("limit 1");

        // 只获取第一条记录
        LookOver lookOver = baseMapper.selectOne(queryWrapper);
        // 返回最大的no值
        return lookOver;
    }

    public UserDTO getUserInfoByOffId(String officeId) {
        return baseMapper.getUserInfoByOffId(officeId);
    }

    public List<UserDTO> getOfficeOnHamlet() {
        return baseMapper.getOfficeOnHamlet();
    }

    /**
     * 根据id获取巡视工单信息
     * @param id
     * @return
     */
    public LookOver selectByID(String id) {
        LookOver lookOver = baseMapper.selectByID(id);
        List<WorkAttachmentInfo> files = baseMapper.getByAttachmentIdAndFlag(id,"before");

        List<WorkAttachment> fileList1 = ossService.findFileList(id, "before");
        lookOver.setBeforeFileList(fileList1);
        List<WorkAttachment> fileList2 = ossService.findFileList(id, "between");
        lookOver.setBetweenFileList(fileList2);
        List<WorkAttachment> fileList3 = ossService.findFileList(id, "after");
        lookOver.setAfterFileList(fileList3);
        if (null != files && files.size()>0) {
            files.forEach(fi->{
                String fileTemporaryLookUrl = ossService.getFileTemporaryLookUrl(fi.getUrl());
                fi.setUrl(fileTemporaryLookUrl);
            });

            lookOver.setFileList1(files);
        }

        // 根据id 从work_attachment 表中获取图片信息
        return lookOver;
    }



    /**
     * 查询无报告项目及老项目列表信息
     * @param page
     * @param lookOver
     * @return
     * @throws Exception
     */
    public IPage<LookOver> getNotDisposeList(Page<LookOverDTO> page, LookOverDTO lookOver) throws Exception{
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        QueryWrapper<LookOverDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( lookOver, LookOverDTO.class );
        queryWrapper.eq("a.del_flag","0");
        queryWrapper.eq("a.processing_unit",userDTO.getOfficeDTO().getId());
        queryWrapper.eq("a.status","5");
        if(StringUtils.isNotBlank(lookOver.getDisposeStatus())){
            queryWrapper.eq("a.dispose_status",lookOver.getDisposeStatus());
        }
        IPage<LookOver> pageList = baseMapper.findPage(page, queryWrapper);
        for (LookOver record : pageList.getRecords()) {
            if(StringUtils.isNotBlank(record.getNo())){
                String no = record.getNo();
                //String no = "XS-J" + record.getNo();
                record.setNo(no);
            }
        }
        return pageList;
    }


    /**
     * 查询无报告项目及老项目列表信息
     * @param idList
     * @param attachmentFlag
     * @return
     * @throws Exception
     */
    public List<LookOver> getFileListByIdList(List<String> idList, String attachmentFlag){

        List<LookOver> list = baseMapper.getListByIdList(idList);
        List<WorkAttachmentInfo> fileList = ossService.findFileInfoList(idList, attachmentFlag);
        for (WorkAttachmentInfo workAttachmentInfo : fileList) {
            workAttachmentInfo.setUrl(workAttachmentInfo.getTemporaryUrl());
        }

        //对数据进行分组
        Map<String, List<WorkAttachmentInfo>> temporaryListMap = dataMessageDispose(fileList);

        for (LookOver record : list) {
            for (String key : temporaryListMap.keySet()) {

                if(StringUtils.isNotBlank(record.getId()) && record.getId().equals(key)){
                    List<WorkAttachmentInfo> mapList = temporaryListMap.get(key);
                    record.setFileList1(mapList);
                }
            }

        }
        return list;
    }


    /**
     * 分组
     * @param list
     * @return
     */
    private Map<String, List<WorkAttachmentInfo>> dataMessageDispose(List<WorkAttachmentInfo> list) {
        Map<String, List<WorkAttachmentInfo>> infoMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            // 分组
            for (WorkAttachmentInfo vo : list) {
                List<WorkAttachmentInfo> tempList = infoMap.get(vo.getAttachmentId());
                /*如果取不到数据,那么直接new一个空的ArrayList**/
                if (tempList == null) {
                    tempList = new ArrayList<>();
                    tempList.add(vo);
                    infoMap.put(vo.getAttachmentId(), tempList);
                }
                else {
                    /*某个vo之前已经存放过了,则直接追加数据到原来的List里**/
                    tempList.add(vo);
                }
            }
        }
        return infoMap;
    }

    public void updateStatus(LookOver lookOver){
        baseMapper.updateStatus(lookOver);
    }

    public void updateDisposeStatus(LookOver lookOver){
        baseMapper.updateDisposeStatus(lookOver);
    }
}
