package cn.iocoder.yudao.module.system.service.dictTenant;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.system.api.dicttenant.dto.DictDataTenantRespDTO;
import cn.iocoder.yudao.module.system.controller.admin.dictTenant.vo.type.DictTypeTenantPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.dictTenant.vo.type.DictTypeTenantSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictTypeDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dictTenant.DictDataTenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dictTenant.DictTypeTenantDO;
import cn.iocoder.yudao.module.system.dal.mysql.dictTenant.DictTypeTenantMapper;
import cn.iocoder.yudao.module.system.enums.dicttenant.DictTypeTenantEnum;
import com.google.common.annotations.VisibleForTesting;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 租户字典类型 Service 实现类
 *
 * @author 芋道源码
 */
@Service
public class DictTypeTenantServiceImpl implements DictTypeTenantService {

    @Resource
    private DictTypeTenantMapper dictTypeTenantMapper;
    @Resource
    private DictDataTenantService dictDataTenantService;

    @Override
    public Long createDictType(DictTypeTenantSaveReqVO createReqVO) {
        // 校验字典类型的名字的唯一性
        validateDictTypeNameUnique(null, createReqVO.getName());
        // 校验字典类型的类型的唯一性
        validateDictTypeUnique(null, createReqVO.getType());

        // 插入字典类型
        DictTypeTenantDO dictType = BeanUtils.toBean(createReqVO, DictTypeTenantDO.class);
        dictType.setDeletedTime(LocalDateTimeUtils.EMPTY); // 唯一索引，避免 null 值
        dictTypeTenantMapper.insert(dictType);
        return dictType.getId();
    }

    @Override
    public void updateDictType(DictTypeTenantSaveReqVO updateReqVO) {
        // 校验自己存在
        validateDictTypeExists(updateReqVO.getId());
        // 校验字典类型的名字的唯一性
        validateDictTypeNameUnique(updateReqVO.getId(), updateReqVO.getName());
        // 校验字典类型的类型的唯一性
        validateDictTypeUnique(updateReqVO.getId(), updateReqVO.getType());
        // 更新
        DictTypeTenantDO updateObj = BeanUtils.toBean(updateReqVO, DictTypeTenantDO.class);
        dictTypeTenantMapper.updateById(updateObj);
    }

    @Override
    public void deleteDictType(Long id) {
        // 校验是否存在
        DictTypeTenantDO dictType = validateDictTypeExists(id);
        // 校验是否有字典数据
        if (dictDataTenantService.getDictDataCountByDictType(dictType.getType()) > 0) {
            throw exception(DICT_TYPE_HAS_CHILDREN);
        }
        // 删除
        dictTypeTenantMapper.deleteById(id);
    }


    @Override
    public DictTypeTenantDO getDictType(Long id) {
        return dictTypeTenantMapper.selectById(id);
    }

    @Override
    public DictTypeTenantDO getDictType(String type) {
        return dictTypeTenantMapper.selectByType(type);
    }

    @Override
    public PageResult<DictTypeTenantDO> getDictTypePage(DictTypeTenantPageReqVO pageReqVO) {
        return dictTypeTenantMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DictTypeTenantDO> getDictTypeList() {
        return dictTypeTenantMapper.selectList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> initDictTypeAndDataForTenant(String dictType) {

        Map<String, String> result = new HashMap<>();

        // 所有租户字典类型枚举
        List<DictTypeTenantEnum> dictTypeTenantEnumList = Stream.of(DictTypeTenantEnum.values()).collect(Collectors.toList());
        // 所有租户字典类型值
        List<String> dictTypeList = dictTypeTenantEnumList.stream().map(DictTypeTenantEnum::getType).collect(Collectors.toList());

        if (StrUtil.isNotBlank(dictType)) {
            if (dictTypeList.contains(dictType)) {
                // 查询当前租户有没有添加该类型
                DictTypeTenantDO dictTypeTenantDO = dictTypeTenantMapper.selectByType(dictType);
                if (dictTypeTenantDO == null) {
                    // 添加类型和数据
                    DictTypeTenantDO build = DictTypeTenantDO.builder()
                            .type(dictType)
                            .name(DictTypeTenantEnum.getLabel(dictType))
                            .build();
                    dictTypeTenantMapper.insert(build);

                    List<DictDataTenantRespDTO> dictData = DictTypeTenantEnum.getDictData(dictType);
                    dictData.forEach(item -> item.setDataType(1));
                    List<DictDataTenantDO> dictDataTenantDOList = BeanUtils.toBean(dictData, DictDataTenantDO.class);
                    dictDataTenantService.insertBatch(dictDataTenantDOList);
                    result.put(dictType + ":" + TenantContextHolder.getTenantId(), "添加成功");
                } else {
                    result.put(dictType + ":" + TenantContextHolder.getTenantId(), "已存在");
                }
            } else {
                result.put(dictType + ":" + TenantContextHolder.getTenantId(), "不是预定义的类型");
            }
        } else {
            for (DictTypeTenantEnum dictTypeTenantEnum : dictTypeTenantEnumList) {
                dictType = dictTypeTenantEnum.getType();
                // 查询当前租户有没有添加该类型
                DictTypeTenantDO dictTypeTenantDO = dictTypeTenantMapper.selectByType(dictType);
                if (dictTypeTenantDO == null) {
                    // 添加类型和数据
                    DictTypeTenantDO build = DictTypeTenantDO.builder()
                            .type(dictType)
                            .name(DictTypeTenantEnum.getLabel(dictType))
                            .build();
                    dictTypeTenantMapper.insert(build);

                    List<DictDataTenantRespDTO> dictData = DictTypeTenantEnum.getDictData(dictType);
                    dictData.forEach(item -> item.setDataType(1));
                    List<DictDataTenantDO> dictDataTenantDOList = BeanUtils.toBean(dictData, DictDataTenantDO.class);
                    dictDataTenantService.insertBatch(dictDataTenantDOList);

                    result.put(dictTypeTenantEnum.getType() + ":" + TenantContextHolder.getTenantId(), "添加成功");
                } else {
                    result.put(dictTypeTenantEnum.getType() + ":" + TenantContextHolder.getTenantId(), "已存在");
                }
            }
        }

        return result;
    }


    @VisibleForTesting
    void validateDictTypeNameUnique(Long id, String name) {
        DictTypeTenantDO dictType = dictTypeTenantMapper.selectByName(name);
        if (dictType == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的字典类型
        if (id == null) {
            throw exception(DICT_TYPE_NAME_DUPLICATE);
        }
        if (!dictType.getId().equals(id)) {
            throw exception(DICT_TYPE_NAME_DUPLICATE);
        }
    }

    @VisibleForTesting
    void validateDictTypeUnique(Long id, String type) {
        if (StrUtil.isEmpty(type)) {
            return;
        }
        DictTypeTenantDO dictType = dictTypeTenantMapper.selectByType(type);
        if (dictType == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的字典类型
        if (id == null) {
            throw exception(DICT_TYPE_TYPE_DUPLICATE);
        }
        if (!dictType.getId().equals(id)) {
            throw exception(DICT_TYPE_TYPE_DUPLICATE);
        }
    }

    @VisibleForTesting
    DictTypeTenantDO validateDictTypeExists(Long id) {
        if (id == null) {
            return null;
        }
        DictTypeTenantDO dictType = dictTypeTenantMapper.selectById(id);
        if (dictType == null) {
            throw exception(DICT_TYPE_NOT_EXISTS);
        }
        return dictType;
    }
}