package cn.ezhizao.project.tenant.controller;

import cn.ezhizao.common.constant.CacheConstants;
import cn.ezhizao.common.constant.UserConstants;
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.business.resourceGroup.domain.BizProductionResourceGroupDetail;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.mapper.SysUserMapper;
import cn.ezhizao.project.system.service.ISysDeptService;
import cn.ezhizao.project.system.service.ISysUserService;
import cn.ezhizao.project.tenant.domain.BizTenant;
import cn.ezhizao.project.tenant.domain.BizTenantApply;
import cn.ezhizao.project.tenant.domain.BizUserTenant;
import cn.ezhizao.project.tenant.service.IBizTenantApplyService;
import cn.ezhizao.project.tenant.service.IBizTenantService;
import cn.ezhizao.project.tenant.service.IBizUserTenantService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * 企业租户Controller
 *
 * @author ruoyi
 * @date 2023-08-25
 */
@RestController
@RequestMapping("/business/tenant")
public class BizTenantController extends BaseController {
    @Resource
    private IBizTenantService 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;

    @Resource
    private ISysDeptService deptService;

    /**
     * 查询企业租户列表
     */
//    @PreAuthorize("@ss.hasPermi('business:tenant:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizTenant bizTenant) {
        if (StringUtils.isNotBlank(bizTenant.getOperateType())) {
            bizTenant.setUserId(SecurityUtils.getUserId());
        }
        startPage();
        List<BizTenant> list = tenantService.getList(bizTenant);
        return getDataTable(list);
    }
    @GetMapping("/info")
    public AjaxResult info() {
       QueryWrapper<BizTenant> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("deleted",0);
       List<BizTenant> oldList = tenantService.list(queryWrapper);
       List<BizTenant> newList = new ArrayList<>();
       for (BizTenant item : oldList) {
           BizTenant bizTenant = new BizTenant();
           bizTenant.setValue(item.getId());
           bizTenant.setLabel(item.getOrgName());
           newList.add(bizTenant);
       }
        return success(newList);
    }

//    @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, BizTenant bizTenant) {
        List<BizTenant> list = tenantService.getList(bizTenant);
        ExcelUtil<BizTenant> util = new ExcelUtil<BizTenant>(BizTenant.class);
        util.exportExcel(response, list, "企业租户数据");
    }

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

    /**
     * 新增企业租户
     */
//    @PreAuthorize("@ss.hasPermi('business:tenant:add')")
    @Log(title = "企业租户", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody BizTenant bizTenant) {
        SysDept dept = new SysDept();
        dept.setDeptName(bizTenant.getOrgName());
        dept.setType("1");
        dept.setParentId(0L);
        if(bizTenant.getId() == null) {
            List<BizTenant> tenantList = tenantService.query().eq("org_name", bizTenant.getOrgName()).list();
            if (tenantList.size() > 0) {
                return error("新增企业'" + dept.getDeptName() + "'失败，企业名称已存在");
            }
        }
        dept.setCreateBy(getUsername());
        deptService.insertDept(dept);
        if(bizTenant.getId() == null) {
            tenantService.save(bizTenant);
        }
        else {
//            QueryWrapper<BizTenant> queryWrapper = new QueryWrapper();
//            queryWrapper.eq("id", bizTenant.getId());
//            queryWrapper.eq("deleted", 0);
//            List<BizTenant> oldList = tenantService.list(queryWrapper);
//            boolean batch = tenantService.saveOrUpdate(tenantService, bizTenant, oldList);
            tenantService.updateById(bizTenant);

        }
        return success();
    }

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

    @Value("${token.expireTime}")
    private int expireTime;

//    @PreAuthorize("@ss.hasPermi('business:tenant:edit')")
    @Log(title = "切换租户", businessType = BusinessType.UPDATE)
    @PostMapping("/changeTenant")
    public AjaxResult change(@RequestBody BizTenant bizTenant) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUser().getUserName();
        SysUser user = userService.selectUserByUserNameAndTenantId(userName, String.valueOf(bizTenant.getId()));
        sysUserMapper.updateUser(user);
        loginUser.setTenantId(bizTenant.getId());
        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:remove')")
    @Log(title = "企业租户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(tenantService.removeBatchByIds(ids));
    }
}
