package com.tashow.cloud.system.controller.admin.socail;

import com.tashow.cloud.common.enums.UserTypeEnum;
import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.common.pojo.PageResult;
import com.tashow.cloud.common.util.object.BeanUtils;
import com.tashow.cloud.system.controller.admin.socail.vo.user.SocialUserBindReqVO;
import com.tashow.cloud.system.controller.admin.socail.vo.user.SocialUserPageReqVO;
import com.tashow.cloud.system.controller.admin.socail.vo.user.SocialUserRespVO;
import com.tashow.cloud.system.controller.admin.socail.vo.user.SocialUserUnbindReqVO;
import com.tashow.cloud.system.convert.social.SocialUserConvert;
import com.tashow.cloud.system.dal.dataobject.social.SocialUserDO;
import com.tashow.cloud.system.service.social.SocialUserService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.tashow.cloud.common.pojo.CommonResult.success;
import static com.tashow.cloud.web.web.core.util.WebFrameworkUtils.getLoginUserId;

/**
 * 管理后台 - 社交用户
 */
@RestController
@RequestMapping("/system/social-user")
@Validated
public class SocialUserController {

    @Resource
    private SocialUserService socialUserService;

    /**
     * 社交绑定，使用 code 授权码
     */
    @PostMapping("/bind")
    public CommonResult<Boolean> socialBind(@RequestBody @Valid SocialUserBindReqVO reqVO) {
        socialUserService.bindSocialUser(
                SocialUserConvert.INSTANCE.convert(getLoginUserId(), UserTypeEnum.ADMIN.getValue(), reqVO));
        return CommonResult.success(true);
    }

    /**
     * 取消社交绑定
     */
    @DeleteMapping("/unbind")
    public CommonResult<Boolean> socialUnbind(@RequestBody SocialUserUnbindReqVO reqVO) {
        socialUserService.unbindSocialUser(
                getLoginUserId(), UserTypeEnum.ADMIN.getValue(), reqVO.getType(), reqVO.getOpenid());
        return CommonResult.success(true);
    }

    // ==================== 社交用户 CRUD ====================

    /**
     * 获得社交用户
     */
    @GetMapping("/get")
    @PreAuthorize("@ss.hasPermission('system:social-user:query')")
    public CommonResult<SocialUserRespVO> getSocialUser(@RequestParam("id") Long id) {
        SocialUserDO socialUser = socialUserService.getSocialUser(id);
        return success(BeanUtils.toBean(socialUser, SocialUserRespVO.class));
    }

    /**
     * 获得社交用户分页
     */
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermission('system:social-user:query')")
    public CommonResult<PageResult<SocialUserRespVO>> getSocialUserPage(
            @Valid SocialUserPageReqVO pageVO) {
        PageResult<SocialUserDO> pageResult = socialUserService.getSocialUserPage(pageVO);
        return success(BeanUtils.toBean(pageResult, SocialUserRespVO.class));
    }
}
