package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsk.common.constant.TenantPackageConstants;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.utils.StringUtils;
import com.dsk.system.domain.SysTenant;
import com.dsk.system.domain.SysTenantPackage;
import com.dsk.system.domain.bo.SysTenantPackageBo;
import com.dsk.system.domain.vo.SysTenantPackageSelectVo;
import com.dsk.system.domain.vo.SysTenantPackageVo;
import com.dsk.system.mapper.SysTenantMapper;
import com.dsk.system.mapper.SysTenantPackageMapper;
import com.dsk.system.service.ISysTenantPackageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author sxk
 * @date 2023.08.24
 */
@RequiredArgsConstructor
@Service
public class ISysTenantPackageServiceImpl implements ISysTenantPackageService {

    private final SysTenantPackageMapper baseMapper;
    private final SysTenantMapper tenantMapper;

    /**
     * 根据方案名称查询方案
     *
     * @param packageName 方案名称
     * @return 方案
     */
    @Override
    public SysTenantPackage selectTenantPackageByName(String packageName) {
        return baseMapper.selectOne(new LambdaQueryWrapper<SysTenantPackage>()
                .eq(SysTenantPackage::getPackageName, packageName));
    }

    /**
     * 查询租户套餐列表
     */
    @Override
    public TableDataInfo<SysTenantPackageVo> queryPageList(SysTenantPackageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysTenantPackage> lqw = buildQueryWrapper(bo);
        pageQuery.setIsAsc("desc");
        pageQuery.setOrderByColumn("createTime");
        Page<SysTenantPackageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询租户套餐已启用列表
     */
    @Override
    public List<SysTenantPackageSelectVo> selectList() {
        LambdaQueryWrapper<SysTenantPackage> wrapper = new LambdaQueryWrapper<SysTenantPackage>()
                .eq(SysTenantPackage::getStatus, TenantPackageConstants.NORMAL)
                .orderByDesc(SysTenantPackage::getCreateTime);
        List<SysTenantPackageVo> tenantPackageVo = baseMapper.selectVoList(wrapper);
        return BeanUtil.copyToList(tenantPackageVo, SysTenantPackageSelectVo.class);
    }

//    /**
//     * 查询租户套餐列表
//     */
//    @Override
//    public List<SysTenantPackageVo> queryList(SysTenantPackageBo bo) {
//        LambdaQueryWrapper<SysTenantPackage> lqw = buildQueryWrapper(bo);
//        return baseMapper.selectVoList(lqw);
//    }

    /**
     * 查询租户套餐
     */
    @Override
    public SysTenantPackageVo queryById(Long packageId) {
        return baseMapper.selectVoById(packageId);
    }

    private LambdaQueryWrapper<SysTenantPackage> buildQueryWrapper(SysTenantPackageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysTenantPackage> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getPackageName()), SysTenantPackage::getPackageName, bo.getPackageName());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysTenantPackage::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增租户套餐
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysTenantPackageBo bo) {
        SysTenantPackage add = BeanUtil.toBean(bo, SysTenantPackage.class);
        // 保存菜单id
        List<Long> menuIds = Arrays.asList(bo.getMenuIds());
        if (CollUtil.isNotEmpty(menuIds)) {
            add.setMenuIds(StringUtils.join(menuIds, ","));
        } else {
            add.setMenuIds("");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPackageId(add.getPackageId());
        }
        return flag;
    }

    /**
     * 修改租户套餐
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(SysTenantPackageBo bo) {
        SysTenantPackage update = BeanUtil.toBean(bo, SysTenantPackage.class);
        List<Long> packageIds = new ArrayList<>();
        packageIds.add(bo.getPackageId());
        //校验该套餐是否正在被使用
        if (TenantPackageConstants.DISABLE.equals(bo.getStatus())) {
            checkPackageIsUsed(packageIds);
        }
        // 保存菜单id
        List<Long> menuIds = Arrays.asList(bo.getMenuIds());
        if (CollUtil.isNotEmpty(menuIds)) {
            update.setMenuIds(StringUtils.join(menuIds, ", "));
        } else {
            update.setMenuIds("");
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 校验套餐是否正在被租户使用
     *
     * @param ids 套餐ID数组
     */
    private void checkPackageIsUsed(List<Long> ids) {
        boolean exists = tenantMapper.exists(new LambdaQueryWrapper<SysTenant>().in(SysTenant::getPackageId, ids));
        if (exists) {
            throw new ServiceException("企业方案已被使用");
        }
    }

//    /**
//     * 修改套餐状态
//     */
//    @Override
//    public int updatePackageStatus(SysTenantPackageBo bo) {
//        SysTenantPackage tenantPackage = BeanUtil.toBean(bo, SysTenantPackage.class);
//        return baseMapper.updateById(tenantPackage);
//    }

    /**
     * 批量删除租户套餐
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(List<Long> ids, boolean isValid) {
        if (isValid) {
            checkPackageIsUsed(ids);
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 校验方案名称是否唯一
     *
     * @param bo 方案信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysTenantPackageBo bo) {
        return baseMapper.exists(new LambdaQueryWrapper<SysTenantPackage>()
                .eq(SysTenantPackage::getPackageName, bo.getPackageName()));
    }
}
