package com.lz.modules.app.controller;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.lz.common.utils.NumberUtil;
import com.lz.common.utils.PageUtils;
import com.lz.common.utils.R;
import com.lz.modules.app.entity.DepartmentsEntity;
import com.lz.modules.app.entity.DepartmentsStaffRelateEntity;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.enums.RoleEnums;
import com.lz.modules.app.model.RoleModel;
import com.lz.modules.app.model.TaskModel;
import com.lz.modules.app.resp.StaffRoleModel;
import com.lz.modules.app.service.DepartmentsService;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.flow.entity.RecordRole;
import com.lz.modules.flow.entity.StaffRole;
import com.lz.modules.flow.entity.StaffRoleDepartment;
import com.lz.modules.flow.entity.StaffRoleEvaluationGroup;
import com.lz.modules.flow.req.StaffRoleRequest;
import com.lz.modules.flow.service.RecordRoleService;
import com.lz.modules.flow.service.StaffRoleDepartmentService;
import com.lz.modules.flow.service.StaffRoleEvaluationGroupService;
import com.lz.modules.flow.service.StaffRoleService;
import com.lz.modules.sys.controller.AbstractController;
import com.lz.modules.sys.entity.SysMenuEntity;
import com.lz.modules.sys.entity.SysRoleEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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


/**
 * 流转关系表
 *
 * @author zgh
 * @email zgh@ldxinyong.com
 * @date 2020-09-19 15:22:13
 */
@RestController
@RequestMapping("user/lzstaffrole")
@Api(tags = "考评组管理员管理")
public class StaffRoleController extends AbstractController {
    @Autowired
    private StaffRoleService staffRoleService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private RecordRoleService recordRoleService;

    @Autowired
    private StaffRoleDepartmentService staffRoleDepartmentService;

    @Autowired
    private DepartmentsService departmentsService;

    @Autowired
    private DepartmentsStaffRelateService departmentsStaffRelateService;
@Autowired
    private  StaffRoleEvaluationGroupService staffRoleEvaluationGroupService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("user:lzstaffrole:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = staffRoleService.queryPage(params);
        return R.ok().put("page", page);
    }


    @GetMapping("/listByGroupId")
    @ApiOperation(value="根据groupId获取管理员列表")
    // http://localhost:8080/lz_management/user/lzstaffrole/listByGroupId?groupId=3
    @ApiImplicitParam(name = "groupId",value = "组id",defaultValue = "1",required = true, dataType = "Long",paramType = "query")
    public R listByGroupId( Long groupId ) {
        List<StaffRole> staffRoleList = staffRoleService.selectAllStaffRoleByDepartmentLevel(Arrays.asList(new String[]{RoleEnums.MASTER_PM.getName(),RoleEnums.CHILD_PM.getName()}));
        List<StaffRoleModel> staffRoles = new ArrayList<>();
        for(StaffRole staffRole:staffRoleList){
            StaffRoleModel staffRoleModel = new StaffRoleModel();
            BeanUtils.copyProperties(staffRole,staffRoleModel);
            Long staffId = staffRole.getStaffId();
            DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateService.selectLastDepartmentByStaffId(staffId);
            if(departmentsStaffRelateEntity !=null ){
                DepartmentsEntity departmentsEntity = departmentsService.selectByDepartmentId(departmentsStaffRelateEntity.getDepartmentId());
                if(departmentsEntity !=null){
                    staffRoleModel.setStaffName(staffRoleModel.getStaffName() + " "+departmentsEntity.getDepartmentName());
                }
            }
            StaffRoleEvaluationGroup staffRoleEvaluationGroup = staffRoleEvaluationGroupService.selectEvaluationGroupIdsByRoleIdGroupId(staffRole.getId(),groupId);
            staffRoleModel.setIsSelect(0);
            if(staffRoleEvaluationGroup !=null){
                staffRoleModel.setIsSelect(1);
            }
            if(new Long(0).equals(staffRole.getEvaluationGroupId())){       //如果是管理全部考评组，则设置为1
                staffRoleModel.setIsSelect(1);
            }
            if(staffRole.getDepartmentLevel().equals(RoleEnums.MASTER_PM.getName())){
                staffRoleModel.setIsSelect(1);
            }
            staffRoles.add(staffRoleModel);
        }
        return R.ok().put("data", staffRoles);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        StaffRole lzStaffRole = staffRoleService.selectStaffRoleById(id);
        List<StaffEntity> staffEntityList = staffService.selectAll();
        List<StaffEntity> newList = new ArrayList<>();
        staffEntityList.forEach(p -> {
            StaffEntity staffEntity = new StaffEntity();
            staffEntity.setId(p.getId());
            staffEntity.setName(p.getName());
            newList.add(staffEntity);
        });
        List<RecordRole> roles = recordRoleService.selectAll();
        return R.ok().put("lzStaffRole", lzStaffRole)
                .put("staffs", newList)
                .put("targetRoles", roles);
    }

