package com.lz.modules.performance.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.lz.common.utils.DateUtils;
import com.lz.common.utils.PageUtils;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.entity.DepartmentsStaffRelateEntity;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.flow.entity.FlowStart;
import com.lz.modules.flow.entity.StaffRole;
import com.lz.modules.flow.entity.StaffRoleDepartment;
import com.lz.modules.flow.service.*;
import com.lz.modules.performance.dto.TaskListDto;
import com.lz.modules.performance.req.AssessTaskReq;
import com.lz.modules.performance.res.ChartStatisticalRes;
import com.lz.modules.performance.res.TaskListRes;
import com.lz.modules.performance.service.AssessService;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: djc
 * @Desc:
 * @Date: 2020/10/14 14:59
 */
@Slf4j
@Service("assessService")
public class AssessServiceImpl implements AssessService {
    @Autowired
    private FlowRecordService flowRecordService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private FlowChangeService flowChangeService;
    @Autowired
    private StaffRoleDepartmentService staffRoleDepartmentService;
    @Autowired
    private StaffRoleEvaluationGroupService staffRoleEvaluationGroupService;
    @Autowired
    private StaffRoleService staffRoleService;
    @Autowired
    private FlowStartService flowStartService;
    @Autowired
    private DepartmentsStaffRelateService departmentsStaffRelateService;

    @Override
    public PageUtils userTaskList(AssessTaskReq req,Long userId) {
        PageUtils data = new PageUtils();
        List<TaskListRes> list = Lists.newArrayList();
        PageUtils pageUtils = flowRecordService.selectTaskListByApprovalStaffId(req,userId);
        if(CollectionUtils.isEmpty(pageUtils.getList())){
            return data;
        }
        List<TaskListDto> dtos = pageUtils.getList();
        dtos.stream().forEach(taskListDto -> {
            TaskListRes res = new TaskListRes();
            StaffEntity staffEntity = staffService.selectStaffById(taskListDto.getRecordStaffId());
            String name = "";
            if(staffEntity!=null){
                res.setAvatar(Optional.ofNullable(staffEntity.getAvatar()).orElse(StringUtil.EMPTY));
                 name = staffEntity.getName();
                if(taskListDto.getRecordStaffId().equals(taskListDto.getApprovalStaffId())){
                    name = "您";
                }
            }else {
                name = "未知";
                log.info("未找到此人信息 staffId: " + taskListDto.getRecordStaffId());
            }

            FlowStart start = flowStartService.selectFlowStartById(taskListDto.getStartId());
            //根据状态拼接文案
            String startName = start == null ? "" : start.getName();
            res.setTitle(name + "的" + startName + "需您进行" + taskListDto.getFlowName());
            res.setTime(DateUtils.format(taskListDto.getGmtModified(),DateUtils.DATE_TIME_PATTERN));
            //跳转绩效详情页
            res.setRecordId(taskListDto.getRecordId());
            list.add(res);
        });
        data.setTotalCount(pageUtils.getTotalCount());
        data.setTotalPage(pageUtils.getTotalPage());
        data.setList(list);
        data.setPageSize(req.getPageSize());
        data.setCurrPage(req.getCurrPage());
        return data;
    }


    @Override
    public List<String> roleDepartments(Long staffId) {
        StaffRole staffRole = staffRoleService.selectByStaffId(staffId);
        if(staffRole == null){
            log.info("staffRole 为空,不存在次人员权限配置信息，staffId：" + staffId);
            //判断是否是领导
            DepartmentsStaffRelateEntity entity = departmentsStaffRelateService.selectByStaffId(staffId);
            if(entity == null || 0 == entity.getIsLeader()){
                log.info("非 leader,此人员无管理部门权限");
                return Collections.EMPTY_LIST;
            }

            List<String> depIds = staffService.selectAllDeparmentIdsByDepartmentParentId(entity.getDepartmentId());
            log.info("获取部门领导管理部门ids: " + JSON.toJSONString(depIds));
            return depIds;
        }
        log.info("获取 roleDepartment,staffRole: " + JSON.toJSONString(staffRole));
        // 0 标识全部部门
        if (staffRole.getDepartmentId() == 0) {
            log.info("staffRole 为0，管理全部部门");
            return null;
        }
        else {
            if (staffRole.getDepartmentId() == 1) {
                DepartmentsStaffRelateEntity entity = departmentsStaffRelateService.selectByStaffId(staffId);
                List<String> strings = staffService.selectAllDeparmentIdsByDepartmentParentId(entity.getDepartmentId());
                log.info("获取到权限对应的部门 " + JSON.toJSONString(strings));
                return strings;
            }
            else if(staffRole.getDepartmentId() == 2){
                List<StaffRoleDepartment> staffRoleDepartments = staffRoleDepartmentService.selectStaffRoleDepartmentByStaffRoleId(staffRole.getId());
                if (CollectionUtils.isNotEmpty(staffRoleDepartments)) {
                    List<String> allDepart = new ArrayList<>();
                    staffRoleDepartments.forEach(staffRoleDepartment -> {
                        List<String> strings = staffService.selectAllDeparmentIdsByDepartmentParentId(staffRoleDepartment.getDepartmentId());
                        allDepart.addAll(strings);
                    });

                    List<String> collect = allDepart.stream().distinct().collect(Collectors.toList());
                    log.info("获取到权限对应的部门 " + JSON.toJSONString(collect));
                    return collect;
                }

            }
        }
        log.info("未获取到用户权限对应的部门 roleID: " + staffRole.getId());
        return Collections.EMPTY_LIST;
    }
}
