package cn.ezhizao.project.tenant.controller;

import cn.ezhizao.common.constant.CacheConstants;
import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.qrCode.QrCodeService;
import cn.ezhizao.framework.redis.RedisCache;
import cn.ezhizao.framework.security.LoginUser;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.mapper.SysUserMapper;
import cn.ezhizao.project.system.service.ISysUserService;
import cn.ezhizao.project.tenant.domain.BizTenantApply;
import cn.ezhizao.project.tenant.domain.BizUserTenant;
import cn.ezhizao.project.tenant.domain.Tenant;
import cn.ezhizao.project.tenant.service.IBizTenantApplyService;
import cn.ezhizao.project.tenant.service.IBizUserTenantService;
import cn.ezhizao.project.tenant.service.ITenantService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 企业租户Controller
 *
 * @author ruoyi
 * @date 2023-08-25
 */
@RestController
@RequestMapping("/business/tenant")
public class TenantController extends BaseController
{
    @Resource
    private ITenantService tenantService;

    @Resource
    private IBizUserTenantService userTenantService;

    @Resource
    private QrCodeService qrCodeService;


    @Resource
    private SysUserMapper sysUserMapper;


    @Resource
    private ISysUserService userService;


    @Resource
    private IBizTenantApplyService tenantApplyService;

    @Resource
    private RedisCache redisCache;
    /**
     * 查询企业租户列表
     */
    @PreAuthorize("@ss.hasPermi('business:tenant:list')")
    @GetMapping("/list")
    public TableDataInfo list(Tenant tenant)
    {
        startPage();
        if(StringUtils.isNotBlank(tenant.getOperateType())){
            tenant.setUserId(SecurityUtils.getUserId());
        }
        List<Tenant> list = tenantService.getList(tenant);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('business:tenant:edit')")
    @GetMapping("/listMyTenant")
    public TableDataInfo list(BizUserTenant userTenant)
    {
        startPage();
        userTenant.setUserId(SecurityUtils.getUserId());
        List<BizUserTenant> list = userTenantService.getList(userTenant);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('business:tenant:edit')")
    @GetMapping(value = "/exitTenant/{id}")
    public AjaxResult exitTenant(@PathVariable("id") Long id)
    {
        BizUserTenant userTenant = userTenantService.getById(id);
        if(userTenant!=null){
            BizTenantApply tenantApply = new BizTenantApply();
            tenantApply.setUserId(userTenant.getUserId());
            tenantApply.setTenantId(userTenant.getTenantId());
            List<BizTenantApply> tenantApplyList = tenantApplyService.getList(tenantApply);
            if(tenantApplyList.size()==1){
                tenantApply = tenantApplyList.get(0);
            }
            tenantApply.setStatus(3);
            tenantApplyService.updateById(tenantApply);
        }
        return success(userTenantService.removeById(id));
    }



    /**
     * 导出企业租户列表
     */
    @PreAuthorize("@ss.hasPermi('business:tenant:export')")
    @Log(title = "企业租户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Tenant tenant)
    {
        List<Tenant> list = tenantService.getList(tenant);
        ExcelUtil<Tenant> util = new ExcelUtil<Tenant>(Tenant.class);
        util.exportExcel(response, list, "企业租户数据");
    }

    /**
     * 获取企业租户详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:tenant:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        Tenant tenant = new Tenant();
        tenant.setId(id);
        List<Tenant> tenants = tenantService.getList(tenant);
        if(tenants.size()==1){
            return success(tenants.get(0));
        }
       return error();
    }


    /**
     * 新增企业租户
     */
    @PreAuthorize("@ss.hasPermi('business:tenant:add')")
    @Log(title = "企业租户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Tenant tenant)
    {
        return toAjax(tenantService.save(tenant));
    }

    @Value("${token.expireTime}")
    private int expireTime;
    @PreAuthorize("@ss.hasPermi('business:tenant:edit')")
    @Log(title = "切换租户", businessType = BusinessType.UPDATE)
    @PostMapping("/changeTenant")
    public AjaxResult change(@RequestBody Tenant tenant)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUser().getUserName();
        SysUser user = userService.selectUserByUserNameAndTenantId(userName,String.valueOf(tenant.getId()));
        sysUserMapper.updateUser(user);
        loginUser.setTenantId(tenant.getId());
        loginUser.setDeptId(user.getDeptId());
        loginUser.setUser(user);
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + loginUser.getToken();
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
        return success();
    }

    /**
     * 修改企业租户
     */
    @PreAuthorize("@ss.hasPermi('business:tenant:edit')")
    @Log(title = "企业租户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Tenant tenant) throws NoSuchFieldException, IllegalAccessException {
        register(tenant);
        qrCodeService.generateIdentityQrCode(tenant);
        return toAjax(tenantService.updateById(tenant));
    }

    /**
     * 删除企业租户
     */
    @PreAuthorize("@ss.hasPermi('business:tenant:remove')")
    @Log(title = "企业租户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(tenantService.removeBatchByIds(ids));
    }
}
