package com.keao.edu.user.controller;


import com.keao.edu.auth.api.client.SysUserFeignService;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.common.controller.BaseController;
import com.keao.edu.common.entity.HttpResponseResult;
import com.keao.edu.common.page.PageInfo;
import com.keao.edu.common.page.QueryInfo;
import com.keao.edu.common.tenant.TenantContextHolder;
import com.keao.edu.user.dto.TenantInfoDto;
import com.keao.edu.user.entity.TenantInfo;
import com.keao.edu.user.service.TenantInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("tenantInfo")
@Api(tags = "机构服务")
public class TenantInfoController extends BaseController {

	@Autowired
	private TenantInfoService tenantInfoService;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	
	@ApiOperation("机构服务分页查询")
	@GetMapping(value = "/list")
	public HttpResponseResult<PageInfo<TenantInfoDto>> getList(QueryInfo queryInfo) {
		return succeed(tenantInfoService.queryTenants(queryInfo));
	}

	@ApiOperation("查询机构详情")
	@GetMapping(value = "/query")
	public HttpResponseResult<TenantInfo> query() {
		String tenantId = TenantContextHolder.getTenantId();
		if(StringUtils.isNotEmpty(tenantId)){
			return succeed(tenantInfoService.get(Integer.parseInt(tenantId)));
		}else {
			return succeed(new TenantInfo());
		}
	}

	@ApiOperation("新增机构")
	@PostMapping(value = "/add")
	public HttpResponseResult add(@RequestBody TenantInfoDto tenantInfo) {
		tenantInfoService.addTenant(tenantInfo);
		return succeed();
	}

	@ApiOperation("更新机构")
	@PostMapping(value = "/update")
	public HttpResponseResult update(@RequestBody TenantInfoDto tenantInfo) {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if(!sysUser.getIsSuperAdmin()){
			String tenantId = TenantContextHolder.getTenantId();
			if(StringUtils.isNotEmpty(tenantId)){
				tenantInfo.setId(Integer.parseInt(tenantId));
			}
		}

		tenantInfo.setUpdateTime(new Date());
		tenantInfoService.updateTenant(tenantInfo);
		return succeed();
	}

	@ApiOperation("删除")
	@PostMapping(value = "/del")
	public HttpResponseResult add(Integer id) {
		return succeed(tenantInfoService.delete(id));
	}

}
