package com.tuoheng.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.dto.TenantDto;
import com.tuoheng.admin.entity.request.TenantQuery;
import com.tuoheng.admin.enums.UpdateOrCreateEnum;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.service.ITenantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuoheng.common.common.BaseQuery;
import com.tuoheng.common.common.BaseServiceImpl;
import com.tuoheng.common.config.CommonConfig;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.CommonUtils;
import com.tuoheng.common.utils.DateUtils;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.utils.StringUtils;
import com.tuoheng.system.entity.Level;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.mapper.LevelMapper;
import com.tuoheng.system.mapper.UserMapper;
import com.tuoheng.system.query.LevelQuery;
import com.tuoheng.system.utils.ShiroUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 企业管理表 服务实现类
 * </p>
 *
 * @author 拓恒
 * @since 2022-07-15
 */
@Service
public class TenantServiceImpl extends BaseServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<Tenant> getTenantList(TenantQuery tenantQuery) {
        // 查询条件
        QueryWrapper<Tenant> queryWrapper = new QueryWrapper<>();
        // 租户名称
        if (!StringUtils.isEmpty(tenantQuery.getName())) {
            queryWrapper.like("name", tenantQuery.getName());
        }
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByAsc("sort");

        // 查询分页数据
        IPage<Tenant> page = new Page<>(tenantQuery.getPage(), tenantQuery.getLimit());
        IPage<Tenant> pageData = tenantMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            // 租户Logo
            if (!StringUtils.isEmpty(x.getLogo())) {
                x.setLogo(CommonUtils.getImageURL(x.getLogo()));
            }
            return x;
        });
        return pageData;
    }

    /**
     * 添加租户
     *
     * @param tenantDto 实体对象
     * @return
     */
    @Override
    public boolean addTenant(TenantDto tenantDto) {
        // 验证是否账号已存在
        Integer count2 = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, tenantDto.getUsername())
                .eq(User::getMark, 1));
        if (count2 > 0) {
            throw new ServiceException("系统中已经存在相同的账号信息");
        }
        // 参数转换
        Tenant tenant = new Tenant();
        BeanUtils.copyProperties(tenantDto, tenant);
        // 租户头像
        if (StringUtils.isNotNull(tenantDto.getLogo()) && tenantDto.getLogo().contains(CommonConfig.imageURL)) {
            tenant.setLogo(tenantDto.getLogo().replaceAll(CommonConfig.imageURL, ""));
        }
        // 新建租户数据
        int count = tenantMapper.insert(tenant);
        if (count == 0) {
            throw new ServiceException("租户创建失败");
        }
        // 创建租户账号
        User user = new User();
        user.setTenantId(tenant.getId());
        user.setRealname(tenantDto.getName());
        user.setNickname(tenantDto.getName());
        user.setUsername(tenantDto.getUsername());
        user.setPassword(CommonUtils.password(tenantDto.getPassword()));
        user.setType(1);
        user.setIsAdmin(1);
        user.setCreateTime(DateUtils.now());
        int count3 = userMapper.insert(user);
        if (count3 == 0) {
            throw new ServiceException("租户登录账号创建失败");
        }

        return true;
    }

    /**
     * 更新
     *
     * @param tenantDto 实体对象
     * @return
     */
    @Override
    public boolean editTenant(TenantDto tenantDto) {
        // 查询租户信息
        Tenant tenant = tenantMapper.selectById(tenantDto.getId());
        if (StringUtils.isNull(tenant)) {
            throw new ServiceException("租户信息不存在");
        }
        BeanUtils.copyProperties(tenantDto, tenant);
        // 租户头像
        if (StringUtils.isNotNull(tenantDto.getLogo()) && tenantDto.getLogo().contains(CommonConfig.imageURL)) {
            tenant.setLogo(tenantDto.getLogo().replaceAll(CommonConfig.imageURL, ""));
        }
        // 更新租户信息
        int count = tenantMapper.updateById(tenant);
        if (count == 0) {
            throw new ServiceException("更新租户信息失败");
        }

        // 验证账号
        Integer count2 = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .ne(User::getTenantId, tenant.getId())
                .eq(User::getUsername, tenantDto.getUsername())
                .eq(User::getMark, 1));
        if (count2 > 0) {
            throw new ServiceException("系统中已经存在相同的账号信息");
        }

        // 查询租户账号信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getTenantId, tenant.getId()).eq(User::getMark, 1));
        if (StringUtils.isNull(user)) {
            throw new ServiceException("租户账号信息不存在");
        }
        user.setRealname(tenantDto.getName());
        user.setNickname(tenantDto.getName());
        user.setUsername(tenantDto.getUsername());
        user.setPassword(CommonUtils.password(tenantDto.getPassword()));
        user.setUpdateTime(DateUtils.now());
        int count3 = userMapper.updateById(user);
        if (count3 == 0) {
            throw new ServiceException("租户账号信息更新失败");
        }
        return true;
    }
}
