package com.usky.system.controller.web;


import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessErrorCode;
import com.usky.common.log.annotation.Log;
import com.usky.common.log.enums.BusinessType;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.SysTenant;
import com.usky.system.domain.SysUser;
import com.usky.system.domain.SysUserTenant;
import com.usky.system.service.SysUserTenantService;
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.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author han
 * @since 2024-09-11
 */
@RestController
@RequestMapping("/sysUserTenant")
public class SysUserTenantController extends BaseController {

    @Autowired
    private SysUserTenantService sysUserTenantService;

    /**
     * 企业邀请用户
     */
    @Log(title = "绑定用户", businessType = BusinessType.INSERT)
    @PostMapping("/inviteUser")
    public ApiResult<Void> insertInviteUser(@RequestBody SysUserTenant sysUserTenant)
    {
        sysUserTenantService.insertInviteUser(sysUserTenant);
        return ApiResult.success();
    }

    /**
     * 解除用户绑定
     */
    @Log(title = "解除用户绑定", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tenantId}/{userId}")
    public ApiResult<Void> remove(@PathVariable Integer tenantId,@PathVariable Long userId)
    {
        Boolean isDefault = sysUserTenantService.getIdByUser(tenantId,userId);
        if (isDefault){
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "该用户默认租户不可解绑");
        }
        sysUserTenantService.deleteUserTenant(tenantId,userId);
        return ApiResult.success();
    }

    /**
     * 根据用户查询企业下拉框
     */
    @GetMapping("/getTenantByUser/{userId}")
    public ApiResult<List<SysTenant>> getTenantByUser(@PathVariable("userId") Long userId)
    {
        return ApiResult.success(sysUserTenantService.getTenantByUser(userId));
    }

    /**
     * 修改用户默认租户
     */
    @Log(title = "修改用户默认租户", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping
    public ApiResult<Void> edit(@Validated @RequestBody SysUserTenant userTenant)
    {
        sysUserTenantService.updateUserTenant(userTenant);
        return ApiResult.success();
    }
}

