package com.usky.system.controller.web;

import com.usky.common.core.util.StringUtils;
import com.usky.common.log.annotation.Log;
import com.usky.common.log.enums.BusinessType;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessErrorCode;
import com.usky.system.domain.SysUser;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.service.ISysUserService;
import com.usky.system.service.SysTenantService;
import com.usky.system.service.vo.SysTenantTwoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 租户管理-管理员配置
 *
 * @author yq
 */
@RestController
@RequestMapping("/userconfig")
public class UserConfigController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysTenantService sysTenantService;


    /**
     * 租户管理-管理员配置-新增
     *
     * @param user
     * @return
     */
//    @Log(title = "租户管理-管理员配置", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping("/addUserData")
    public ApiResult<Void> addUserData(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName(),user.getTenantId()))) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique1(user.getPhonenumber(),user.getTenantId()))){
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增手机号'" + user.getPhonenumber() + "'失败，手机号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setCreateTime(new Date());
        user.setUserType("01");
        user.setFullName(user.getNickName());
//        user.setStatus("0");
        user.setDelFlag("0");
        int row = userService.addUser(user);
        return toAjax(row);
    }


    /**
     * 租户管理-管理员配置-修改
     *
     * @param user
     * @return
     */
    @Log(title = "修改租户信息", businessType = BusinessType.UPDATE)
    @Transactional
    @PostMapping("/updateserData")
    public ApiResult<Void> updateserData(@Validated @RequestBody SysUser user) {
        if(StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        return toAjax(userService.updateUserData(user));
    }


    /**
     * 租户管理-管理员配置-删除
     *
     * @param userId 用户ID
     * @return
     */
    @Log(title = "删除租户", businessType = BusinessType.DELETE)
    @GetMapping("/delUsers")
    public ApiResult<Void> delUsers(@RequestParam Long userId) {
        SysUser user = new SysUser();
        if (userId == 0 && userId == null) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "用户ID不能为空");
        }
        user.setUserId(userId);
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        user.setRemark("注销用户");
        user.setDelFlag("2");
        return toAjax(userService.updateUserData(user));
    }


    /**
     * 租户管理-管理员配置-重置密码
     *
     * @param newPassword 新密码
     * @param UserId      用户ID
     * @return
     */
    @Log(title = "重置租户密码", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public ApiResult updatePwd(String newPassword, Long UserId) {
        SysUser sysUser = userService.selectUserById(UserId);
        if (sysUser.getUserId() == 0 && sysUser.getUserId() == null) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "无此用户，请联系管理员");
        }
        if (SecurityUtils.matchesPassword(newPassword, sysUser.getPassword())) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新密码不能与旧密码相同");
        }
        userService.resetUserPwdOne(UserId, SecurityUtils.encryptPassword(newPassword));
        return ApiResult.success();
    }


    /**
     * 租户管理-管理员配置-管理员信息查询
     *
     * @param tenantId 租户ID
     * @param page     当前页
     * @param size     每页条数
     * @return
     */
    @GetMapping("getUserList")
    public ApiResult<CommonPage<SysUser>> getUserList(@RequestParam(value = "tenantId", required = false, defaultValue = "0") Integer tenantId,
                                                      @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                                                      @RequestParam(value = "size", required = false, defaultValue = "0") Integer size,
                                                      @RequestParam(value = "userId", required = false, defaultValue = "0") long userId,
                                                      @RequestParam(value = "nickName",required = false) String nickName) {
        return ApiResult.success(userService.userList(tenantId, page, size, userId, nickName));
    }


    /**
     * 租户管理-管理员配置-列表查询
     *
     * @param tenantName    租户名称
     * @param tenantManager 租户责任人名称
     * @param page          当前页
     * @param size          每页条数
     * @return
     */
    @GetMapping("getTenantDataOne")
    public ApiResult<CommonPage<SysTenantTwoVo>> getTenantDataOne(@RequestParam(value = "tenantName", required = false) String tenantName,
                                                                  @RequestParam(value = "tenantManager", required = false) String tenantManager,
                                                                  @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                                                                  @RequestParam(value = "size", required = false, defaultValue = "0") Integer size) {
        return ApiResult.success(sysTenantService.getTenantDataOne(tenantName, tenantManager, page, size));
    }


}
