package com.xy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.consts.CommConsts;
import com.xy.dto.SysRoleDto;
import com.xy.dto.SysSystemDto;
import com.xy.entity.*;
import com.xy.mapper.*;
import com.xy.redis.RedisCache;
import com.xy.service.SysSystemService;
import com.xy.utils.Emptys;
import com.xy.utils.MybatisPlusQuery;
import com.xy.utils.PageBean;
import com.xy.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

import static com.xy.utils.Beans.copy;
import static com.xy.utils.PlusBeans.toIPage;
import static com.xy.utils.PlusBeans.toPageBean;

/**
 * <p>
 * 系统表 服务实现类
 * </p>
 *
 * @author lijin
 * @since 2022-12-09
 */
@Api(tags = "系统接口")
@Service
@AllArgsConstructor
public class SysSystemServiceImpl extends ServiceImpl<SysSystemMapper, SysSystem> implements SysSystemService {

    private SysSystemValueMapper sysSystemValueMapper;

    private SysRoleMenuMapper sysRoleMenuMapper;

    private SysMenuMapper sysMenuMapper;

    private SysUserRoleMapper sysUserRoleMapper;

    private SysDeptRoleMapper sysDeptRoleMapper;

    private SysRoleMapper sysRoleMapper;

    private SysUserDeptMapper sysUserDeptMapper;

    private SysDeptRelationMapper sysDeptRelationMapper;

    private SysDeptMapper sysDeptMapper;

    private SysRoleServiceImpl sysRoleService;

    @PostMapping("obj")
    @ApiOperation("对象查询")
    public R<SysSystemDto.Vo> obj(@RequestBody SysSystemDto.Vo vo) {
        SysSystemDto.Select selectList = copy(SysSystemDto.Select.class, vo);
        List<SysSystemDto.Vo> list = listCommon(selectList).getData();
        if (Emptys.check(list)) {
            return R.ok(list.get(0));
        }
        return R.ok();
    }

    public R<List<SysSystemDto.Vo>> listCommon(@RequestBody SysSystemDto.Select select) {
        LambdaQueryWrapper<SysSystem> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(select, SysSystem.class).build().eq(SysSystem::getStatus, true);
        List<SysSystem> list = list(lambdaQueryWrapper);
        return R.ok(copy(SysSystemDto.Vo.class, list));
    }

    @PostMapping("save")
    @ApiOperation("添加系统")
    @Transactional(rollbackFor = Exception.class)
    public R<Long> save(@RequestBody @Validated SysSystemDto.Save save) {
        //校验
        long count = count(new LambdaQueryWrapper<SysSystem>().eq(SysSystem::getCode, save.getCode()));
        if (count > 0) {
            return R.fail("标识已存在");
        }
        //添加
        SysSystem sysSystem = copy(SysSystem.class, save)
                .create(RedisCache.getLoginId(Long.class));
        save(sysSystem);
        //增加管理员角色
        R<Long> r = sysRoleService.saveOrUpdate(new SysRoleDto.SaveOrUpdate()
                .setSysId(sysSystem.getId())
                .setCode(CommConsts.ADMIN_ROLE_CODE)
                .setName("超级管理员")
        );
        //赋予用户管理员
        SysUserRole sysUserRole = new SysUserRole()
                .createId()
                .setRoleId(r.getData())
                .setSysId(sysSystem.getId())
                .setWorkUserId(CommConsts.ADMIN_USER_ID);
        sysUserRoleMapper.insert(sysUserRole);
        return R.ok(sysSystem.getId());
    }

    @PostMapping("update")
    @ApiOperation("修改系统")
    public R update(@RequestBody @Validated SysSystemDto.Update update) {
        SysSystem sysSystem = copy(SysSystem.class, update).update(RedisCache.getLoginId(Long.class));
        updateById(sysSystem);
        return R.ok();
    }

    @PostMapping("list")
    @ApiOperation("登录人所属系统列表")
    public R<List<SysSystemDto.Vo>> list(@RequestBody SysSystemDto.Select select) {
        List<Long> systemIds = RedisCache.getSystemIds();
        LambdaQueryWrapper<SysSystem> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(select, SysSystem.class)
                .in(SysSystem::getId, systemIds)
                .ge(SysSystem::getCreateTime, select.getBeginCreateTime())
                .le(SysSystem::getCreateTime, select.getEndCreateTime())
                .like(SysSystem::getName)
                .build()
                .eq(SysSystem::getStatus, true);
        List<SysSystem> list = list(lambdaQueryWrapper);
        return R.ok(copy(SysSystemDto.Vo.class, list));
    }

    @PostMapping("page")
    @ApiOperation("分页查询")
    public R<PageBean<SysSystemDto.Vo>> page(@RequestBody @Validated SysSystemDto.PageSelect pageSelect) {
        LambdaQueryWrapper<SysSystem> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(pageSelect, SysSystem.class)
                .ge(SysSystem::getCreateTime, pageSelect.getBeginCreateTime())
                .le(SysSystem::getCreateTime, pageSelect.getEndCreateTime())
                .like(SysSystem::getName)
                .build();
        IPage<SysSystem> page = page(toIPage(pageSelect.getPage()), lambdaQueryWrapper);
        return R.ok(toPageBean(SysSystemDto.Vo.class, page));
    }

    @PostMapping("del")
    @ApiOperation("删除系统")
    @Transactional(rollbackFor = Exception.class)
    public R del(@RequestBody @Validated SysSystemDto.Del del) {
        //删除系统属性
        sysSystemValueMapper.delete(new LambdaQueryWrapper<SysSystemValue>().in(SysSystemValue::getSysId, del.getId()));
        //删除角色菜单
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().in(SysRoleMenu::getSysId, del.getId()));
        //删除菜单
        sysMenuMapper.delete(new LambdaQueryWrapper<SysMenu>().in(SysMenu::getSysId, del.getId()));
        //删除用户角色
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getSysId, del.getId()));
        //删除部门角色
        sysDeptRoleMapper.delete(new LambdaQueryWrapper<SysDeptRole>().in(SysDeptRole::getSysId, del.getId()));
        //删除角色
        sysRoleMapper.delete(new LambdaQueryWrapper<SysRole>().in(SysRole::getSysId, del.getId()));
        //删除用户部门
        sysUserDeptMapper.delete(new LambdaQueryWrapper<SysUserDept>().in(SysUserDept::getSysId, del.getId()));
        //删除部门关系
        sysDeptRelationMapper.delete(new LambdaQueryWrapper<SysDeptRelation>().in(SysDeptRelation::getSysId, del.getId()));
        //删除部门
        sysDeptMapper.delete(new LambdaQueryWrapper<SysDept>().in(SysDept::getSysId, del.getId()));
        //删除系统
        removeBatchByIds(del.getId());
        return R.ok();
    }
}