    /**
     * 信息
     */
    @RequestMapping("/role/list/{id}")
    public R roleList(@PathVariable("id") Long id) {
        SysRoleEntity role = staffRoleService.getRole(id);
        return R.ok().put("role", role);
    }

    @RequestMapping("/menu/list")
    public List<SysMenuEntity> menuList() {
        List<SysMenuEntity> list = staffRoleService.selectMenuList();
        return list;
    }


    /**
     * 修改
     */
    @RequestMapping("/updateOrAdd")
    @RequiresPermissions("user:lzstaffrole:update")
    public R update(@RequestBody StaffRoleRequest req) {
        StaffRole staffRole = null;
        List<StaffRole> staffRoles = staffRoleService.selectByRole(req.getDepartmentLevel());
        List<Long> ids = staffRoles.stream().map(StaffRole::getId).collect(Collectors.toList());
        if (req.getId() == null ||  req.getId() <= 0) {
            staffRole = new StaffRole();
        } else {
            staffRole = staffRoleService.selectStaffRoleById(req.getId());
        }

        staffRole.setStaffId(req.getStaffId());
        staffRole.setDepartmentLevel(req.getDepartmentLevel());
        Map<String, Integer> map = new HashMap<>();
        map.put("type1", req.getTargetRole());
        map.put("type2", req.getResultRole());
        staffRole.setTypeRoleIds(JSON.toJSONString(map));
        List<Long> menuIdList = req.getMenuIdList();
        for(Long menuId : menuIdList) {
            if (menuId <= 0) {
                break;
            }
            StaffRoleDepartment staffRoleDepartment = staffRoleDepartmentService.selectStaffRoleDepartmentByDepartmentIdRoleIds(menuId, ids);
            if (staffRoleDepartment != null) {
                StaffRole staffRoleOld = staffRoleService.selectStaffRoleById(staffRoleDepartment.getStaffRoleId());
                if (staffRoleOld.getStaffId().equals(req.getStaffId()) && req.getId() != null && req.getId() > 0) {
                    // 如果是编辑的时候，排除自己
                    continue;
                }
                StaffEntity staffEntity = staffService.getById(staffRoleOld.getStaffId());
                DepartmentsEntity departmentsEntity = departmentsService.selectByDepartmentId(staffRoleDepartment.getDepartmentId());
                return R.error(departmentsEntity.getDepartmentName() + " 己经分给了 " + staffEntity.getName() + " 审批，如需要更换，请去掉" + staffEntity.getName() + " 权限 ");
            }
            staffRoleDepartment = new StaffRoleDepartment();
            staffRoleDepartment.setDepartmentId(menuId + "");
            staffRoleDepartment.setStaffRoleId(staffRole.getId());
            staffRoleDepartmentService.insertStaffRoleDepartment(staffRoleDepartment);
        }
        if (req.getId() != null && req.getId() > 0) {
            List<StaffRoleDepartment> staffRoleDepartments = staffRoleDepartmentService.selectStaffRoleDepartmentByStaffRoleId(staffRole.getId());
            for(StaffRoleDepartment staffRoleDepartment : staffRoleDepartments){
                if(!menuIdList.contains(NumberUtil.objToLong(staffRoleDepartment.getDepartmentId()))){
                    // 删除没有选的部门
                    staffRoleDepartmentService.deleteStaffRoleDepartment(staffRoleDepartment.getId());
                }
            }
        }
        if (req.getId() == null || req.getId() <= 0) {
            staffRoleService.insertStaffRole(staffRole);
        } else {
            staffRoleService.updateStaffRoleById(staffRole);
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    @RequiresPermissions("user:lzstaffrole:delete")
    public R delete(@PathVariable("id") String id) {
        staffRoleService.deleteBatchIds(Arrays.asList(NumberUtil.objToLongDefault(id,0l)));
        return R.ok();
    }

    // http://localhost:8080/lz_management/user/lzstaffrole/role/set?pageSize=100
    @RequestMapping("/role/set")
    public R roleSet(RoleModel roleModel) {
        return staffRoleService.selectRoleInfoBy(roleModel);
    }

    // http://localhost:8080/lz_management/user/lzstaffrole/role/detail?id=28
    // http://localhost:8080/lz_management/user/lzstaffrole/role/detail
    @RequestMapping("/role/detail")
    public R roleDetail(RoleModel roleModel) {
        return staffRoleService.selectRoleDetail(roleModel);
    }


    // 老板add :http://localhost:8080/lz_management/user/lzstaffrole/role/addOrUpdate?departmentLevel=MASTER_PM&staffId=395
    // 老板edit :http://localhost:8080/lz_management/user/lzstaffrole/role/addOrUpdate?id=24&staffId=294
    // 普通add: http://localhost:8080/lz_management/user/lzstaffrole/role/addOrUpdate?departmentLevel=CHILD_PM&staffId=28&evaluationGroupId=1&evaluationGroupInfoStr=2,3&departmentId=2&departmentInfoStr=154332270,379635019&selectStaffMenuInfoStr=15,17
    // 普通add: http://localhost:8080/lz_management/user/lzstaffrole/role/addOrUpdate?id=26&evaluationGroupId=1&evaluationGroupInfoStr=2,4&departmentId=2&departmentInfoStr=154332270,379635019&selectStaffMenuInfoStr=15,17
    // 主管理员add:http://localhost:8080/lz_management/user/lzstaffrole/role/addOrUpdate?departmentLevel=MASTER_PM&staffId=294
    // 主管理员edit:http://localhost:8080/lz_management/user/lzstaffrole/role/addOrUpdate?id=19&staffId=303
    @RequestMapping("/role/addOrUpdate")
    public R roleAddOrUpdate(RoleModel roleModel) {
        return staffRoleService.roleAddOrUpdate(roleModel);
    }



    // http://localhost:8080/lz_management/user/lzstaffrole/role/delete?id=26
    @RequestMapping("/role/delete")
    public R roleDelete(RoleModel roleModel) {
        return staffRoleService.delete(roleModel);
    }




    // http://localhost:8080/lz_management/user/lzstaffrole/task/comment?taskId=1&content=xxx&staffId=294&atStaffIds=314,320
    @RequestMapping("/task/comment")
    public R taskComment(TaskModel taskModel) {
        if(taskModel.getStaffId() == null && getUser()!=null && getUserId() !=null){
            taskModel.setStaffId(getUserId());
        }
        return staffRoleService.taskComment(taskModel);
    }


    //http://localhost:8080/lz_management/user/lzstaffrole/comment/list?detailId=4917&pageSize=2
    @RequestMapping("/comment/list")
    public R commentList(TaskModel taskModel) {
        if(taskModel.getStaffId() == null && getUser()!=null && getUserId() !=null){
            taskModel.setStaffId(getUserId());
        }
        return staffRoleService.commentList(taskModel);
    }

}
