package com.mortals.xhx.module.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;

import java.util.*;

import com.mortals.framework.model.DbMatchMode;
import com.google.common.collect.Maps;
import com.mortals.framework.model.PageInfo;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.StudyStatusEnum;
import com.mortals.xhx.common.code.TopEnum;
import com.mortals.xhx.common.code.UserType;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.notice.model.NoticeStudyEntity;
import com.mortals.xhx.module.notice.model.NoticeStudyQuery;
import com.mortals.xhx.module.project.model.ProjectStudyEntity;
import com.mortals.xhx.module.project.model.ProjectStudyQuery;
import com.mortals.xhx.module.project.service.ProjectStudyService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.project.dao.ProjectDao;
import com.mortals.xhx.module.project.model.ProjectEntity;
import com.mortals.xhx.module.project.service.ProjectService;
import org.springframework.util.ObjectUtils;

import java.util.stream.Collectors;

/**
 * ProjectService
 * 学习项目 service实现
 *
 * @author zxfei
 * @date 2023-02-23
 */
@Service("projectService")
public class ProjectServiceImpl extends AbstractCRUDServiceImpl<ProjectDao, ProjectEntity, Long> implements ProjectService {

    @Autowired
    private ProjectStudyService projectStudyService;
    @Autowired
    private UserService userService;


    @Override
    protected void findAfter(ProjectEntity params, PageInfo pageInfo, Context context, List<ProjectEntity> list) throws AppException {

        list.stream().forEach(item->{
            Map<Boolean, Long> collect = projectStudyService.find(new ProjectStudyQuery().projectId(item.getId())).stream().collect(Collectors.partitioningBy(x -> x.getStudyStatus() == StudyStatusEnum.已学习.getValue(), Collectors.counting()));
            item.setStudyPersonRadio(collect.getOrDefault(true,0L)+"/"+(collect.getOrDefault(false,0L)+collect.getOrDefault(true, 0L)));
        });

        super.findAfter(params, pageInfo, context, list);
    }

    @Override
    protected void saveBefore(ProjectEntity entity, Context context) throws AppException {
        super.saveBefore(entity, context);
    }

    @Override
    protected void saveAfter(ProjectEntity entity, Context context) throws AppException {
        super.saveAfter(entity, context);
        if (!ObjectUtils.isEmpty(entity.getPerson()) && YesNoEnum.NO.getValue() == entity.getPerson()) {
            //全部工作人员
            List<UserEntity> workPersons = userService.find(new UserQuery().userType(UserType.WORK_PERSON.getValue()));
            List<ProjectStudyEntity> studyPersons = workPersons.stream().map(work -> {
                ProjectStudyEntity projectStudyEntity = buildStudyPerson(entity, context, work);
                return projectStudyEntity;
            }).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(studyPersons)) {
                projectStudyService.save(studyPersons);
            }
        }

