package com.vctgo.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vctgo.common.core.utils.poi.ExcelUtil;
import com.vctgo.common.core.web.controller.BaseController;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.log.annotation.Log;
import com.vctgo.common.log.enums.BusinessType;
import com.vctgo.common.mybatisplus.aop.TemporaryIgnoreTables;
import com.vctgo.common.security.annotation.RequiresPermissions;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysTenant;
import com.vctgo.system.api.domain.SysUser;
import com.vctgo.system.domain.SysGardenManage;
import com.vctgo.system.mapper.SysServiceMapper;
import com.vctgo.system.service.ISysGardenManageService;
import com.vctgo.system.service.ISysTenantService;
import com.vctgo.system.service.ISysUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 租户管理Controller
 *
 * @author vctgo
 * @date 2022-04-11
 */
@RestController
@RequestMapping("/tenant")
public class SysTenantController extends BaseController {
    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private SysServiceMapper sysServiceMapper;

    @Autowired
    private ISysGardenManageService sysGardenManageService;

    @Autowired
    private ISysUserService userService;

    /**
     * 分页查询租户管理列表
     */
    @RequiresPermissions("system:tenant:page")
    @GetMapping("/page")
    public AjaxResult pageList(SysTenant sysTenant) {
        IPage<SysTenant> pageList = sysTenantService.selectSysTenantPage(sysTenant);
        return AjaxResult.success(pageList);
    }

    /**
     * 全量查询租户管理列表
     */
    @RequiresPermissions("system:tenant:list")
    @GetMapping("/allList")
    public AjaxResult allList() {
        SysTenant sysTenant = new SysTenant();
        sysTenant.setDelFlag("0");
        return AjaxResult.success(sysTenantService.selectSysTenantList(sysTenant));
    }

    /**
     * 全量查询租户管理树结构
     */
    @GetMapping("/all/tree")
    public AjaxResult allTree() {
        SysTenant sysTenant = new SysTenant();
        sysTenant.setDelFlag("0");
        return AjaxResult.success(sysTenantService.selectSysTenantTree(sysTenant));
    }

    /**
     * 只给服务间调用使用，不能用到前台的调用----全量查询租户管理列表
     */
    @GetMapping("/all/list")
    public AjaxResult allTenantList() {
        SysTenant sysTenant = new SysTenant();
        sysTenant.setDelFlag("0");
        return AjaxResult.success(sysTenantService.selectSysTenantList(sysTenant));
    }

    /**
     * 导出租户管理列表
     */
    @RequiresPermissions("system:tenant:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysTenant sysTenant) {
        List<SysTenant> list = sysTenantService.selectSysTenantList(sysTenant);
        ExcelUtil<SysTenant> util = new ExcelUtil<SysTenant>(SysTenant.class);
        util.exportExcel(response, list, "租户管理数据");
    }

    /**
     * 获取租户管理详细信息
     */
    @RequiresPermissions("system:tenant:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        SysTenant sysTenant = sysTenantService.selectSysTenantById(id);
        if (sysTenant != null && sysTenant.getTenantType() == 2 && sysTenant.getGardenId() != null) {
            SysGardenManage sysGardenManage = sysGardenManageService.selectSysGardenManageById(sysTenant.getGardenId());
            sysTenant.getParams().put("gardenName", sysGardenManage.getName());
        }

        // 通过租户id获取对应的服务列表
        sysTenant.setSysServiceList(sysServiceMapper.selectServiceListByTenantId(sysTenant.getId()));
        return AjaxResult.success(sysTenant);
    }

    /**
     * 新增租户管理
     */
    @RequiresPermissions("system:tenant:add")
    @PostMapping
    public AjaxResult add(@RequestBody SysTenant sysTenant) {
        sysTenant.setCreateById(SecurityUtils.getUserId());
        return sysTenantService.insertNewSysTenant(sysTenant);
    }

    /**
     * 修改租户管理
     */
    @RequiresPermissions("system:tenant:edit")
    @PutMapping
    public AjaxResult edit(@RequestBody SysTenant sysTenant) {
        sysTenant.setUpdateById(SecurityUtils.getUserId());
        return toAjax(sysTenantService.updateSysTenant(sysTenant));
    }

    /**
     * 新增权限管理
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/config/permission")
    public AjaxResult addConfigPermission(@RequestBody SysTenant sysTenant) {
        return toAjax(sysTenantService.addConfigPermission(sysTenant));
    }

    /**
     * 修改权限管理
     */
    @RequiresPermissions("system:tenant_permission:edit")
    @GlobalTransactional
    @PutMapping("/config/permission")
    public AjaxResult editConfigPermission(@RequestBody SysTenant sysTenant) {
        return toAjax(sysTenantService.editConfigPermission(sysTenant));
    }

    /**
     * 重置密码
     */
    @TemporaryIgnoreTables
    @RequiresPermissions("system:tenant:resetPwd")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysTenant sysTenant) {
        //根据租户id和租户账号查询用户信息
        SysUser user = userService.selectUserByUserAccount(sysTenant.getId(), sysTenant.getUserName());
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if(SecurityUtils.getTenantId() == 9999L){
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_user"));
        }
        //默认密码采用随机生成
        String randomPassword = SecurityUtils.randomPassword(6);//随机密码6位
        String newPassword = SecurityUtils.encryptPassword(randomPassword);
        user.setPassword(newPassword);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user), randomPassword);
    }

    /**
     * 删除租户管理
     */
    @RequiresPermissions("system:tenant:remove")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysTenantService.deleteSysTenantByIds(ids));
    }

    /**
     * 获取指定租户的父级租户信息
     */
    @GetMapping("/{tenantId}/parent/info")
    public AjaxResult getParentTenantInfo(@PathVariable Long tenantId) {
        return AjaxResult.success(sysTenantService.getParentTenantInfo(tenantId));
    }


    /**
     * 条件查询租户管理列表
     */
    @GetMapping("/toyService/bi")
    public AjaxResult getTenantList(@RequestParam("sysTenant") String sysTenant) {
        SysTenant tenant = JSONObject.parseObject(sysTenant, SysTenant.class);
        List<SysTenant> tenantList = sysTenantService.selectTenantList(tenant);
        return AjaxResult.success(tenantList);
    }
}
