/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.demo.annotation.DemoMode;
import com.jeeplus.config.properties.JeePlusProperties;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.domain.Tenant;
import com.jeeplus.sys.model.TenantForm;
import com.jeeplus.sys.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 租户Controller
 *
 * @author jeeplus
 * @version 2021-6-2
 */
@RestController
@RequestMapping("/sys/tenant")
public class TenantController {

    @Autowired
    private TenantService tenantService;
    @Autowired
    protected JeePlusProperties jeePlusProperites;

    @GetMapping("list")
    public ResponseEntity data(Tenant tenant, Page <Tenant> page) throws Exception {
        QueryWrapper <Tenant> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( tenant, Tenant.class );
        IPage <Tenant> result = tenantService.page ( page, queryWrapper );
        return ResponseEntity.ok ( result );
    }


    /**
     * 根据Id获取数据
     */
    @GetMapping("queryById")
    public ResponseEntity queryById(String id) {
        TenantForm tenantForm = tenantService.get ( id );
        return ResponseEntity.ok ( tenantForm );
    }

    /**
     * 保存租户
     */
    @DemoMode
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody TenantForm tenantForm) {
        //新增或编辑表单保存
        tenantService.saveOrUpdate ( tenantForm );

        return ResponseEntity.ok ( "保存租户成功" );
    }

    /**
     * 批量删除租户
     */
    @DemoMode
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        String idArray[] = ids.split ( "," );
        tenantService.removeByIds ( Lists.newArrayList ( idArray ) );
        return ResponseEntity.ok ( "删除租户成功" );
    }


    /**
     * 验证tenant是否存在
     *
     * @param tenant
     * @return
     */
    @GetMapping("validateNotExist")
    public ResponseEntity validateExist(Tenant tenant) {
        tenant = tenantService.lambdaQuery ( ).eq ( StrUtil.isNotBlank ( tenant.getDomain ( ) ), Tenant::getDomain, tenant.getDomain ( ) )
                .eq ( StrUtil.isNotBlank ( tenant.getName ( ) ), Tenant::getName, tenant.getName ( ) ).one ( );

        if ( tenant == null ) {
            return ResponseEntity.ok ( true );
        } else {
            return ResponseEntity.ok ( false );
        }
    }


}
