package com.vctgo.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vctgo.common.core.constant.CacheConstants;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.core.web.controller.BaseController;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.mybatisplus.aop.TemporaryIgnoreTables;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.annotation.RequiresPermissions;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysUser;
import com.vctgo.system.api.model.LoginUser;
import com.vctgo.system.service.ISysUserService;
import com.vctgo.system.util.ConstantUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;

/**
 * 用户信息
 *
 * @author vctgo
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/user/account")
public class SysUserAccountController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisService redisService;

    /**
     * 获取分页的账号列表
     */
    @RequiresPermissions("system:account:page")
    @GetMapping("/page")
    public AjaxResult pageList(SysUser user) {
        user.getParams().put("isExistAccount", 1);
        IPage<SysUser> list = userService.selectUserPage(user);
        return AjaxResult.success(list);
    }

    /**
     * 添加账号
     */
    @TemporaryIgnoreTables
    @RequiresPermissions("system:account:add")
    @PostMapping()
    public AjaxResult addAccount(@Validated @RequestBody SysUser user) {

        if (SecurityUtils.getTenantId() == 9999L || SecurityUtils.getTenantType() == 1) {
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_user_role"));
        }

        /**
         * 账号管理-新增账号校验
         *
         * 1.原有校验全部通过（必填项、密码规则）
         *
         * 2.当前账号是否在其他园开通账号且有启用状态
         *      ①其他园无账号或有账号但无启用状态，账号新增成功
         *      ②其他园有账号且有账号状态为启用，弹框提示“该手机号已在其他园开通且为启用状态，请联系平台客服处理，或更换教职工手机号后再试”
         */
        userService.checkUserAccount(user);

        //默认密码采用随机生成
        String randomPassword = SecurityUtils.randomPassword(6);//随机密码6位
        String password = SecurityUtils.encryptPassword(randomPassword);
        user.setPassword(password);
        user.setUserName(user.getUserAccount());
        user.setAccountStatus(StrUtils.isEmpty(user.getAccountStatus()) ? ConstantUtils.ACCOUNT_STATUS_0 : user.getAccountStatus());
        user.setAccountDate(new Date());
        int result = userService.updateUserAccount(user);
        return toAjax(result, randomPassword);
    }

    /**
     * 修改账号
     */
    @TemporaryIgnoreTables
    @RequiresPermissions("system:account:edit")
    @PutMapping()
    public AjaxResult updateAccount(@Validated @RequestBody SysUser user) {

        if (SecurityUtils.getTenantType() == 1) {
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user", "sys_user_role"));
        }

        /**
         * 2.账号从禁用至启用，校验该手机号是否在其他园开通且为启用，如无则操作成功；如有操作失败，弹框提示“该手机号已在其他园开通且为启用状态，请联系平台客服处理，或更换教职工手机号后再试”
         *
         */
        if (ConstantUtils.ACCOUNT_STATUS_0.equals(user.getAccountStatus())) {
            userService.checkUserAccount(user);
        }

        int result = userService.updateUserAccount(user);

        // 凡是涉及到该角色的人员都退出登录
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser) && Objects.nonNull(onlineUser.getSysUser())
                    && onlineUser.getUserid().longValue() == user.getUserId().longValue()) {
                redisService.deleteObject(key);
            }
        }
        return toAjax(result);
    }

    /**
     * 删除用户账号信息
     */
    @RequiresPermissions("system:account:remove")
    @DeleteMapping("/{userId}")
    public AjaxResult remove(@PathVariable Long userId) {
        if (SecurityUtils.getUserId().equals(userId)) {
            return error("当前用户账号不能删除");
        }
        return toAjax(userService.deleteUserAccountById(userId));
    }
}
