package com.storlead.centre.system;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.ecode.PasswordEncoder;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.web.assemble.Result;
import com.storlead.user.pojo.dto.SetUserDetailDTO;
import com.storlead.user.pojo.dto.UserParam;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.pojo.vo.SetUserDetailVo;
import com.storlead.user.pojo.vo.UserVo;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.IUserRoleService;
import com.storlead.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * @program: sp-cloud
 * @description:
 * @author: chenkq
 * @create: 2022-05-20 12:08
 */
@Slf4j
@Api(tags = "用户: 用户管理")
@RestController
@RequestMapping("/sys/user")
public class UserApiController {

    @Resource
    private IUserService userService;

    @Resource
    private IDepartService departService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @ApiOperation("根据部门id查询用户")
    @PostMapping("listByDeptId")
    public Result listByDeptId(Long deptId) {

        List<UserEntity> list = userService.list(
                new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getDeptId,deptId)
                        .ne(UserEntity::getStatus,Integer.valueOf(5))
                        .eq(UserEntity::getIsDelete,0));
        return Result.ok(list);
    }
    @ApiOperation("分页查询用户")
    @PostMapping("pagelist")
    public Result pagelist(@RequestBody UserParam param) {

//        param.setCommonQueryOrderBy("UserEntity");

        IPage<UserVo> page = new Page<>(param.getPageIndex(),param.getPageSize());
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<UserEntity>(new UserEntity());
        queryWrapper.eq(UserEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(param.getBlurry())) {
            queryWrapper.like(UserEntity::getUserName,param.getBlurry()).or().like(UserEntity::getRealName,param.getBlurry());
        }
        if (StrUtil.isNotBlank(param.getOrgRouteCode())) {
            queryWrapper.likeRight(UserEntity::getOrgRouteCode,param.getOrgRouteCode());
        }
//        if (Objects.isNull(param.getStatus())) {
//            queryWrapper.ne(UserEntity::getStatus,Integer.valueOf(5));
//        } else {
//            queryWrapper.ne(UserEntity::getStatus,param.getStatus());
//        }
        if (!param.getIsIncludeResign()) {
            queryWrapper.ne(UserEntity::getStatus,Integer.valueOf(5));
        }
        queryWrapper.orderByDesc(UserEntity::getEmail);
//        List<UserVo> us  = userService.listWithScopeVo(page,queryWrapper,param);
//        if (CollectionUtil.isNotEmpty(us)) {
//            List<Long> userIds = us.stream().map(UserVo::getId).collect(Collectors.toList());
//            List<UserRoleEntity> userRolels = userRoleService.selectUserRole(new LambdaQueryWrapper<UserRoleEntity>().in(UserRoleEntity::getUserId,userIds));
//            if (CollectionUtil.isNotEmpty(userRolels)) {
//                List<RoleEntity> rs = roleService.list(new LambdaQueryWrapper<RoleEntity>().in(RoleEntity::getId,userRolels.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList())));
//                us.forEach(u -> {
//                    List<RoleEntity> roles = rs.stream().filter(r -> userRolels.stream().anyMatch(ur -> ur.getRoleId().equals(r.getId()) && ur.getUserId().equals(u.getId()))).collect(Collectors.toList());
//                    if(CollectionUtil.isNotEmpty(roles)) {
//                        u.setRoleNames(roles.stream().map(RoleEntity::getName).collect(Collectors.toList()));
//                        u.setRoleIds(roles.stream().map(RoleEntity::getId).collect(Collectors.toList()));
//                    }
//                });
//            }
//
//            us.forEach(e -> {
//                e.setIdNum("");
//                e.setPassword("");
//                e.setBankCardNum("");
//                e.setBankName("");
//                e.setEducation("");
//                e.setAddress("");
//                e.setBirthday(null);
//                e.setEmail("");
//            });
//        }
        page.setRecords(null);
        return Result.ok(page);
    }

    @ApiOperation("分页查询用户")
    @PostMapping("pageScopelist")
    public Result pageScopelist(@RequestBody UserParam param) {

        IPage<UserVo> page = new Page<>(param.getPageIndex(),param.getPageSize());
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<UserEntity>(new UserEntity());
        queryWrapper.eq(UserEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(param.getBlurry())) {
            queryWrapper.like(UserEntity::getUserName,param.getBlurry()).or().like(UserEntity::getRealName,param.getBlurry());
        }
        if (StrUtil.isNotBlank(param.getOrgRouteCode())) {
            queryWrapper.likeRight(UserEntity::getOrgRouteCode,param.getOrgRouteCode());
        }
        if (!param.getIsIncludeResign()) {
            queryWrapper.ne(UserEntity::getStatus,Integer.valueOf(5));
        }
        queryWrapper.orderByDesc(UserEntity::getEmail);
//        List<UserVo> us  = userService.listWithScopeVo(page,queryWrapper,param);
//        if (CollectionUtil.isNotEmpty(us)) {
//            List<Long> userIds = us.stream().map(UserVo::getId).collect(Collectors.toList());
//            List<UserRoleEntity> userRolels = userRoleService.selectUserRole(new LambdaQueryWrapper<UserRoleEntity>().in(UserRoleEntity::getUserId,userIds));
//            if (CollectionUtil.isNotEmpty(userRolels)) {
//                List<RoleEntity> rs = roleService.list(new LambdaQueryWrapper<RoleEntity>().in(RoleEntity::getId,userRolels.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList())));
//                us.forEach(u -> {
//                    List<RoleEntity> roles = rs.stream().filter(r -> userRolels.stream().anyMatch(ur -> ur.getRoleId().equals(r.getId()) && ur.getUserId().equals(u.getId()))).collect(Collectors.toList());
//                    if(CollectionUtil.isNotEmpty(roles)) {
//                        u.setRoleNames(roles.stream().map(RoleEntity::getName).collect(Collectors.toList()));
//                        u.setRoleIds(roles.stream().map(RoleEntity::getId).collect(Collectors.toList()));
//                    }
//                });
//            }
//
//            us.forEach(e -> {
//                e.setIdNum("");
//                e.setPassword("");
//                e.setBankCardNum("");
//                e.setBankName("");
//                e.setEducation("");
//                e.setAddress("");
//                e.setBirthday(null);
//                e.setEmail("");
//            });
//        }
        page.setRecords(null);
        return Result.ok(page);
    }

    @ApiOperation("删除人员数据")
    @PostMapping("delete")
    public Result delete(Long [] ids) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.in(UserEntity::getId,Arrays.asList(ids));
        update.set(UserEntity::getIsDelete,1);
        userService.update(update);
        return Result.ok();
    }


    @ApiOperation("标记冻结")
    @PostMapping("markFreeze")
    public Result markFreeze(Long [] ids,Integer isFreeze) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.in(UserEntity::getId,Arrays.asList(ids));
        update.set(UserEntity::getIsFreeze,isFreeze);
        userService.update(update);
        if(Integer.valueOf(0).equals(isFreeze)) {
            userService.updateLastFollowUpTime(Arrays.asList(ids));
        }
        return Result.ok();
    }


    @ApiOperation("删除人员数据")
    @PostMapping("deleteById")
    public Result deleteById(Long id) {
        if (id == null) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.eq(UserEntity::getId,id);
        update.set(UserEntity::getIsDelete,1);
        userService.update(update);
        return Result.ok();
    }

    @ApiOperation("删除人员数据")
    @PostMapping("updateRealName")
    public Result deleteById(Long id,String realName) {
        if (id == null) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.eq(UserEntity::getId,id);
        update.set(UserEntity::getRealName,realName);
        userService.update(update);
        return Result.ok();
    }


    @ApiOperation("启用禁用员工")
    @PostMapping("enable")
    public Result setEnable(Long [] ids,Boolean enable) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper();
        update.in(UserEntity::getId,Arrays.asList(ids));
        update.set(UserEntity::getEnabled,enable);
        Boolean re =  userService.update(update);
        if (re) {
            return Result.ok();
        } else {
            return Result.error("操作失败");
        }
    }


    @ApiOperation("根据ids查询用户")
    @PostMapping("queryByIds")
    public Result queryByIds(Long [] ids) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<UserEntity> query = new LambdaUpdateWrapper();
        query.in(UserEntity::getId,Arrays.asList(ids));
        List<UserEntity> list  =  userService.list(query);
        return Result.ok(list);
    }


    @ApiOperation("同步OA数据")
    @PostMapping("syncOa")
    public Result syncOa() {
       userService.syncOa();
       return Result.ok();
    }

    @ApiOperation("同步OA数据")
    @PostMapping("syncWxId")
    public Result syncOasyncWxId() {
        userService.syncWxId();
        return Result.ok();
    }

    @ApiOperation("重置密码")
    @PostMapping("resetPassword")
    public Result resetPassword(Long userId) {
        if  (Objects.isNull(userId)) {
            return Result.error("参数错误");
        }
        String defaultPassWord = "storlead123456";
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper<UserEntity>();
        update.eq(UserEntity::getId,userId);
        update.set(UserEntity::getPassword,passwordEncoder.encode(defaultPassWord));
        userService.update(update);
        return Result.ok();
    }

    @ApiOperation("修改用户信息")
    @PostMapping("updateUserInfo")
    public Result setPhone(SetUserDetailDTO dto) {
        Long userId = LoginUserUtil.getCurrentUserId();
        if  (Objects.isNull(userId)) {
            return Result.error("您未登录");
        }
        if  (StrUtil.isBlank(dto.getAvatar())) {
            return Result.error("参数错误,头像url不能为空");
        }
        if  (StrUtil.isBlank(dto.getMobile())) {
            return Result.error("参数错误,手机号不能为空");
        }
        UserEntity entity = userService.getById(userId);
        if (Objects.isNull(entity)) {
            return Result.error("未找到当前用户,请重新登录");
        }
        UserEntity oUser = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getMobile,dto.getMobile()).eq(UserEntity::getIsDelete,0).last("limit 1"));
        if (Objects.nonNull(oUser)) {
            if (!oUser.getId().equals(userId)) {
                return Result.error("该手机'"+dto.getMobile()+"'号已被占用!");
            }
        }
        if  (StrUtil.isNotBlank(dto.getEmail())) {
            oUser = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getMobile,dto.getEmail()).eq(UserEntity::getIsDelete,0).last("limit 1"));
            if (Objects.nonNull(oUser)) {
                if (!oUser.getId().equals(userId)) {
                    return Result.error("该邮箱'"+dto.getEmail()+"'已被占用!");
                }
            }
        }
        LambdaUpdateWrapper<UserEntity> update = new LambdaUpdateWrapper<>();
        update.eq(UserEntity::getId, userId);

        update.set(UserEntity::getAvatar, dto.getAvatar())
              .set(UserEntity::getEmail, dto.getEmail())
              .set(UserEntity::getNickName, dto.getNickName())
              .set(UserEntity::getRealName, dto.getRealName())
              .set(UserEntity::getMobile, dto.getMobile())
              .set(UserEntity::getSex, dto.getSex())
              .set(UserEntity::getBirthday, dto.getBirthday());

        if (StrUtil.isNotBlank(dto.getJobDes())) {
            update.set(UserEntity::getJobDes, dto.getJobDes());
        }

        try {
            boolean result = userService.update(update);
            if (!result) {
                return Result.error("更新用户信息失败，请重试。");
            }
        } catch (Exception e) {
            log.error("更新用户信息发生错误: {}", e.getMessage());
            return Result.error("系统错误，更新用户信息失败。");
        }

        if (StrUtil.isNotBlank(dto.getDeptJobDes()) && Objects.nonNull(entity.getDeptId())) {
            DeptEntity dept = departService.getById(entity.getDeptId());
            if (!dto.getDeptJobDes().equals(dept.getDeptJobDes())) {
                if (Integer.valueOf(0).equals(entity.getIsLeader())) {
                    return Result.error("只有领导才能设置部门职责");
                }
                LambdaUpdateWrapper<DeptEntity> dUpdate = new LambdaUpdateWrapper<DeptEntity>();
                dUpdate.eq(DeptEntity::getId,entity.getDeptId());
                dUpdate.set(DeptEntity::getDeptJobDes,dto.getDeptJobDes());
                departService.update(dUpdate);
            }
        }
        return Result.ok();
    }

    @ApiOperation("获取用户基础信息")
    @PostMapping("getSimpleUserInfo")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SetUserDetailVo.class)
    })
    public Result getSimpleUserInfo() {
        Long userId = LoginUserUtil.getCurrentUserId();
        if  (Objects.isNull(userId)) {
            return Result.error("您未登录");
        }
        UserVo entity = userService.getUserInfoById(userId);

        SetUserDetailVo detailVo = new SetUserDetailVo();
        detailVo.setDeptId(entity.getDeptId());
        detailVo.setId(entity.getId());
        detailVo.setDeptName(entity.getDeptName());
        detailVo.setAvatar(entity.getAvatar());
        detailVo.setJobId(entity.getJobId());
        detailVo.setJobName(entity.getJobName());
        detailVo.setEmail(entity.getEmail());
        detailVo.setMobile(entity.getMobile());
        detailVo.setUserName(entity.getRealName());
        detailVo.setJobDes(entity.getJobDes());
        detailVo.setIsLeader(entity.getIsLeader());
        DeptEntity dept = departService.getById(entity.getDeptId());
        if (Objects.nonNull(dept)) {
            detailVo.setDeptJobDes(dept.getDeptJobDes());
        }
        return Result.ok(detailVo);
    }

    public void updateManagerId(UserEntity user,Long oldManagerId){
        if (Objects.isNull(user)) {
            return;
        }
        if (Objects.isNull(user.getManagerId())) {
            return;
        }
        List<UserEntity> userEntities = userService.list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getManagerId,user.getId()));
        for (UserEntity userEntity : userEntities) {
            if (StrUtil.isNotBlank(userEntity.getManagers())) {
                String routeCodeStr = ","+userEntity.getManagers()+",";
                routeCodeStr = routeCodeStr.replace(","+oldManagerId+",",","+userEntity.getManagerId()+",");
                StringUtils.startsWithIgnoreCase(routeCodeStr,",");
                StringUtils.endsWithIgnoreCase(routeCodeStr,",");

                LambdaUpdateWrapper<UserEntity> updateWrapper = new LambdaUpdateWrapper();
                updateWrapper.eq(UserEntity::getId,userEntity.getId());
                updateWrapper.set(UserEntity::getManagers,routeCodeStr);
                userService.update(updateWrapper);
            }
        }

    }
}
