package cn.quantgroup.xyqb.controller.tenant;

import cn.quantgroup.xyqb.entity.ProductLoginEntity;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.user.IOauthClientDetailsService;
import cn.quantgroup.xyqb.service.user.IProductLoginService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/tenant")
public class TenantController {


    @Autowired
    private IProductLoginService productLoginService;

    @Autowired
    private IOauthClientDetailsService oauthClientDetailsService;

    @Autowired
    private IUserService userService;

    /**
     * 根据用户ID查询租户列表
     * @param userId
     * @return
     * @Yapi http://yapi.quantgroups.com/project/17/interface/api/30068
     */
    @PostMapping("/userIdTenantList")
    public JsonResult findTenantByUserId(Long userId) {
        // 通过userId获取租户机构和产品
        List<ProductLoginEntity> productLoginEntityList = productLoginService.findSlaveByUserId(userId);
        List<Integer> tenantList = new ArrayList<>();
        if (!productLoginEntityList.isEmpty()) {
            // 通过机构和产品Id 获取租户id
            tenantList = oauthClientDetailsService.findTenantList(productLoginEntityList);
        }

        if (tenantList.isEmpty()) {
            User user = userService.findById(userId);
            if (user == null) {
                return JsonResult.buildErrorStateResult("该用户不存在", null);
            }
            tenantList.add(TenantUtil.TENANT_DEFAULT);
        }

        return JsonResult.buildSuccessResult("租户列表", tenantList);
    }

}
