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

import com.mortals.framework.model.PageInfo;
import com.mortals.framework.util.StringUtils;
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.CheckTypeEnum;
import com.mortals.xhx.module.perform.model.*;
import com.mortals.xhx.module.perform.service.*;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import org.apache.commons.collections4.CollectionUtils;
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.perform.dao.PerformStaffConfDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

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

/**
 * PerformStaffConfService
 * 人员自动考核信息 service实现
 *
 * @author zxfei
 * @date 2023-05-16
 */
@Service("performStaffConfService")
@Slf4j
public class PerformStaffConfServiceImpl extends AbstractCRUDServiceImpl<PerformStaffConfDao, PerformStaffConfEntity, Long> implements PerformStaffConfService {

    @Autowired
    private PerformStaffConfDetailService performStaffConfDetailService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private PerformRulesCategoryService performRulesCategoryService;
    @Autowired
    private PerformRulesService performRulesService;
    @Autowired
    private UserService userService;
    @Autowired
    private PerformDeptConfDetailService performDeptConfDetailService;


    @Override
    protected void saveBefore(PerformStaffConfEntity entity, Context context) throws AppException {
        super.saveBefore(entity, context);
        if (StringUtils.isNotEmpty(entity.getStaffIds())) {
            List<Long> staffIdList = StringUtils.converStr2Long(entity.getStaffIds());
            StaffQuery staffQuery = new StaffQuery();
            staffQuery.setIdList(staffIdList);
            List<StaffEntity> staffEntityList = staffService.find(staffQuery);
            if (CollectionUtils.isNotEmpty(staffEntityList)) {
                String names = "";
                for (StaffEntity item : staffEntityList) {
                    names += item.getName() + ",";
                }
                entity.setStaffNames(names.substring(0, names.length() - 1));
                entity.setStaffCount(staffEntityList.size());
            } else {
                entity.setStaffCount(0);
            }
        }


        updateCount(entity);
    }

    private  void updateCount(PerformStaffConfEntity entity) {
        if (CollectionUtils.isNotEmpty(entity.getStaffConfDetail())) {
            Map<Integer, List<PerformStaffConfDetailEntity>> groupMap = entity.getStaffConfDetail().stream().collect(Collectors.groupingBy(PerformStaffConfDetailEntity::getType));
            if (groupMap.containsKey(CheckTypeEnum.考勤绩效.getValue())) {
                entity.setAttendCount(groupMap.get(CheckTypeEnum.考勤绩效.getValue()).size());
            } else {
                entity.setAttendCount(0);
            }
            if (groupMap.containsKey(CheckTypeEnum.评价绩效.getValue())) {
                entity.setAssessCount(groupMap.get(CheckTypeEnum.评价绩效.getValue()).size());
            } else {
                entity.setAssessCount(0);
            }
            if (groupMap.containsKey(CheckTypeEnum.办件绩效.getValue())) {
                entity.setWorkCount(groupMap.get(CheckTypeEnum.办件绩效.getValue()).size());
            } else {
                entity.setWorkCount(0);
            }
            if (groupMap.containsKey(CheckTypeEnum.效能绩效.getValue())) {
                entity.setEffectCount(groupMap.get(CheckTypeEnum.效能绩效.getValue()).size());
            } else {
                entity.setEffectCount(0);
            }
            if (groupMap.containsKey(CheckTypeEnum.其它绩效.getValue())) {
                entity.setOtherCount(groupMap.get(CheckTypeEnum.其它绩效.getValue()).size());
            } else {
                entity.setOtherCount(0);
            }
        }
    }

    @Override
    protected void saveAfter(PerformStaffConfEntity entity, Context context) throws AppException {
        if (CollectionUtils.isNotEmpty(entity.getStaffConfDetail())) {
            for (PerformStaffConfDetailEntity item : entity.getStaffConfDetail()) {
                PerformRulesEntity rulesEntity = performRulesService.get(item.getRuleId());
                if(rulesEntity!=null){
                    item.setRuleName(rulesEntity.getName());
                }
                item.setStaffConfId(entity.getId());
                item.setCreateTime(entity.getCreateTime());
                item.setCreateUser(entity.getCreateUser());
                item.setId(null);
                PerformRulesCategoryEntity categoryEntity = performRulesCategoryService.get(item.getCategoryId());
                if (categoryEntity != null) {
                    item.setCategoryName(categoryEntity.getName());
                }
            }
            performStaffConfDetailService.save(entity.getStaffConfDetail(), context);
        }
    }

