package com.ym.mec.web.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dto.EmployeeLevelDto;
import com.ym.mec.biz.dal.dto.SimpleUserDto;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.enums.EmployeeOperateEnum;
import com.ym.mec.biz.dal.page.EmployeeQueryInfo;
import com.ym.mec.biz.service.EmployeeService;
import com.ym.mec.biz.service.OrganizationService;
import com.ym.mec.biz.service.StudentManageService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author Joburgess
 * @Date 2019/9/17
 */
@RequestMapping("employee")
@Api(tags = "员工管理")
@RestController
public class EmployeeController extends BaseController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private StudentManageService studentManageService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private EmployeeDao employeeDao;

    @ApiOperation(value = "根据部门获取下面的员工")
    @GetMapping("/queryEmployByOrganId")
    @PreAuthorize("@pcs.hasPermissions('employee/queryEmployByOrganId')")
    public Object queryEmployByOrganId(EmployeeQueryInfo queryInfo) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
		if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeService.get(sysUser.getId());
			if (StringUtils.isEmpty(queryInfo.getOrganId())) {
				queryInfo.setOrganId(employee.getOrganIdList());
			}else if(StringUtils.isEmpty(employee.getOrganIdList())){
                return failed("用户所在分部异常");
            }else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if(!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))){
                    return failed("非法请求");
                }
            }
		}
        return succeed(employeeService.queryEmployByOrganId(queryInfo));
    }

    @ApiOperation(value = "员工操作")
    @PostMapping("/employeeOperate")
    @PreAuthorize("@pcs.hasPermissions('employee/employeeOperate')")
    public Object employeeOperate(Integer employeeId, EmployeeOperateEnum operate){
        employeeService.employeeOperate(employeeId,operate);
        return succeed();
    }

    @ApiOperation(value = "当前用户是否有课程组教务老师关联")
    @PostMapping("/hasCourseGroupRelation")
    @PreAuthorize("@pcs.hasPermissions('employee/hasCourseGroupRelation')")
    public Object hasCourseGroupRelation(Integer employeeId){
        return succeed(employeeService.hasCourseGroupRelation(employeeId));
    }

    @ApiOperation(value = "修改指定的教务老师关联")
    @PostMapping("/updateEducationTeacherId")
    @PreAuthorize("@pcs.hasPermissions('employee/updateEducationTeacherId')")
    public Object updateEducationTeacherId(Integer currentUserId,Integer targetUserId){
        employeeService.updateEducationTeacherId(currentUserId,targetUserId);
        return succeed();
    }

    @ApiOperation(value = "新增员工")
    @PostMapping("/add")
    @PreAuthorize("@pcs.hasPermissions('employee/add')")
    public Object add(@RequestBody Employee employee) throws Exception {
        employeeService.add(employee);
        return succeed();
    }

    @ApiOperation(value = "修改员工")
    @PostMapping("/update")
    @PreAuthorize("@pcs.hasPermissions('employee/update')")
    public Object update(@RequestBody Employee employee) {
        employee.setUpdateTime(new Date());
        employeeService.updateEmployee(employee);
        return succeed();
    }

    @ApiOperation(value = "修改用户")
    @PostMapping("/updateUser")
    public Object update(SysUser sysUser) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user != null) {
            Date date = new Date();
            sysUser.setId(user.getId());
            sysUser.setUpdateTime(date);
            studentManageService.updateUser(sysUser);
            return succeed();
        }
        return failed("获取用户失败");
    }

    @ApiOperation(value = "获取所有员工")
    @GetMapping("/findAll")
    @PreAuthorize("@pcs.hasPermissions('employee/findAll')")
    public Object findAll() {
        return succeed(employeeService.findAll(null));
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/queryUserInfo")
    public Object apiQueryUserInfo() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser != null && sysUser.getId() != null){
            Employee employee = employeeService.get(sysUser.getId());
            sysUser.setOrganName(organizationService.getOrganName(employee.getOrganIdList()));
            sysUser.setRoles(employeeDao.queryUserRole(sysUser.getId()));
            sysUser.setContactAddress(employee.getContactAddress());
            sysUser.setPostalCode(employee.getPostalCode());
            return succeed(sysUser);
        }
        return failed("获取用户信息失败");
    }

    @ApiOperation(value = "获取教务人员")
    @GetMapping("/findEducationUsers")
    public HttpResponseResult findEducationUsers(Integer userId){
        SysUser sysUser;
        if(userId == null){
            sysUser = sysUserFeignService.queryUserInfo();
            if (sysUser == null) {
                return failed("用户信息获取失败");
            }
        }else {
            sysUser = sysUserFeignService.queryUserById(userId);
        }
        String organIds = new String();
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeService.get(sysUser.getId());
            if (StringUtils.isEmpty(organIds)) {
                organIds = employee.getOrganIdList();
            }
        }
        return succeed(employeeService.findByRole("4,5",organIds));
    }

    @ApiOperation(value = "获取教务老师")
    @GetMapping("/findEducationTeacher")
    public HttpResponseResult findEducationTeacher(Integer userId){
        SysUser sysUser;
        if(userId == null){
            sysUser = sysUserFeignService.queryUserInfo();
            if (sysUser == null) {
                return failed("用户信息获取失败");
            }
        }else {
            sysUser = sysUserFeignService.queryUserById(userId);
        }
        String organIds = new String();
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeService.get(sysUser.getId());
            if (StringUtils.isEmpty(organIds)) {
                organIds = employee.getOrganIdList();
            }
        }
        return succeed(employeeService.findByRole("4",organIds));
    }

    @ApiOperation(value = "获取维修技师")
    @GetMapping("/findTechnician")
    @PreAuthorize("@pcs.hasPermissions('employee/findTechnician')")
    public HttpResponseResult findTechnician(){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        String organIds = new String();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeService.get(sysUser.getId());
            if (StringUtils.isEmpty(organIds)) {
                organIds=employee.getOrganIdList();
            }
        }
        return succeed(employeeService.findByRole("37",organIds));
    }

    @ApiOperation(value = "获取所选用户离职所需交接信息")
    @GetMapping("/levelDetail")
    @PreAuthorize("@pcs.hasPermissions('employee/levelDetail')")
    public HttpResponseResult levelDetail(Integer userId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        return succeed(employeeService.levelDetail(userId));
    }

    @ApiOperation(value = "员工离职交接")
    @PostMapping("/level")
    @PreAuthorize("@pcs.hasPermissions('employee/level')")
    public HttpResponseResult level(@RequestBody List<EmployeeLevelDto> employeeLevelDtos){
        employeeService.level(employeeLevelDtos);
        return succeed();
    }

    @ApiOperation(value = "获取所有维修技师（包含离职和冻结的）")
    @GetMapping("/findAllTechnician")
    @PreAuthorize("@pcs.hasPermissions('employee/findAllTechnician')")
    public HttpResponseResult<List<SimpleUserDto>> findAllTechnician(){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        String organIds = new String();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if (!sysUser.getIsSuperAdmin()) {
            Employee employee = employeeService.get(sysUser.getId());
            if (StringUtils.isEmpty(organIds)) {
                organIds=employee.getOrganIdList();
            }
        }
        return succeed(employeeService.findAllByRole("37",organIds));
    }
}