        //判断是否选择部门
        if(!ObjectUtils.isEmpty(entity.getDeptIds())) {
            //根据部门查询人员
            UserQuery userQuery = new UserQuery();
            userQuery.setUserType(UserType.WORK_PERSON.getValue());
            userQuery.setDeptIdList(entity.getDeptIds());
            List<UserEntity> workPersons = userService.find(userQuery);
            List<ProjectStudyEntity> studyPersons = workPersons.stream().map(work -> {
                ProjectStudyEntity projectStudyEntity = buildStudyPerson(entity, context, work);
                return projectStudyEntity;
            }).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(studyPersons)) {
                projectStudyService.save(studyPersons);
            }
        }

        if(ObjectUtils.isEmpty(entity.getDeptIds())&&!ObjectUtils.isEmpty(entity.getPersonIds())){
            UserQuery userQuery = new UserQuery();
            userQuery.setIdList(entity.getPersonIds());
            List<UserEntity> workPersons = userService.find(userQuery);
            List<ProjectStudyEntity> studyPersons = workPersons.stream().map(work -> {
                ProjectStudyEntity projectStudyEntity = buildStudyPerson(entity, context, work);
                return projectStudyEntity;
            }).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(studyPersons)) {
                projectStudyService.save(studyPersons);
            }
        }

    }

    private ProjectStudyEntity buildStudyPerson(ProjectEntity entity, Context context, UserEntity work) {
        ProjectStudyEntity projectStudyEntity = new ProjectStudyEntity();
        projectStudyEntity.initAttrValue();
        projectStudyEntity.setProjectId(entity.getId());
        projectStudyEntity.setProjectType(entity.getProjectType());
        projectStudyEntity.setTitle(entity.getTitle());
        projectStudyEntity.setUserId(work.getId());
        projectStudyEntity.setUserName(work.getRealName());
        projectStudyEntity.setDeptName(work.getDeptName());
        projectStudyEntity.setStudyStatus(StudyStatusEnum.未学习.getValue());
        projectStudyEntity.setTop(TopEnum.否.getValue());
        projectStudyEntity.setStudyTime(new Date());
        projectStudyEntity.setRemark("");
        projectStudyEntity.setCreateTime(new Date());
        projectStudyEntity.setCreateUserId(this.getContextUserId(context));
        return projectStudyEntity;
    }

    @Override
    protected void updateAfter(ProjectEntity entity, Context context) throws AppException {
        super.updateAfter(entity, context);
        List<ProjectStudyEntity> oldProjectStudy = projectStudyService.find(new ProjectStudyQuery().projectId(entity.getId()));
        List<ProjectStudyEntity> studyPersons = new ArrayList<>();
        if (!ObjectUtils.isEmpty(entity.getPerson()) && YesNoEnum.NO.getValue() == entity.getPerson()) {
            //全部工作人员
            List<UserEntity> workPersons = userService.find(new UserQuery().userType(UserType.WORK_PERSON.getValue()));
            studyPersons = workPersons.stream().map(work -> {
                ProjectStudyEntity projectStudyEntity = buildStudyPerson(entity, context, work);
                return projectStudyEntity;
            }).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(studyPersons)) {
                projectStudyService.save(studyPersons);
            }
        }

        //判断是否选择部门
        if(!ObjectUtils.isEmpty(entity.getDeptIds())) {
            //根据部门查询人员
            UserQuery userQuery = new UserQuery();
            userQuery.setUserType(UserType.WORK_PERSON.getValue());
            userQuery.setDeptIdList(entity.getDeptIds());
            List<UserEntity> workPersons = userService.find(userQuery);
            studyPersons = workPersons.stream().map(work -> {
                ProjectStudyEntity projectStudyEntity = buildStudyPerson(entity, context, work);
                return projectStudyEntity;
            }).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(studyPersons)) {
                projectStudyService.save(studyPersons);
            }
        }

        if(ObjectUtils.isEmpty(entity.getDeptIds())&&!ObjectUtils.isEmpty(entity.getPersonIds())){
            UserQuery userQuery = new UserQuery();
            userQuery.setIdList(entity.getPersonIds());
            List<UserEntity> workPersons = userService.find(userQuery);
             studyPersons = workPersons.stream().map(work -> {
                ProjectStudyEntity projectStudyEntity = buildStudyPerson(entity, context, work);
                return projectStudyEntity;
            }).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(studyPersons)) {
                projectStudyService.save(studyPersons);
            }
        }


        //差集计算 noticeStudyEntities 与   oldNoticeStudy
        //获取新增的元素
        List<ProjectStudyEntity> addList = CollUtil.subtract(studyPersons, oldProjectStudy).stream().collect(Collectors.toList());

        if (ObjectUtils.isEmpty(addList)) {
            projectStudyService.save(addList);
        }
        //需删除的元素
        List<ProjectStudyEntity> delList = CollUtil.subtract(oldProjectStudy, studyPersons).stream().collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(delList)) {
            Long[] delIds = delList.stream().map(item -> {
                return projectStudyService.selectOne(new ProjectStudyQuery().projectId(item.getProjectId()).userId(item.getUserId()));
            }).filter(f -> f != null).map(item -> item.getId()).toArray(Long[]::new);
            if (!ObjectUtils.isEmpty(delIds)) {
                projectStudyService.remove(delIds, context);
            }
        }


    }

    @Override
    protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
        super.removeAfter(ids, context, result);
        List<Long> idList = Arrays.asList(ids);
        Long[] delIds = projectStudyService.find(new ProjectStudyQuery().projectIdList(idList)).stream().map(item -> item.getId()).toArray(Long[]::new);
        if (!ObjectUtils.isEmpty(delIds)) {
            projectStudyService.remove(delIds, context);
        }


    }
}