    @Override
    protected void updateBefore(PerformStaffConfEntity entity, Context context) throws AppException {
        super.updateBefore(entity, context);
        if (StringUtils.isNotEmpty(entity.getStaffIds())) {
            List<Long> staffIdList = StringUtils.converStr2Long(entity.getStaffIds());
            StaffQuery staffQuery = new StaffQuery();
            staffQuery.setIdList(staffIdList);
            List<StaffEntity> staffEntityList = staffService.find(staffQuery);
            if (CollectionUtils.isNotEmpty(staffEntityList)) {
                entity.setStaffNames(staffEntityList.stream().map(i->i.getName()).collect(Collectors.joining(",")));
                entity.setStaffCount(staffEntityList.size());
            } else {
                entity.setStaffCount(0);
            }
        }
        updateCount(entity);
    }

    @Override
    protected void updateAfter(PerformStaffConfEntity entity, Context context) throws AppException {
        if (CollectionUtils.isNotEmpty(entity.getStaffConfDetail())) {
            Long[] detailIds = performStaffConfDetailService.find(new PerformStaffConfDetailQuery().staffConfId(entity.getId())).stream().map(PerformStaffConfDetailEntity::getId).toArray(Long[]::new);
            performStaffConfDetailService.remove(detailIds, context);
            for (PerformStaffConfDetailEntity item : entity.getStaffConfDetail()) {
                PerformRulesEntity rulesEntity = performRulesService.get(item.getRuleId());
                if(rulesEntity!=null){
                    item.setRuleName(rulesEntity.getName());
                }
                item.setStaffConfId(entity.getId());
                item.setCreateTime(entity.getCreateTime());
                item.setCreateUser(entity.getCreateUser());
                item.setId(null);
                PerformRulesCategoryEntity categoryEntity = performRulesCategoryService.get(item.getCategoryId());
                if (categoryEntity != null) {
                    item.setCategoryName(categoryEntity.getName());
                }
            }
            performStaffConfDetailService.save(entity.getStaffConfDetail(), context);
        }
    }

    @Override
    protected void findAfter(PerformStaffConfEntity params, PageInfo pageInfo, Context context, List<PerformStaffConfEntity> list) throws AppException {
        Map<Long, UserEntity> userMap = userService.findToMap(new UserQuery(), context);
        if (CollectionUtils.isNotEmpty(list)) {
            for (PerformStaffConfEntity item : list) {
                UserEntity userEntity = userMap.get(item.getCreateUserId());
                if (!ObjectUtils.isEmpty(userEntity)) {
                    item.setCreateUserName(userEntity.getRealName());
                }
                List<PerformStaffConfDetailEntity> detailEntityList = performStaffConfDetailService.find(new PerformStaffConfDetailQuery().staffConfId(item.getId()));
                item.setStaffConfDetail(detailEntityList);
            }
        }
    }

    @Override
    public PerformStaffConfEntity get(Long key, Context context) throws AppException {
        PerformStaffConfEntity entity = this.dao.get(key);
        if (entity != null) {
            List<PerformStaffConfDetailEntity> detailEntityList = performStaffConfDetailService.find(new PerformStaffConfDetailQuery().staffConfId(entity.getId()));
            entity.setStaffConfDetail(detailEntityList);
        }
        return entity;
    }

    @Override
    protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
        if (ids != null && ids.length != 0) {
            for (Long id : ids) {
                PerformStaffConfDetailEntity condition = new PerformStaffConfDetailEntity();
                condition.setStaffConfId(id);
                performStaffConfDetailService.remove(condition, context);
            }
        }
    }

    @Override
    public boolean checkRules(Long staffId, Long deptId, Long rulesId) {
        boolean result = false;
        PerformStaffConfEntity staffConfEntity = this.selectOne(new PerformStaffConfQuery().staffIds(String.valueOf(staffId)));
        if(staffConfEntity!=null){
            List<PerformStaffConfDetailEntity> detailEntities = performStaffConfDetailService.find(new PerformStaffConfDetailQuery().staffConfId(staffConfEntity.getId()).ruleId(rulesId));
            if(CollectionUtils.isNotEmpty(detailEntities)){
                result = true;
            }else {
                PerformDeptConfDetailEntity deptConfDetailEntity = performDeptConfDetailService.selectOne(new PerformDeptConfDetailQuery().deptId(deptId).ruleId(rulesId));
                if(deptConfDetailEntity!=null){
                    result = true;
                }
            }
        }else {
            PerformDeptConfDetailEntity deptConfDetailEntity = performDeptConfDetailService.selectOne(new PerformDeptConfDetailQuery().deptId(deptId).ruleId(rulesId));
            if(deptConfDetailEntity!=null){
                result = true;
            }
        }
        return result;
    }
}