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.SysEmployeePositionDto;
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.dal.page.UserBasicQueryInfo;
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.biz.service.SysEmployeePositionService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.tenant.TenantContextHolder;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @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;
    @Autowired
    private SysEmployeePositionService sysEmployeePositionService;

    @ApiOperation(value = "获取员工列表（基本信息）")
    @GetMapping("/queryEmployeeBasicInfo")
    @PreAuthorize("@pcs.hasPermissions('employee/queryEmployeeBasicInfo')")
    public Object queryEmployeeBasicInfo(UserBasicQueryInfo queryInfo){
        queryInfo.setOrganId(organizationService.getEmployeeOrgan(queryInfo.getOrganId()));
        return succeed(employeeService.queryEmployeeBasicInfo(queryInfo));
    }

    @ApiOperation(value = "根据部门获取下面的员工")
    @GetMapping("/queryEmployByOrganId")
    @PreAuthorize("@pcs.hasPermissions('employee/queryEmployByOrganId')")
    public Object queryEmployByOrganId(EmployeeQueryInfo queryInfo) throws Exception {
        queryInfo.setOrganId(organizationService.getEmployeeOrgan(queryInfo.getOrganId()));
        return succeed(employeeService.queryEmployByOrganId(queryInfo));
    }

    @ApiOperation(value = "获取平台的员工")
    @GetMapping("/queryPlatformEmploy")
    @PreAuthorize("@pcs.hasPermissions('employee/queryPlatformEmploy')")
    public Object queryPlatformEmploy(EmployeeQueryInfo queryInfo) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        queryInfo.setOrganId(null);
        queryInfo.setTenantId(-1);
        return succeed(employeeService.queryEmployByOrganId(queryInfo));
    }

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

    @ApiOperation(value = "密码重置")
    @PostMapping("/resetPassword")
    @PreAuthorize("@pcs.hasPermissions('employee/resetPassword')")
    public HttpResponseResult resetPassword(Integer userId){
        employeeService.resetPassword(userId);
        return succeed();
    }

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

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

    @ApiOperation(value = "新增员工")
    @PostMapping("/add")
    @PreAuthorize("@pcs.hasPermissions('employee/add')")
    public HttpResponseResult 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) {
        TenantContextHolder.setTenantId(employee.getTenantId());
        employee.setUpdateTime(new Date());
        employeeService.updateEmployee(employee);
        return succeed();
    }

    @ApiOperation(value = "修改员工")
    @PostMapping("/simpleUpdate")
    @PreAuthorize("@pcs.hasPermissions('employee/simpleUpdate')")
    public HttpResponseResult simpleUpdate(@RequestBody Employee employee) {
        employeeService.simpleUpdate(employee);
        return succeed();
    }

    @ApiOperation(value = "修改用户")
    @PostMapping("/updateUser")
    public HttpResponseResult 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 HttpResponseResult<List<Employee>> findAll() {
        return succeed(employeeService.findAll(null));
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/queryUserInfo")
    public HttpResponseResult 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());
            sysUser.setDeptId(employee.getDeptId());
            sysUser.setDeptIds(employee.getDeptIds());
            sysUser.setPostIds(employee.getPostIds());
            sysUser.setBankCard(employee.getBankCard());
            sysUser.setOpenBankAddress(employee.getOpenBankAddress());
            sysUser.setPostDeptIds(employee.getPostDeptIds());
            sysUser.setOrganIdList(employee.getOrganIdList());
            
            List<SysEmployeePositionDto> sysEmployeePositionDtoList = sysEmployeePositionService.queryByUserId(sysUser.getId());
            if(sysEmployeePositionDtoList != null && sysEmployeePositionDtoList.size() > 0){
                sysUser.setPositions(StringUtils.join(sysEmployeePositionDtoList.stream().map(SysEmployeePositionDto :: getRoleId).collect(Collectors.toSet()),","));
            	sysUser.setPositionName(sysEmployeePositionDtoList.stream().map(SysEmployeePositionDto :: getPositionName).collect(Collectors.joining(",")));
            }
            return succeed(sysUser);
        }
        return failed("获取用户信息失败");
    }

    @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();
    }
}
