package cn.ezhizao.project.tenant.controller;

import cn.ezhizao.common.constant.CacheConstants;
import cn.ezhizao.common.constant.HttpStatus;
import cn.ezhizao.common.constant.UserConstants;
import cn.ezhizao.common.exception.ServiceException;
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.SysDept;
import cn.ezhizao.project.system.domain.SysRole;
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.ISysRoleService;
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.domain.vo.InitTenantVo;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 企业租户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 ISysRoleService roleService;


    @Resource
    private IBizTenantApplyService tenantApplyService;
    @Resource
    private ISysDeptService deptService;

    @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')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(tenantService.removeBatchByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('business:tenant:edit')")
    @Log(title = "企业租户初始化检测", businessType = BusinessType.UPDATE)
    @GetMapping("/checkTenantInit")
    public AjaxResult checkTenantInit(@RequestParam Long tenantId) {
        // 判断是否已有管理员角色
        boolean checkAdminRole = tenantService.checkAdminRole(tenantId);
        // 判断是否已有管理员
        boolean checkAdmin = tenantService.checkAdmin(tenantId);
        // 获取初始化管理员信息
        SysUser admin = tenantService.getAdminUser(tenantId);
        // 判断是否已有初始化角色
        // 获取初始化角色信息
        List<SysRole> roles = tenantService.getInitRoles(tenantId);
        SysRole adminRole = roles.stream().filter(v -> v.getEditDisable().equals("1")).findFirst().orElse(null);
        // 判断管理员权限是否与版本一致
        boolean checkAdminMenu = adminRole != null && tenantService.checkAdminMenu(tenantId, adminRole.getId());
        // 判断是否已初始化来源类型
        boolean checkSource = tenantService.checkInitSource(tenantId);
        // 判断是否已初始化部门
        boolean checkDept = tenantService.checkInitDept(tenantId);
        SysDept dept = tenantService.getInitDept(tenantId);
        Tenant tenant = tenantService.getById(tenantId);
        Map<String, Object> map = new HashMap<>();
        map.put("checkAdminRole", checkAdminRole);
        map.put("checkAdmin", checkAdmin);
        map.put("adminRole", adminRole);
        map.put("initRole", roles);
        map.put("admin", admin);
        map.put("checkDept", checkDept);
        map.put("checkInitRole", roles.size() > 0);
        map.put("checkAdminMenu", checkAdminMenu);
        map.put("checkSource", checkSource);
        map.put("initRoleData", tenantService.initRolesData());
        map.put("tenant", tenant);
        map.put("initDept", dept);
        return success(map);
    }

    @PreAuthorize("@ss.hasPermi('business:tenant:edit')")
    @Log(title = "企业租户初始化", businessType = BusinessType.UPDATE)
    @PostMapping("/initTenant")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult initTenant(@RequestBody List<InitTenantVo> initFlows) {
        SysRole adminRole = new SysRole();
        SysUser adminUser = new SysUser();
        boolean initStatus = true;
        for (InitTenantVo l : initFlows) {
            switch (l.getFlowName()) {
                case "auditingTenant":
                    initStatus = auditingTenant(l);
                    break;
                // 创建管理员 角色
                case "initAdminRole":
                    initStatus = initStatus && initAdminRole(l);
                    adminRole = l.getAdminRole();
                    break;
                // 创建管理员 用户
                case "initAdminSysUser":
                    initStatus = initStatus && initAdminSysUser(l);
                    adminRole = l.getAdminRole() != null && l.getAdminRole().getRoleId() != null ? l.getAdminRole() : adminRole;
                    adminUser = l.getAdmin();
                    break;
                // 创建管理员角色关联
                case "initAdminAuth":
                    SysRole finalAdminRole = adminRole;
                    initStatus = initStatus && (roleService.selectRoleListByUserId(adminUser.getUserId()).stream().anyMatch(v -> finalAdminRole.getRoleId().equals(v)) || roleService.insertAuthUsers(adminRole.getRoleId(), new Long[]{adminUser.getUserId()}) > 0);
                    break;
                // 初始化来源
                case "initDept":
                    initStatus = initStatus && initDept(l);
                    break;
                case "initSource":
                    initStatus = initStatus && initSource(l);
                    break;
                // 初始化角色
                case "initRoles":
                    initStatus = initStatus && initRoles(l);
                default:
                    break;
            }
        }
        return initStatus ? AjaxResult.success() : AjaxResult.error();
    }

    private boolean auditingTenant(InitTenantVo initFlow) {
        Tenant tenant = tenantService.getById(initFlow.getTenantId());
        tenant.setStatus(2);
        return tenantService.updateById(tenant);
    }

    private boolean initAdminRole(InitTenantVo initFlow) {
        SysRole sysRole = initFlow.getAdminRole();
        sysRole.setEditDisable("1");
        sysRole.setIsInit("1");
        sysRole.setTenantId(initFlow.getTenantId());
        List<Long> menuIds = tenantService.getTenantMenuIds(initFlow.getTenantId());
        sysRole.setMenuIds(menuIds.toArray(new Long[0]));
        return (sysRole.getRoleId() != null && sysRole.getRoleId().equals(0L)) ? roleService.updateRole(sysRole) > 0 :
                roleService.insertRole(sysRole) > 0;
    }

    private boolean initSource(InitTenantVo initFlow) {
        return tenantService.initSource(initFlow.getTenantId());
    }

    private boolean initDept(InitTenantVo initFlow) {
        SysDept sysDept = initFlow.getDept();
        sysDept.setTenantId(initFlow.getTenantId());
        sysDept.setParentId(100L);
        return (sysDept.getDeptId() != null && !sysDept.getDeptId().equals(0L)) ? deptService.updateDept(sysDept) > 0 : deptService.insertDept(sysDept) > 0;
    }

    private boolean initRoles(InitTenantVo initFlow) {
        List<SysRole> sysRoles = initFlow.getInitRoles();
        List<SysRole> existsRoles = roleService.selectRolesByTenantId(initFlow.getTenantId());
        // 判断角色是否存在
        List<SysRole> insertRoles = sysRoles.stream().filter(v -> existsRoles.stream().noneMatch(t -> v.getInitId().equals(t.getInitId()))).collect(Collectors.toList());
        List<SysRole> updateRoles = sysRoles.stream().filter(v -> existsRoles.stream().anyMatch(t -> t.getInitId().equals(v.getInitId()))).collect(Collectors.toList());
        // 不存在则新增角色
        AtomicInteger insertRole = new AtomicInteger();
        insertRoles.forEach(v -> insertRole.addAndGet(roleService.insertRole(v)));
        // 存在则更新角色
        AtomicInteger updateRole = new AtomicInteger();
        updateRoles.forEach(v -> updateRole.addAndGet(roleService.updateRole(v)));
        return sysRoles.isEmpty() || insertRole.getAndAdd(updateRole.get()) > 0;
    }

    private boolean initAdminSysUser(InitTenantVo initFlow) {
        // 判断人员账号是否重复
        SysUser user = initFlow.getAdmin();
//        SysUser checkUser = sysUserMapper.selectUserByPhoneNumber(sysUser.getUserName());
//        if (checkUser != null && !sysUser.getUserId().equals(checkUser.getUserId())) {
//            throw new ServiceException("管理员账号重复，请重新输入", HttpStatus.ERROR);
//        }
//        sysUser.setTenantId(initFlow.getTenantId());
//        sysUser.setPassword(sysUser.getPassword().isEmpty() ? SecurityUtils.encryptPassword("123456") : sysUser.getPassword());
        BizUserTenant userTenant = new BizUserTenant();
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            throw new ServiceException("新增用户'" + user.getUserName() + "'失败，登录账号已存在", HttpStatus.ERROR);
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            throw new ServiceException("新增用户'" + user.getUserName() + "'失败，手机号码已存在", HttpStatus.ERROR);
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            throw new ServiceException("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在", HttpStatus.ERROR);
        }
        user.setCreateBy(getUsername());
        user.setPassword(user.getPassword().isEmpty() ? SecurityUtils.encryptPassword("123456") : user.getPassword());
        if (StringUtils.isNotEmpty(initFlow.getTenantId().toString())) {
            user.setUserType("02");
        }
        int rows = (user.getUserId() != null && !user.getUserId().equals(0L)) ? userService.updateUser(user) :userService.insertUser(user);
        boolean bool = false;
        userTenant.setUserId(user.getUserId());
        userTenant.setDeptId(user.getDeptId() != null ? user.getDeptId() : 0L);
        userTenant.setTenantId(initFlow.getTenantId());
        bool = userTenantService.save(userTenant);
        return bool && rows > 0;
//        return () ? sysUserMapper.updateUser(sysUser) > 0 : sysUserMapper.insertUser(sysUser) > 0;
    }
}
