package com.bs.web.controller.system;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.domain.entity.SysDept;
import com.bs.common.core.domain.entity.SysTenant;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.SecurityUtils;
import com.bs.common.utils.poi.ExcelUtil;
import com.bs.system.domain.SysPost;
import com.bs.system.domain.SysUserRole;
import com.bs.system.mapper.SysDeptMapper;
import com.bs.system.mapper.SysPostMapper;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.mapper.SysUserRoleMapper;
import com.bs.system.service.ISysUserService;
import com.bs.system.service.SysTenantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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.stream.Collectors;

/**
 * 租户信息Controller
 *
 * @author bs
 * @date 2024-02-22
 */
@Api(tags = "租户信息")
@RestController
@RequestMapping("/system/tenant")
public class SysTenantController extends BaseController {
    @Resource
    private SysTenantService sysTenantService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysPostMapper postMapepr;

    /**
     * 分页查询租户信息列表
     */
    @ApiOperation("分页查询租户信息列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(SysTenant sysTenant) {
        startPage();
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper, sysTenant);
        List<SysTenant> list = sysTenantService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询租户信息列表
     */
    @ApiOperation("查询租户信息列表")
    @GetMapping("/list")
    public AjaxResult list(SysTenant sysTenant) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper, sysTenant);
        List<SysTenant> list = sysTenantService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出租户信息列表
     */
    @ApiOperation("导出租户信息列表")
    @Log(title = "租户信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysTenant sysTenant) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper, sysTenant);
        List<SysTenant> list = sysTenantService.list(queryWrapper);
        ExcelUtil<SysTenant> util = new ExcelUtil<SysTenant>(SysTenant.class);
        util.exportExcel(response, list, "租户信息数据");
    }

    /**
     * 获取租户信息详细信息
     */
    @ApiOperation("获取租户信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        final SysTenant sysTenant = sysTenantService.getById(id);
        SysUser sysUser = userMapper.selectTenantAdmin(sysTenant.getId());
        final List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, sysUser.getUserId()));
        final List<Long> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        sysTenant.setRoleIds(roleIds);
        return success(sysTenant);
    }

    /**
     * 新增租户信息
     */
    @ApiOperation("新增租户信息")
    @Log(title = "租户信息新增", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody SysTenant sysTenant) {
        //新增租户的时候，进行租户管理员账号的添加
        sysTenantService.save(sysTenant);
        SysUser user = new SysUser();
        user.setNickName(sysTenant.getName() + "管理员");
        user.setUserName(sysTenant.getUserName());
        user.setPassword(sysTenant.getPassword());
        user.setStatus("0");
        user.setIsTenant("Y");
        user.setIsTenantAdmin("Y");
        user.setPhonenumber(sysTenant.getContactPhone());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (Validator.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setTenantId(sysTenant.getId());

        initTenantDate(user);
        userMapper.insert(user);
        List<SysUserRole> userRoles = new ArrayList<>();
        sysTenant.getRoleIds().forEach(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(user.getUserId());
            sysUserRole.setRoleId(roleId);
            userRoles.add(sysUserRole);
        });
        sysUserRoleMapper.insertBatch(userRoles);
        return success("添加成功");
    }

    /**
     * 初始化租户的数据
     * 新建部门，复制一份基础租户的角色，配置给admin
     * 复制一份字典给租户
     */
    public void initTenantDate(SysUser user) {
        //查询 sys_dept 表，租户id为空的，复制一份
        //初始化部门
        SysDept parentsysDepts = new SysDept();
        parentsysDepts.setParentId(0L);
        parentsysDepts.setDeptName("总公司");
        parentsysDepts.setOrderNum(0);
        parentsysDepts.setAncestors("0");
        parentsysDepts.setLeader("admin");
        parentsysDepts.setPhone("15888888888");
        parentsysDepts.setEmail("zgs@qq.com");
        parentsysDepts.setTenantId(user.getTenantId());
        deptMapper.insert(parentsysDepts);
        SysDept sonSysDepts = new SysDept();
        sonSysDepts.setParentId(parentsysDepts.getDeptId());
        sonSysDepts.setDeptName("福建分公司");
        sonSysDepts.setOrderNum(1);
        //祖辈id列表
        sonSysDepts.setAncestors("0," + parentsysDepts.getDeptId());
        sonSysDepts.setLeader("admin");
        sonSysDepts.setPhone("15888888888");
        sonSysDepts.setEmail("zgs@qq.com");
        sonSysDepts.setTenantId(user.getTenantId());
        deptMapper.insert(sonSysDepts);
        //初始化岗位
        List<SysPost> sysPosts = postMapepr.selectList(new LambdaQueryWrapper<SysPost>().eq(SysPost::getDelFlag, "0").eq(SysPost::getTenantId, "0"));
        sysPosts.forEach(ele -> {
            ele.setTenantId(user.getTenantId());
            ele.setPostId(null);
        });
        postMapepr.insertBatch(sysPosts);
        //最高部门
        user.setDeptId(parentsysDepts.getDeptId());
        //ceo
        Long[] postIds = new Long[1];
        sysPosts.forEach(ele -> {
            if (ele.getPostCode().equals("ceo")) {
                postIds[0] = ele.getPostId();
            }
        });
        user.setPostIds(postIds);
    }


    /**
     * 修改租户信息
     */
    @ApiOperation("修改租户信息")
    @Log(title = "租户信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysTenant sysTenant) {
        //修改租户，判断密码是否有更换，如有更换进行修改用户密码
        SysTenant tenant = sysTenantService.getById(sysTenant.getId());
        SysUser user = userMapper.selectTenantAdmin(sysTenant.getId());
        if (!tenant.getPassword().equals(sysTenant.getPassword()) || !tenant.getUserName().equals(sysTenant.getUserName())) {

            user.setPassword(SecurityUtils.encryptPassword(sysTenant.getPassword()));
            user.setUserName(sysTenant.getUserName());
            userService.resetPwd(user);
        }
        //修改租户的角色信息
        sysUserRoleMapper.delete(new LambdaUpdateWrapper<SysUserRole>().eq(SysUserRole::getUserId, user.getUserId()));
        List<SysUserRole> userRoles = new ArrayList<>();
        sysTenant.getRoleIds().forEach(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(user.getUserId());
            sysUserRole.setRoleId(roleId);
            userRoles.add(sysUserRole);
        });
        if(userRoles.size()>0){
            sysUserRoleMapper.insertBatch(userRoles);
        }
        return toAjax(sysTenantService.updateById(sysTenant));
    }

    /**
     * 删除租户信息
     */
    @ApiOperation("删除租户信息")
    @Log(title = "租户信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(sysTenantService.removeBatchByIds(ids));
    }

    /**
     * 条件设置
     */
    private void condition(LambdaQueryWrapper<SysTenant> queryWrapper, SysTenant sysTenant) {


        //用户ID
        if (Validator.isNotEmpty(sysTenant.getId())) {
            queryWrapper.eq(SysTenant::getId, sysTenant.getId());
        }

        //租户名
        if (Validator.isNotEmpty(sysTenant.getName())) {
            queryWrapper.eq(SysTenant::getName, sysTenant.getName());
        }

        //租户简名
        if (Validator.isNotEmpty(sysTenant.getSimpleName())) {
            queryWrapper.eq(SysTenant::getSimpleName, sysTenant.getSimpleName());
        }

        //行政区划
        if (Validator.isNotEmpty(sysTenant.getAreaCode())) {
            queryWrapper.eq(SysTenant::getAreaCode, sysTenant.getAreaCode());
        }


        //租户密码
        if (Validator.isNotEmpty(sysTenant.getPassword())) {
            queryWrapper.eq(SysTenant::getPassword, sysTenant.getPassword());
        }

        //租户账号
        if (Validator.isNotEmpty(sysTenant.getUserName())) {
            queryWrapper.eq(SysTenant::getUserName, sysTenant.getUserName());
        }

        //联系人
        if (Validator.isNotEmpty(sysTenant.getContactUser())) {
            queryWrapper.eq(SysTenant::getContactUser, sysTenant.getContactUser());
        }

        //联系电话
        if (Validator.isNotEmpty(sysTenant.getContactPhone())) {
            queryWrapper.eq(SysTenant::getContactPhone, sysTenant.getContactPhone());
        }

        //状态，启用1，禁用0，即将过期2
        if (Validator.isNotEmpty(sysTenant.getStatus())) {
            queryWrapper.eq(SysTenant::getStatus, sysTenant.getStatus());
        }

        //创建部门
        if (Validator.isNotEmpty(sysTenant.getCreateDept())) {
            queryWrapper.eq(SysTenant::getCreateDept, sysTenant.getCreateDept());
        }

        //创建人
        if (Validator.isNotEmpty(sysTenant.getCreateBy())) {
            queryWrapper.eq(SysTenant::getCreateBy, sysTenant.getCreateBy());
        }

        //创建时间
        if (Validator.isNotEmpty(sysTenant.getCreateTime())) {
            queryWrapper.eq(SysTenant::getCreateTime, sysTenant.getCreateTime());
        }

        //修改人
        if (Validator.isNotEmpty(sysTenant.getUpdateBy())) {
            queryWrapper.eq(SysTenant::getUpdateBy, sysTenant.getUpdateBy());
        }

        //修改时间
        if (Validator.isNotEmpty(sysTenant.getUpdateTime())) {
            queryWrapper.eq(SysTenant::getUpdateTime, sysTenant.getUpdateTime());
        }

        //备注
        if (Validator.isNotEmpty(sysTenant.getRemark())) {
            queryWrapper.eq(SysTenant::getRemark, sysTenant.getRemark());
        }

        //删除标志（0代表存在 2代表删除）
        if (Validator.isNotEmpty(sysTenant.getDelFlag())) {
            queryWrapper.eq(SysTenant::getDelFlag, sysTenant.getDelFlag());
        }

    }

}
