package com.jeeplus.business.humanResources.service;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
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.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.business.goOut.mapper.GoOutMapper;
import com.jeeplus.business.humanResources.domain.JyDimissionProcess;
import com.jeeplus.business.humanResources.domain.StaffDimission;
import com.jeeplus.business.humanResources.domain.StaffHeir;
import com.jeeplus.business.humanResources.mapper.JyDimissionProcessMapper;
import com.jeeplus.business.humanResources.mapper.StaffDimissionMapper;
import com.jeeplus.business.humanResources.mapper.StaffHeirMapper;
import com.jeeplus.business.humanResources.service.dto.StaffDimissionDTO;
import com.jeeplus.business.humanResources.service.dto.StaffHeirDTO;
import com.jeeplus.business.project.domain.JyProjectMembers;
import com.jeeplus.business.project.mapper.JyProjectMemberMapper;
import com.jeeplus.business.project.service.JyProjectService;
import com.jeeplus.business.project.service.dto.JyProjectDTO;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;

import com.jeeplus.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class StaffDimissionService {

    @Resource
    private StaffDimissionMapper staffDimissionMapper;

    @Resource
    private GoOutMapper goOutMapper;

    @Resource
    private StaffHeirMapper staffHeirMapper;

    @Resource
    private JyProjectService jyProjectService;

    @Resource
    private JyProjectMemberMapper jyProjectMemberMapper;

    @Resource
    private JyDimissionProcessMapper jyDimissionProcessMapper;

    /**
     * 列表展示
     * @param dimissionDTO
     * @param page
     * @return
     */
    public IPage<StaffDimissionDTO> findPageList(StaffDimissionDTO dimissionDTO, Page<StaffDimissionDTO> page) throws Exception {
        QueryWrapper<StaffDimissionDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dimissionDTO, StaffDimissionDTO.class);
        queryWrapper.eq("a.del_flag",0);
        if (StringUtils.isNotBlank(dimissionDTO.getCreateById())){
            queryWrapper.eq("a.create_by_id",dimissionDTO.getCreateById());
        }
        if (StringUtils.isNotBlank(dimissionDTO.getOfficeId())){
            queryWrapper.eq("so.id",dimissionDTO.getOfficeId());
        }
        //离职时间
        if (dimissionDTO.getDates() != null && dimissionDTO.getDates().length>0){
            queryWrapper.between("a.dimission_date",dimissionDTO.getDates()[0],dimissionDTO.getDates()[1]);
        }

        IPage<StaffDimissionDTO> list=staffDimissionMapper.findPageList(queryWrapper,page);
        return list;


    }

    /**
     * 根据id进行查询
     * @param id
     * @return
     */
    public StaffDimissionDTO findById(String id) {
        StaffDimissionDTO dimissionDTO=staffDimissionMapper.findById(id);
        // 查询附件信息
        List<WorkAttachmentInfo> files = goOutMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentInfo i : files) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            dimissionDTO.setFiles(files);
        }
        return dimissionDTO;
    }

    /**
     * 新增或修改
     * @param dimissionDTO
     * @return
     */
    public String save(StaffDimissionDTO dimissionDTO) {
        String id="";
        StaffDimission staffDimission = new StaffDimission();
        BeanUtils.copyProperties(dimissionDTO,staffDimission);
        if (StringUtils.isNotBlank(dimissionDTO.getId())){
            id=dimissionDTO.getId();
            staffDimissionMapper.updateById(staffDimission);
        }else {
            //获取id
            id = UUID.randomUUID().toString().replace("-", "");
            staffDimission.setId(id);
            staffDimissionMapper.insert(staffDimission);
            //获取当前登录人信息
            UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
            //创建交接人信息
            StaffHeir staffHeir = new StaffHeir();
            String heirId = UUID.randomUUID().toString().replace("-", "");
            staffHeir.setId(heirId);
            staffHeir.setCreateById(userDTO.getId());
            staffHeir.setCreateTime(new Date());
            staffHeir.setUpdateById(userDTO.getId());
            staffHeir.setUpdateTime(new Date());
            staffHeir.setStatus("0");
            staffHeir.setDimissionId(id);
            staffHeirMapper.insert(staffHeir);
        }

        //保存附件信息
        if (ObjectUtils.isNotEmpty(dimissionDTO)){
            Map<String,String> map = new HashMap<>();
            String fileList = JSON.toJSONString((dimissionDTO.getFiles()));
            String attachmentId = id;
            String attachmentFlag = "dimission";
            map.put("fileList",fileList);
            map.put("attachmentId",attachmentId);
            map.put("attachmentFlag",attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken ( ));
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileListFlag(map);
        }
        return id;
    }

    /**
     * 根据id修改状态
     * @param dimissionDTO
     */
    public void updateStatusById(StaffDimissionDTO dimissionDTO) {
        staffDimissionMapper.updateStatusById(dimissionDTO.getStatus(),dimissionDTO.getId());
    }

    /**
     * 根据id进行删除
     * @param id
     * @return
     */
    public String deleteById(String id) {
        staffDimissionMapper.deleteById(id);
        return "操作成功";
    }

    /**
     * 新增或修改   交接申请
     * @param staffHeirDTO
     * @return
     */
    public String saveHeir(StaffHeirDTO staffHeirDTO) {
        String id = "";
        StaffHeir staffHeir = new StaffHeir();
        BeanUtils.copyProperties(staffHeirDTO,staffHeir);

        if (StringUtils.isNotBlank(staffHeirDTO.getId())){
            id=staffHeirDTO.getId();
            staffHeirMapper.updateById(staffHeir);
        }else {
            //获取id
            id = UUID.randomUUID().toString().replace("-", "");
            staffHeir.setId(id);
            staffHeirMapper.insert(staffHeir);
        }
        return id;
    }

    /**
     * 修改交接状态
     * @param staffHeirDTO
     */
    public void updateHeirStatusById(StaffHeirDTO staffHeirDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        staffHeirMapper.updateHeirStatusById(staffHeirDTO.getStatus(),staffHeirDTO.getId(),userDTO.getId());

        //当人事审核同意后,将当前登录人所有未完成的项目中的项目组成员替换为交接人
        if (staffHeirDTO.getStatus().equals("5")){
            //获取离职人未归档的项目
            List<JyProjectDTO> projectDTOS = jyProjectService.getByIdNoArchive(staffHeirDTO.getCreateById());
            //根据项目查找项目组成员
            if (ObjectUtils.isNotEmpty(projectDTOS)){
                for (JyProjectDTO projectDTO : projectDTOS) {
                    //获取项目组成员中的数据
                    LambdaQueryWrapper<JyProjectMembers> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(JyProjectMembers::getProjectId,projectDTO.getId());
                    queryWrapper.eq(JyProjectMembers::getDelFlag, 0);
                    queryWrapper.orderByDesc(JyProjectMembers::getCreateTime);
                    List<JyProjectMembers> jyProjectMembers = jyProjectMemberMapper.selectList(queryWrapper);
                    for (JyProjectMembers jyProjectMember : jyProjectMembers) {
                        //判断交接人是否在当前项目组成员中
                        if (staffHeirDTO.getHeir().equals(jyProjectMember.getUserId())){
                            continue;
                        }else if (staffHeirDTO.getCreateById().equals(jyProjectMember.getUserId())){
                            //将项目组成员中的该条数据进行逻辑删除
                            jyProjectMemberMapper.deleteById(jyProjectMember.getId());
                            //在项目组成员中将离职人替换为交接人
                            JyProjectMembers projectMembers = new JyProjectMembers();
                            String memberId = UUID.randomUUID().toString().replace("-", "");
                            projectMembers.setId(memberId);
                            projectMembers.setCreateById(userDTO.getId());
                            projectMembers.setCreateTime(new Date());
                            projectMembers.setUpdateById(userDTO.getId());
                            projectMembers.setUpdateTime(new Date());
                            projectMembers.setProjectId(projectDTO.getId());
                            projectMembers.setUserId(staffHeirDTO.getHeir());
                            projectMembers.setStatus("0");
                            jyProjectMemberMapper.insert(projectMembers);
                        }
                    }
                }
            }

            //冻结离职人员信息
//            UserDTO dto = SpringUtil.getBean(IUserApi.class).getById(staffHeirDTO.getCreateById());
//            dto.setLoginFlag("0");
//            SpringUtil.getBean(IUserApi.class).updateUser(dto);

        }

    }

    /**
     * 根据id查询交接信息
     * @param id
     * @return
     */
    public StaffHeirDTO findHeirById(String id) {
        StaffHeirDTO staffHeirDTO=staffHeirMapper.findHeirById(id);
        //根据离职id查询离职项目进度
        List<JyDimissionProcess> dimissionProcesses = jyDimissionProcessMapper.findByDimissionId(id);
        if (ObjectUtils.isNotEmpty(dimissionProcesses)){
            staffHeirDTO.setProcessList(dimissionProcesses);
        }else {
            //获取当前登录人信息
            UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
            //获取当前登陆人未归档的项目信息
            List<JyProjectDTO> jyProjectDTO=jyProjectService.getByIdNoArchive(userDTO.getId());
            List<JyProjectDTO> arrayList = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(jyProjectDTO)){
                for (JyProjectDTO item : jyProjectDTO) {
                    //项目进度信息
                    if (!item.getFirstInstanceStatus().equals("5") && StringUtils.isNotBlank(item.getFirstInstanceStatus())){
                        item.setProcess("登记完成");
                        item.setProcessTime(item.getUpdateTime());
                        continue;
                    }else {
                        item.setProcess("一级校审完成");
                        item.setProcessTime(item.getAudit1UpdateTime());
                    }
                    if (!item.getSecondInstanceStatus().equals("5") && StringUtils.isNotBlank(item.getSecondInstanceStatus())){
                        item.setProcess("一级校审完成");
                        item.setProcessTime(item.getAudit1UpdateTime());
                        continue;
                    }else {
                        item.setProcess("二级校审完成");
                        item.setProcessTime(item.getAudit2UpdateTime());
                    }
                    if (!item.getThirdInstanceStatus().equals("5") && StringUtils.isNotBlank(item.getThirdInstanceStatus())){
                        item.setProcess("二级校审完成");
                        item.setProcessTime(item.getAudit2UpdateTime());
                        continue;
                    }else {
                        item.setProcess("三级校审完成");
                        item.setProcessTime(item.getAudit3UpdateTime());
                    }
                    if ((StringUtils.isNotBlank(item.getReportStatus()) && !item.getReportStatus().equals("5")) || StringUtils.isBlank(item.getReportStatus())){
                        item.setProcess("三级校审完成");
                        item.setProcessTime(item.getAudit3UpdateTime());
                        continue;
                    }else {
                        item.setProcess("报告签发完成");
                        item.setProcessTime(item.getReportTime());
                    }
                    if (StringUtils.isNotBlank(item.getOutInstance()) && !item.getOutInstance().equals("5")){
                        item.setProcess("报告签发完成");
                        item.setProcessTime(item.getReportTime());
                        continue;
                    }else {
                        item.setProcess("外审完成");
                        item.setProcessTime(item.getOutTime());
                    }
                    if ((StringUtils.isNotBlank(item.getReportsStatus()) && !item.getReportsStatus().equals("5")) ||StringUtils.isBlank(item.getReportsStatus())){
                        item.setProcess("外审完成");
                        item.setProcessTime(item.getOutTime());
                        continue;
                    }else {
                        item.setProcess("报批签发完成");
                        item.setProcessTime(item.getReportsTime());
                    }
                };
                arrayList.addAll(jyProjectDTO);
            }
            List<JyDimissionProcess> jyProcessList = saveProcess(arrayList, id);
            staffHeirDTO.setProcessList(jyProcessList);
        }
        return staffHeirDTO;
    }

    /**
     * 往进度表中添加数据
     */
    public List<JyDimissionProcess> saveProcess(List<JyProjectDTO> projectDTOS,String dimissionId){
        ArrayList<JyDimissionProcess> jyProcesses = new ArrayList<>();
        projectDTOS.stream().forEach(item->{
            JyDimissionProcess jyDimissionProcess = new JyDimissionProcess();
            String id = UUID.randomUUID().toString().replace("-", "");
            jyDimissionProcess.setId(id);
            jyDimissionProcess.setOfficeName(item.getOfficeName());//部门
            jyDimissionProcess.setProjectName(item.getName());//项目名称
            jyDimissionProcess.setNo(item.getNo());//报告号
            jyDimissionProcess.setProjectLeader(item.getProjectLeader());//项目负责人
            jyDimissionProcess.setProcessTime(item.getProcessTime());//进度完成时间
            jyDimissionProcess.setProcess(item.getProcess());//进度
            jyDimissionProcess.setDimissionId(dimissionId);//月报id
            jyDimissionProcessMapper.insert(jyDimissionProcess);
            jyProcesses.add(jyDimissionProcess);
        });
        return jyProcesses;
    }

    /**
     * 获取所有离职信息
     * @return
     */
    public List<StaffHeirDTO> getList() {
        List<StaffHeirDTO> list = staffHeirMapper.getList();
        return list;
    }

    public void updateUserById(String id, String loginFlag) {
        //冻结员工账号
        staffHeirMapper.updateUserById(id,loginFlag);

        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(id);
        //获取在线员工信息
        Set <String> keys = RedisUtils.getInstance ( ).keys ( CacheNames.USER_CACHE_ONLINE_USERS, "*" );
        List <UserDTO> onlineUsers = Lists.newArrayList ( );
        keys.forEach ( key -> {
            onlineUsers.add ( (UserDTO) RedisUtils.getInstance ( ).get ( key ) );
        } );
        //将该员工的信息从redis删除
        onlineUsers.forEach(dto ->{
            if (userDTO.getTenantDTO().getId().equals(dto.getTenantDTO().getId()) && userDTO.getName().equals(dto.getName())) {
                RedisUtils.getInstance ( ).delete ( CacheNames.USER_CACHE_ONLINE_USERS, dto.getToken ( ) );
                RedisUtils.getInstance ( ).delete ( CacheNames.USER_CACHE_TOKEN, dto.getToken ( ) );
            }
        });
    }
}
