package org.dromara.web.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.web.utils.WxXcxUtils;
import org.dromara.work.domain.TzUser;
import org.dromara.work.domain.vo.TzUserVo;
import org.dromara.work.service.ITzUserService;
import org.dromara.web.common.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author Maosw
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/user/login")
@Tag(name = "登录接口")
public class LoginController {

    private final ITzUserService tzUserService;

    private final TokenStore tokenStore;


    @PostMapping("/getUserPhoneNumber")
    @Operation(summary = "微信接口获取手机号码" , description = "微信接口获取手机号码")
    @Parameter(name = "code", description = "code", required = true)
    public ServerResponseEntity<JSONObject> getUserPhoneNumber(@RequestParam(value = "code") String code) {
//        String phone = WxXcxUtils.getUserPhoneNumber(code);
        return ServerResponseEntity.success(WxXcxUtils.getUserPhoneNumber(code));
    }

    @PostMapping("/register")
    @Operation(summary = "注册登录" , description = "用户绑定手机号注册登录")
    public ServerResponseEntity<TokenInfoVO> register(@Valid @RequestBody UserRegisterParam userRegisterParam) {
        if (StrUtil.isBlank(userRegisterParam.getNickName())) {
            userRegisterParam.setNickName(userRegisterParam.getUserName());
        }

        TzUser tzUser = tzUserService.getOne(new LambdaQueryWrapper<TzUser>().eq(TzUser::getUserMobile, userRegisterParam.getMobile()));
        if (ObjectUtil.isNotEmpty(tzUser)) {
            //登录
            UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
            userInfoInTokenBO.setUserId(tzUser.getUserId());
            userInfoInTokenBO.setSysType(0);
            userInfoInTokenBO.setEnabled(true);
            return ServerResponseEntity.success(tokenStore.storeAndGetVo(userInfoInTokenBO));
        }else {
            //注册并登录
            Date now = new Date();
            TzUser user = new TzUser();
            user.setModifyTime(now);
            user.setUserRegtime(now);
            user.setStatus(1);
            user.setUserMobile(userRegisterParam.getMobile());
            user.setNickName(userRegisterParam.getNickName());
            user.setUserMail(userRegisterParam.getUserMail());
            user.setPic(userRegisterParam.getImg());
            user.setLoginPassword(BCrypt.hashpw(userRegisterParam.getPassWord()));
            user.setOpenId(userRegisterParam.getOpenId());
            tzUserService.save(user);
            // 2. 登录
            UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
            userInfoInTokenBO.setUserId(user.getUserId());
            userInfoInTokenBO.setSysType(0);
            userInfoInTokenBO.setEnabled(true);
            return ServerResponseEntity.success(tokenStore.storeAndGetVo(userInfoInTokenBO));
        }
    }

    @PutMapping("/updatePwd")
    @Operation(summary = "修改密码" , description = "修改密码")
    public ServerResponseEntity<Boolean> updatePwd(@Valid @RequestBody UserRegisterParam userPwdUpdateParam) {
        Long userId = SecurityUtils.getUser().getUserId();
        TzUserVo user = tzUserService.queryById(userId);
        if (user == null) {
            // 无法获取用户信息
            throw new ServiceException("无法获取用户信息");
        }
        if (StrUtil.isBlank(userPwdUpdateParam.getPassWord())) {
            // 新密码不能为空
            throw new ServiceException("新密码不能为空");
        }
        String password = BCrypt.hashpw(userPwdUpdateParam.getPassWord());
        if (StrUtil.equals(password, user.getLoginPassword())) {
            // 新密码不能与原密码相同
            throw new ServiceException("新密码不能与原密码相同");
        }
        user.setModifyTime(new Date());
        user.setLoginPassword(password);

        TzUser tzUser = MapstructUtils.convert(user, TzUser.class);
        return ServerResponseEntity.success(tzUserService.updateById(tzUser));
    }

    /**
     * 获取登录用户信息
     */
    @GetMapping("/info")
    @Operation(summary = "获取登录用户信息" , description = "获取登录用户信息")
    public ServerResponseEntity<TzUserVo> info() {
        Long userId = SecurityUtils.getUser().getUserId();
        TzUserVo user = tzUserService.queryById(userId);
        return ServerResponseEntity.success(user);
    }



}
