package com.lz.modules.performance.controller;


import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.lz.common.utils.PageUtils;
import com.lz.common.utils.R;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.dto.DepartmentsSimpleDto;
import com.lz.modules.app.dto.StaffSimpleDto;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.flow.entity.*;
import com.lz.modules.flow.model.EvaluationGroupDto;
import com.lz.modules.flow.req.EvaluationGroupReq;
import com.lz.modules.flow.service.*;
import com.lz.modules.performance.req.CheckStaffReq;
import com.lz.modules.sys.controller.AbstractController;
import com.lz.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/evaluationGroup")
@Api(tags="考评组")
@Slf4j
public class EvaluationGroupController extends AbstractController {


    @Autowired
    private EvaluationGroupService evaluationGroupService;



    @Autowired
    private ResultModelService resultModelService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private StaffRoleDepartmentService staffRoleDepartmentService;

    @Autowired
    private StaffRoleService staffRoleService;
    @Autowired
    private StaffRoleEvaluationGroupService staffRoleEvaluationGroupService;




    @GetMapping("/getById")
    @ApiOperation("获取考评组详情")
    @ApiResponses({@ApiResponse(code=200,message = "成功", response= EvaluationGroupDto.class)})
    public R getById(@RequestParam @ApiParam("考评组id") Long id) {
        EvaluationGroup evaluationGroup = evaluationGroupService.selectEvaluationGroupById(id);
        EvaluationGroupDto evaluationGroupDto = new EvaluationGroupDto();
        if(evaluationGroup.getDepIds() != null && evaluationGroup.getDepIds().length() > 0){

            List<String> ids = Arrays.stream(evaluationGroup.getDepIds().split(",")).map(new Function<String, String>() {
                @Override
                public String apply(String s) {
                    return s;
                }
            }).collect(Collectors.toList());
            List<DepartmentsSimpleDto> departmentsSimpleDtos = staffRoleDepartmentService.selectDepartmentSimpleInfos(ids);
            evaluationGroupDto.setDeps(departmentsSimpleDtos);
        }
        if(evaluationGroup.getStaffIds() != null && evaluationGroup.getStaffIds().length() > 0){
            List<Long> ids = Arrays.stream(evaluationGroup.getStaffIds().split(",")).map(new Function<String, Long>() {
                @Override
                public Long apply(String s) {
                    return Long.parseLong(s);
                }
            }).collect(Collectors.toList());

            //指定人员，搜索人员信息
            List<StaffSimpleDto> staffSimpleDtos = staffService.selectStaffSimpleInfoByIds(ids);
            evaluationGroupDto.setStaffs(staffSimpleDtos);
        }

        if(evaluationGroup.getManagerIds() != null && evaluationGroup.getManagerIds().length() > 0){
            List<Long> ids = Arrays.stream(evaluationGroup.getManagerIds().split(",")).map(new Function<String, Long>() {
                @Override
                public Long apply(String s) {
                    return Long.parseLong(s);
                }
            }).collect(Collectors.toList());
            //下面的操作是防止在权限里面单独加绩效管理人员时，导致前端展示不一致问题
            //搜索管理表里面的人员去重
            List<StaffRole> staffRoles = staffRoleService.selectAllGroupManageRoles();
            if(staffRoles.size() > 0){
                List<Long> roleIds = staffRoles.stream().map(new Function<StaffRole, Long>() {
                    @Override
                    public Long apply(StaffRole staffRole) {
                        return staffRole.getStaffId();
                    }
                }).collect(Collectors.toList());
                ids.addAll(roleIds);
            }
            //获取管理特定组的
            staffRoles = staffRoleService.selectByEvaluationGroupId(evaluationGroup.getId());
            if(staffRoles.size() > 0){
                List<Long> roleIds = staffRoles.stream().map(new Function<StaffRole, Long>() {
                    @Override
                    public Long apply(StaffRole staffRole) {
                        return staffRole.getStaffId();
                    }
                }).collect(Collectors.toList());
                ids.addAll(roleIds);
            }
            //去重
            Map<Long, Long> mapIds = ids.stream().collect(Collectors.toMap(Long::longValue,Function.identity(), (e, r) -> e));
            ids = mapIds.values().stream().collect(Collectors.toList());
            //指定人员，搜索人员信息
            List<StaffSimpleDto> staffSimpleDtos = staffService.selectStaffSimpleInfoByIds(ids);

            evaluationGroupDto.setManagers(staffSimpleDtos);
        }
        if(evaluationGroup.getOutIds() != null && evaluationGroup.getOutIds().length() > 0){
            List<Long> ids = Arrays.stream(evaluationGroup.getOutIds().split(",")).map(new Function<String, Long>() {
                @Override
                public Long apply(String s) {
                    return Long.parseLong(s);
                }
            }).collect(Collectors.toList());

            //指定人员，搜索人员信息
            List<StaffSimpleDto> staffSimpleDtos = staffService.selectStaffSimpleInfoByIds(ids);
            evaluationGroupDto.setOuts(staffSimpleDtos);
        }

        BeanUtils.copyProperties(evaluationGroup, evaluationGroupDto);
        return R.ok().put("data",evaluationGroupDto);
    }


