package org.jeecg.modules.system.app.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.app.dto.AppInstructorDTO;
import org.jeecg.modules.system.app.entity.AppInstructor;
import org.jeecg.modules.system.app.service.IAppInstructorService;
import org.jeecg.modules.system.app.vo.staff.StaffRequestVO;
import org.jeecg.modules.system.app.vo.staff.StaffResponseVO;
import org.jeecg.modules.system.app.vo.staff.StaffSaveVO;
import org.jeecg.modules.system.app.vo.staff.StaffVO;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 教练表
 * @Author: jeecg-boot
 * @Version: V1.0
 */
@Tag(name="员工信息")
@RestController
@RequestMapping("/staff/staff")
@Slf4j
public class AppInstructorController extends JeecgController<AppInstructor, IAppInstructorService> {
	@Autowired
	private IAppInstructorService appInstructorService;
	 @Autowired
	 private ISysUserService sysUserService;
	@Autowired
	private BaseCommonService baseCommonService;
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysRoleService iSysRoleService;

	/**
	 * 分页列表查询
	 *
	 * @param staffRequestVO
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "教练表-分页列表查询")
	@Operation(summary="员工信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<StaffResponseVO>> queryPageList(StaffRequestVO staffRequestVO,
													  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													  HttpServletRequest req) {

		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		Page<StaffResponseVO> page = new Page<StaffResponseVO>(pageNo, pageSize);
		IPage<StaffResponseVO> pageList = appInstructorService.findPage(page, staffRequestVO,loginUser.getOrgCode());
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param staffSaveVO
	 * @return
	 */
	@AutoLog(value = "员工信息-添加")
	@Operation(summary="员工信息-添加")
	@RequiresPermissions("staff:add")
	@PostMapping(value = "/add")
	@Transactional
	public Result<String> add(@RequestBody StaffSaveVO staffSaveVO) {
		try {
			SysUser user = new SysUser();
			AppInstructor appInstructor = new AppInstructor();
			if (StringUtils.isEmpty(staffSaveVO.getSelectedroles())){
				return Result.error("角色权限为空");
			}
			if (StringUtils.isEmpty(staffSaveVO.getSelecteddeparts())){
				return Result.error("所属部门为空");
			}

			SysUser sysUser =	sysUserService.findByUserName(staffSaveVO.getUsername());
			if (sysUser!=null){
				return Result.error("该登录账号已存在");
			}
			SysRole sysRole = iSysRoleService.getById(staffSaveVO.getSelectedroles());
			if (sysRole==null||StringUtils.isEmpty(sysRole.getRoleCode())){
				return Result.error("未查询到角色信息");
			}
			SysDepart departById =null;

			if (sysRole.getRoleCode().indexOf("instructor")==0){
				if (staffSaveVO.getSelecteddeparts().contains(",")){
					return Result.error("该角色涉及教练，不允许多部门");
				}
				departById = sysDepartService.getDepartById(staffSaveVO.getSelecteddeparts());
			}else {
				String dept=null;
				if (staffSaveVO.getSelecteddeparts().indexOf(",")>0){
					dept=staffSaveVO.getSelecteddeparts().split(",")[0];
				}else {
					dept=staffSaveVO.getSelecteddeparts();
				}
				departById = sysDepartService.getDepartById(dept);
			}
			if (departById==null){
				return Result.error("未查询到部门信息");
			}
			LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			try {
				BeanUtils.copyProperties(staffSaveVO,user);
				user.setId(UuidUtils.getUUID());
				user.setCreateBy(loginUser.getUsername());
				user.setCreateTime(new Date());//设置创建时间
				String salt = oConvertUtils.randomGen(8);
				user.setSalt(salt);
				String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
				user.setPassword(passwordEncode);
				user.setStatus(1);
				user.setDelFlag(CommonConstant.DEL_FLAG_0);
				user.setUserIdentity(CommonConstant.USER_IDENTITY_1);
				//用户表字段org_code不能在这里设置他的值
				user.setOrgCode(departById.getOrgCode());
				// 保存用户走一个service 保证事务
				sysUserService.saveUser(user, staffSaveVO.getSelectedroles(), staffSaveVO.getSelecteddeparts(), null);
				baseCommonService.addLog("添加用户，username： " +user.getUsername() ,CommonConstant.LOG_TYPE_2, 2);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("添加失败！");
			}
			if (sysRole.getRoleCode().indexOf("instructor")==0){
				BeanUtils.copyProperties(staffSaveVO,appInstructor);
				if (appInstructor.getStatus().equals(1)){
					appInstructor.setStatus(0);
				}else {
					appInstructor.setStatus(1);
				}
				appInstructor.setId(UuidUtils.getUUID());
				appInstructor.setUserId(user.getId());
				appInstructor.setOrgCode(departById.getOrgCode());
				appInstructor.setDelFlag(CommonConstant.DEL_FLAG_0);
				appInstructorService.save(appInstructor);
			}

		} catch (BeansException e) {
			e.getMessage();
			return Result.error("添加失败！");
		}
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param staffSaveVO
	 * @return
	 */
	@AutoLog(value = "员工信息-编辑")
	@Operation(summary="员工信息-编辑")
	@RequiresPermissions("staff:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@Transactional
	public Result<String> edit(@RequestBody StaffSaveVO staffSaveVO) {
		try {
			if (staffSaveVO==null||StringUtils.isEmpty(staffSaveVO.getId())){
				return Result.error("编辑失败!请选择需要编辑的员工信息。");
			}
			StaffVO staffVO =sysUserService.findByUserIdStaff(staffSaveVO.getId());
			if (staffVO==null){
				return Result.error("编辑失败!未查询到需要编辑的员工信息。");
			}

			if (!(StringUtils.isNotEmpty(staffVO.getUsername())&&staffVO.getUsername().equals(staffSaveVO.getUsername()))){
				SysUser sysUserO =	sysUserService.findByUserName(staffSaveVO.getUsername());
				if (sysUserO!=null){
					return Result.error("该登录账号已存在");
				}
			}
			if (StringUtils.isEmpty(staffVO.getStaffId())){
				return Result.error("编辑失败!未知员工信息");
			}
			if (StringUtils.isEmpty(staffSaveVO.getSelectedroles())){
				return Result.error("角色权限为空");
			}
			if (StringUtils.isEmpty(staffSaveVO.getSelecteddeparts())){
				return Result.error("所属部门为空");
			}
			SysRole sysRole = iSysRoleService.getById(staffSaveVO.getSelectedroles());
			if (sysRole==null||StringUtils.isEmpty(sysRole.getRoleCode())){
				return Result.error("未查询到角色信息");
			}
			SysDepart departById =null;
			if (sysRole.getRoleCode().indexOf("instructor")==0){
				if (staffSaveVO.getSelecteddeparts().contains(",")){
					return Result.error("该角色涉及教练，不允许多部门");
				}
				departById = sysDepartService.getDepartById(staffSaveVO.getSelecteddeparts());
			}else {
				String dept=null;
				if (staffSaveVO.getSelecteddeparts().indexOf(",")>0){
					dept=staffSaveVO.getSelecteddeparts().split(",")[0];
				}else {
					dept=staffSaveVO.getSelecteddeparts();
				}
				departById = sysDepartService.getDepartById(dept);
			}
			if (departById==null){
				return Result.error("未查询到部门信息");
			}
			SysUser sysUserById = sysUserService.findById(staffVO.getStaffId());
			if (sysUserById==null){
				return Result.error("编辑失败!未查询到需要编辑的员工信息。");
			}
			LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			SysUser sysUser = new SysUser();
			BeanUtils.copyProperties(staffSaveVO,sysUser);
			sysUser.setId(staffVO.getStaffId());
			sysUser.setOrgCode(departById.getOrgCode());
			sysUser.setUpdateBy(loginUser.getUsername());
			sysUser.setUpdateTime(new Date());
			String passwordEncode =sysUserById.getPassword();
			if (StringUtils.isNotEmpty(staffSaveVO.getPassword())){
				passwordEncode = PasswordUtil.encrypt(sysUserById.getUsername(), staffSaveVO.getPassword(), sysUserById.getSalt());
			}
			sysUser.setPassword(passwordEncode);
			sysUserService.editUser(sysUser, staffSaveVO.getSelectedroles(), staffSaveVO.getSelecteddeparts(), null, null);
			boolean fal=StringUtils.isNotEmpty(staffVO.getInstructorId());
			AppInstructor appInstructor = new AppInstructor();
			BeanUtils.copyProperties(staffSaveVO,appInstructor);
			if (sysRole.getRoleCode().indexOf("instructor")==0&&fal){
				appInstructor.setId(staffVO.getInstructorId());
				appInstructor.setUpdateBy(loginUser.getUsername());
				appInstructor.setUpdateTime(new Date());
				if (staffSaveVO.getStatus().equals(1)){
					appInstructor.setStatus(0);
				}else {
					appInstructor.setStatus(1);
				}
				appInstructor.setOrgCode(departById.getOrgCode());
				appInstructorService.updateById(appInstructor);
			}else if (sysRole.getRoleCode().indexOf("instructor")==0&&!fal){
				appInstructor.setId(UuidUtils.getUUID());
				appInstructor.setUserId(sysUser.getId());
				appInstructor.setDelFlag(CommonConstant.DEL_FLAG_0);
				if (staffSaveVO.getStatus().equals(1)){
					appInstructor.setStatus(0);
				}else {
					appInstructor.setStatus(1);
				}
				appInstructor.setOrgCode(departById.getOrgCode());
				appInstructorService.save(appInstructor);
			}else if (sysRole.getRoleCode().indexOf("instructor")!=0&&fal){
				appInstructor.setId(staffVO.getInstructorId());
				appInstructor.setDelFlag(CommonConstant.DEL_FLAG_1);
				appInstructor.setUpdateBy(loginUser.getUsername());
				appInstructor.setUpdateTime(new Date());
				if (staffSaveVO.getStatus().equals(1)){
					appInstructor.setStatus(0);
				}else {
					appInstructor.setStatus(1);
				}
				appInstructor.setOrgCode(departById.getOrgCode());
				appInstructorService.updateById(appInstructor);
				appInstructorService.removeById(staffVO.getInstructorId());
			}
		} catch (BeansException e) {
			e.getMessage();
			return Result.error("编辑失败!");
		}
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "员工信息-通过id删除")
	@Operation(summary="员工信息-通过id删除")
	@RequiresPermissions("staff:delete")
	@DeleteMapping(value = "/delete")
	@Transactional
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		try {
			StaffVO staffVO =sysUserService.findByUserIdStaff(id);
			if (staffVO==null){
				return Result.error("删除失败！未查询到信息");
			}
			LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			SysUser sysUser = new SysUser();
			sysUser.setId(staffVO.getStaffId());
			sysUser.setDelFlag(CommonConstant.DEL_FLAG_1);
			sysUser.setUpdateBy(loginUser.getUsername());
			sysUser.setUpdateTime(new Date());
			Integer i=sysUserService.updateDelStatus(sysUser);
			if (i<1){
				return Result.error("删除失败！");
			}
			if (StringUtils.isNotEmpty(staffVO.getInstructorId())){
				AppInstructor appInstructor = new AppInstructor();
				appInstructor.setId(staffVO.getInstructorId());
				appInstructor.setDelFlag(CommonConstant.DEL_FLAG_1);
				appInstructor.setUpdateBy(loginUser.getUsername());
				appInstructor.setUpdateTime(new Date());
				i=appInstructorService.updateDelStatus(appInstructor);
				if (i<1){
					return Result.error("删除失败！");
				}
			}
		} catch (Exception e) {
			e.getMessage();
			return Result.error("删除失败!");
		}
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "员工信息-批量删除")
	@Operation(summary="员工信息-批量删除")
	@RequiresPermissions("staff:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.appInstructorService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "教练表-通过id查询")
	@Operation(summary="员工信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<StaffVO> queryById(@RequestParam(name="id",required=true) String id) {
		StaffVO staffVO = appInstructorService.findById(id);
		if(staffVO==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(staffVO);
	}

	/**
	 * 修改状态
	 *
	 * @param sysUser
	 * @return
	 */
	//@AutoLog(value = "教练表-通过id查询")
	@Operation(summary="员工信息-修改状态")
	@PutMapping(value = "/updateStatus")
	public Result<String> updateStatus(@RequestBody  SysUser sysUser) {
		StaffVO staffVO = appInstructorService.findById(sysUser.getId());
		if(staffVO==null) {
			return Result.error("未找到对应数据");
		}
		if (StringUtils.isNotEmpty(staffVO.getInstructorId())){
			AppInstructor appInstructor = new AppInstructor();
			appInstructor.setId(staffVO.getInstructorId());
			appInstructor.setStatus(sysUser.getStatus());
			appInstructorService.updateById(appInstructor);
		}
		sysUserService.updateById(sysUser);
		return Result.OK("修改状态成功");
	}

    /**
    * 导出excel
    *
    * @param request
    * @param appInstructor
    */
    @RequiresPermissions("staff:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AppInstructor appInstructor) {
        return super.exportXls(request, appInstructor, AppInstructor.class, "员工表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("staff:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AppInstructor.class);
    }

	/**
	 * 通过部门查询教练列表
	 *
	 * @param orgCode
	 * @return
	 */
	//@AutoLog(value = "教练表-通过部门查询教练列表")
	@Operation(summary="员工信息-通过部门查询教练列表")
	@GetMapping(value = "/queryList")
	public Result<List<AppInstructorDTO>> queryList(@RequestParam(name="orgCode",required=true) String orgCode) {

		List<AppInstructor> list = Optional.ofNullable(appInstructorService.list(Wrappers.<AppInstructor>lambdaQuery().likeRight(AppInstructor::getOrgCode, orgCode))).orElse((List.of()));
		List<AppInstructorDTO> dtoList = list.stream().map(e -> {
			AppInstructorDTO dto = new AppInstructorDTO();
			SysUser sysUser = sysUserService.getById(e.getUserId());
			dto.setUserId(e.getUserId()).setName(sysUser.getRealname());
			return dto;
		}).collect(Collectors.toList());
		return Result.OK(dtoList);
	}

}
