package com.ruoyi.xq.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.BeanConvertUtil;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.domain.UserInfo;
import com.ruoyi.xq.dto.admin.user.FullUserVo;
import com.ruoyi.xq.dto.admin.user.UserAdminUpdateVo;
import com.ruoyi.xq.dto.admin.user.UserAdminVo;
import com.ruoyi.xq.dto.admin.user.req.AddUserReq;
import com.ruoyi.xq.dto.admin.user.req.ResetPasswordAdminReq;
import com.ruoyi.xq.dto.admin.user.req.UpdateMobileAdminReq;
import com.ruoyi.xq.dto.admin.user.req.UpdateUserReq;
import com.ruoyi.xq.dto.app.common.IdReq;
import com.ruoyi.xq.service.UserInfoService;
import com.ruoyi.xq.service.UserInviteService;
import com.ruoyi.xq.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理
 *
 * @author 77
 * @date 2024-03-04
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xq/user")
public class UserController extends BaseController {

    private final UserService userService;
    private final UserInviteService userInviteService;
    private final UserInfoService userInfoService;


    /**
     * 查询用户管理列表
     */
    @SaCheckPermission("xq:user:list")
    @GetMapping("/list")
    public TableDataInfo<UserAdminVo> list(UserAdminVo bo, PageQuery pageQuery) {
        Page<UserAdminVo> page = userService.pageAdmin(pageQuery, bo);
        return TableDataInfo.build(page);
    }


    @SaCheckPermission("xq:user:list")
    @GetMapping("/fullUser")
    public R<FullUserVo> fullUser(Long userId) {
        FullUserVo vo = userService.fullUserAdmin(userId);
        return R.ok(vo);
    }

    @GetMapping("/getByUsercode")
    public R<User> getByUsercode(String usercode){
        return R.ok(userService.getByUsercode(usercode));
    }

    @GetMapping("/listByUserCode")
    public R<List<String>> listByUserCode(String usercode, int limit){
        if(limit == 0){
            limit = 40;
        }
        List<User> users = userService.list(Wrappers.lambdaQuery(User.class)
                .select(User::getUsercode)
                .like(StringUtils.isNotEmpty(usercode), User::getUsercode, usercode)
                .last("limit " + limit));
        return R.ok(users.stream().map(User::getUsercode).collect(Collectors.toList()));
    }

    @PostMapping("/resetPwd")
    @SaCheckPermission("xq:user:restPwd")
    @Log(title = "重置用户密码", businessType = BusinessType.UPDATE)
    public R<Void> resetPwd(@RequestBody ResetPasswordAdminReq req) {
        User user = userService.getById(req.getUserId());
        userService.resetPassword(req.getUserId(),user.getPassword());
        return R.ok();
    }

    @SaCheckPermission("xq:user:updateMobile")
    @Log(title = "修改用户手机", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/updateMobile")
    public R<Void> updateMobile(@RequestBody UpdateMobileAdminReq bo) {
        userService.updateMobileUser(bo);
        return R.ok();
    }

    @SaCheckPermission("xq:user:unBindInvite")
    @Log(title = "解绑用户邀请人", businessType = BusinessType.OTHER)
    @GetMapping("/unBindInvite")
    public R<Void> unBindInvite(Long userId) {
        userInviteService.unBindInviteUser(userId);
        return R.ok();
    }

    @SaCheckPermission("xq:user:bindInvite")
    @Log(title = "绑定用户邀请人", businessType = BusinessType.OTHER)
    @GetMapping("/bindInvite")
    public R<Void> bindInvite(Long userId,String inviteUsercode) {
        userInviteService.bindInvite(userId,inviteUsercode);
        return R.ok();
    }

    @PostMapping("/resetAvatar")
    @SaCheckPermission("xq:user:resetAvatar")
    @Log(title = "重置用户头像", businessType = BusinessType.UPDATE)
    public R<Void> resetAvatar(@RequestBody IdReq res){
        userService.resetAvatar(res.getId());
        return R.ok();
    }

    @PostMapping("/resetNickname")
    @SaCheckPermission("xq:user:resetNickname")
    @Log(title = "重置用户昵称", businessType = BusinessType.UPDATE)
    public R<Void> resetNickname(@RequestBody IdReq res){
        userService.resetNickname(res.getId());
        return R.ok();
    }

    @PostMapping("/lock")
    @SaCheckPermission("xq:user:lock")
    @Log(title = "封禁用户", businessType = BusinessType.UPDATE)
    public R<Void> lock(@RequestBody IdReq res){
        userService.lock(res.getId());
        return R.ok();
    }


    @PostMapping("/unlock")
    @SaCheckPermission("xq:user:unlock")
    @Log(title = "解封用户", businessType = BusinessType.UPDATE)
    public R<Void> unlock(@RequestBody IdReq res){
        userService.unlock(res.getId());
        return R.ok();
    }



    /**
     * 获取用户管理详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("xq:user:query")
    @GetMapping("/{id}")
    public R<UserAdminUpdateVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        User user = userService.getById(id);
        UserInfo userInfo = userInfoService.getByUserId(user.getId());
        UserAdminUpdateVo res = BeanConvertUtil.convertTo(user, UserAdminUpdateVo::new);
        res.setCarStatus(userInfo.getCarStatus());
        res.setHousingStatus(userInfo.getHousingStatus());
        return R.ok(res);
    }

    /**
     * 新增用户管理
     */
    @SaCheckPermission("xq:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@RequestBody AddUserReq bo) {
        userService.saveUser(bo);
        return R.ok();
    }

    /**
     * 修改用户管理
     */
    @SaCheckPermission("xq:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@RequestBody UpdateUserReq bo) {
        userService.updateBaseUser(bo);
        return R.ok();
    }

    /**
     * 删除用户管理
     *
     * @param ids 主键串
     */
    @SaCheckPermission("xq:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(userService.removeBatchByIds(Arrays.asList(ids)));
    }
}