     @PostMapping("/getGroups")
     @ApiOperation("获取考评组列表")
     @ApiResponses({@ApiResponse(code=200,message = "成功", response=EvaluationGroup.class)})
     public R getGroups(@RequestBody @ApiParam EvaluationGroupReq req) {
        log.info("获取考评组列表数据{}", req);
         SysUserEntity sysUserEntity = getUser();
         PageUtils pageUtils = evaluationGroupService.selectEvaluationGroupByReq(req, sysUserEntity);
        return R.ok().put("data",pageUtils);
     }



     @PostMapping("/update")
     public R update(@RequestBody @ApiParam EvaluationGroup evaluationGroup) {
         evaluationGroupService.updateEvaluationGroupById(evaluationGroup);
        return R.ok();
     }


     @PostMapping("/save")
     @ApiOperation("保存考评组")
     @ApiResponses({@ApiResponse(code = 200, message = "成功", response = EvaluationGroup.class)})
     public R save(@RequestBody @ApiParam EvaluationGroup evaluationGroup) {
        log.info("保存考评组数据{}", evaluationGroup);
        EvaluationGroup evaluationGroup1 = evaluationGroupService.selectEvaluationGroupByName(evaluationGroup.getName());
         List<StaffRole> staffRoles = null;
        if(evaluationGroup.getId() != null && evaluationGroup.getId().intValue() > 0){
            if(evaluationGroup1 == null || evaluationGroup1.getId().equals(evaluationGroup.getId())){
                if(evaluationGroup.getDepIds() == null){
                    evaluationGroup.setDepIds("");
                }
                if(evaluationGroup.getStaffIds() == null){
                    evaluationGroup.setStaffIds("");
                }
                if(evaluationGroup.getManagerIds() == null){
                    evaluationGroup.setManagerIds("");
                }
                if(evaluationGroup.getOutIds() == null){
                    evaluationGroup.setOutIds("");
                }
                evaluationGroupService.updateEvaluationGroupById(evaluationGroup);

                staffRoles = staffRoleService.selectByEvaluationGroupId(evaluationGroup.getId());//查询已经管理改组的管理员
            }else {
                return R.error("已经存在相同名称考核组");
            }

        }else{
            if(evaluationGroup1 != null){
                return R.error("已经存在相同名称考核组");
            }
            evaluationGroupService.insertEvaluationGroup(evaluationGroup);
        }
        //更新组管理员信息
         if(evaluationGroup.getManagerIds() != null && evaluationGroup.getManagerIds().length() > 0){
             Map<Long, Long> mapIds = Arrays.stream(evaluationGroup.getManagerIds().split(",")).map(new Function<String, Long>() {
                 @Override
                 public Long apply(String s) {
                     return Long.parseLong(s);
                 }
             }).collect(Collectors.toMap(Long::longValue, Function.identity(), (e, replace) -> e));
            if(staffRoles != null && staffRoles.size() > 0){
                for (StaffRole staffRole:staffRoles
                ) {//去掉已经在管理本组的管理员
                    if(mapIds.containsKey(staffRole.getStaffId())){
                        mapIds.remove(staffRole.getStaffId());
                    }else{//删除管理的组信息
                        staffRoleEvaluationGroupService.deleteStaffRoleEvaluationGroupByRoleId(staffRole.getId());
                    }
                }
            }


            //去掉管理全考评组
             staffRoles  = staffRoleService.selectAllGroupManageRoles();
             for (StaffRole staffRole:staffRoles
             ) {
                 if(mapIds.containsKey(staffRole.getStaffId())){
                     mapIds.remove(staffRole.getStaffId());
                 }
             }


             if(mapIds.size() > 0){
                 List<Long> ids = mapIds.values().stream().collect(Collectors.toList());
                 staffRoles = staffRoleService.selectStaffRolesByStaffId(ids);

                 if(staffRoles.size() > 0){
                     List<StaffRoleEvaluationGroup> staffRoleEvaluationGroups = new ArrayList<>();
                     for (StaffRole staffRole:staffRoles
                          ) {
                         StaffRoleEvaluationGroup staffRoleEvaluationGroup = new StaffRoleEvaluationGroup();
                         staffRoleEvaluationGroup.setRoleId(staffRole.getId());
                         staffRoleEvaluationGroup.setEvaluationGroupId(evaluationGroup.getId());
                         staffRoleEvaluationGroups.add(staffRoleEvaluationGroup);
                     }
                     staffRoleEvaluationGroupService.saveBatch(staffRoleEvaluationGroups);
                 }
             }

         }
        return R.ok().put("data", evaluationGroup);
     }


    @GetMapping("/delete")
    @ApiOperation("删除考评组")
    public R delete(@RequestParam @ApiParam("组id") Long id) {
        resultModelService.deleteResultModelByGroupId(id);
        return evaluationGroupService.deleteEvaluationGroupById(id);
        //return R.ok();
     }


    @PostMapping("/checkStaff")
    @ApiOperation("校验是否有跨组人员")
    @ApiResponses({@ApiResponse(code = 200,message = "成功"),@ApiResponse(code = 504,message = "已跨组",response = StaffSimpleDto.class)})
    public R checkStaff(@RequestBody @ApiParam(required = true,name = "body") CheckStaffReq checkStaffReq) {
        log.info("校验跨组人员接受数据{}", checkStaffReq);
        return evaluationGroupService.checkStaff(checkStaffReq);
    }
}
