package com.artfess.sysConfig.persistence.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.artfess.base.exception.BaseException;
import com.artfess.base.id.IdGenerator;
import com.artfess.base.util.*;
import com.artfess.base.util.time.DateUtil;
import com.artfess.sysConfig.persistence.manager.SysTypeManager;
import com.artfess.sysConfig.persistence.model.SysTag;
import com.artfess.sysConfig.persistence.model.SysType;
import org.springframework.stereotype.Service;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.sysConfig.persistence.dao.SysTagDao;
import com.artfess.sysConfig.persistence.manager.SysTagManager;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 
 * <pre> 
 * 描述：portal_sys_tag 处理实现类
 * 构建组：x7
 * 作者:heyf
 * 邮箱:heyf@jee-soft.cn
 * 日期:2020-07-27 11:08:18
 * 版权：广州宏天软件股份有限公司
 * </pre>
 */
@Service("sysTagManager")
public class SysTagManagerImpl extends BaseManagerImpl<SysTagDao, SysTag> implements SysTagManager{

    @Resource
    SysTypeManager sysTypeManager;

    @Resource
    IdGenerator idGenerator;

    @Override
    @Transactional
    public void removeByTypeId(String typeId) {
        if (StringUtil.isNotEmpty(typeId)) {
            List<SysType> sysTypes = sysTypeManager.getChildByTypeId(typeId);
            List<String> ids = sysTypes.stream().map(item -> item.getId()).collect(Collectors.toList());
            ids.add(typeId);
            sysTypeManager.removeByIds(ids);
            ids.forEach(id -> {
                QueryWrapper<SysTag> wrapper = new QueryWrapper<>();
                wrapper.eq("type_id_",id);
                baseMapper.delete(wrapper);
            });
        }
    }

    @Override
    public List<SysTag> getTagsByTypeId(String typeId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("type_id_",typeId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public Integer countByName(String key,String typeId) {
        QueryWrapper<SysTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name_",key).eq("type_id_",typeId);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer countByKey(String sysTagKey, String typeId) {
        QueryWrapper<SysTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("key_",sysTagKey).eq("type_id_",typeId);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public void createWithCheck(SysTag sysTag) throws Exception{
        SysType sysType = sysTypeManager.getByTypeKeyAndGroupKey("TAG",sysTag.getTypeKey());
        if (BeanUtils.isEmpty(sysType))
            throw new RuntimeException("["+sysTag.getTypeKey()+"]不存在");
        if (countByName(sysTag.getName(),sysType.getId())>0){
            throw new RuntimeException("["+sysTag.getName()+"]已存在");
        }
        if(countByKey(sysTag.getKey(),sysType.getId()) > 0){
            throw new RuntimeException("标签key：["+sysTag.getKey()+"]已存在");
        }
        sysTag.setTypeId(sysType.getId());
        if (StringUtil.isEmpty(sysTag.getKey())){
            sysTag.setKey(PinyinUtil.getPinyinToLowerCase(sysTag.getName())+ DateUtil.getCurrentTimeInMillis());
        }
        create(sysTag);
    }

    @Override
    @Transactional
    public void importFile(String unZipFilePath,String typeId) {
        List<SysTag> primitive = this.getTagsByTypeId(typeId);
        try{
            String json = FileUtil.readFile(unZipFilePath + File.separator + "sysTags.json");
            List list = JsonUtil.toBean(json, List.class);
            List<SysTag> newTags = new ArrayList<>();
            for (Object o : list) {
                SysTag sysTag = JsonUtil.toBean(JsonUtil.toJson(o), SysTag.class);
                //重新设置typeId
                sysTag.setTypeId(typeId);
                //重新生成ID
                sysTag.setId(idGenerator.getSuid());
                sysTag.setTenantId(null);
                newTags.add(sysTag);
            }
            if(BeanUtils.isEmpty(primitive)){
                for (SysTag newTag : newTags) {
                    this.create(newTag);
                }
            }else{
                for (SysTag newTag : newTags) {
                    if(isSysTagExists(newTag,primitive)){
                        continue;
                    }
                    this.create(newTag);
                }
            }
        }catch (Exception e){
            throw new BaseException(e.getMessage());
        }
    }

    //判断系统标签在不在新分类里
    private boolean isSysTagExists(SysTag sysTag,List<SysTag> list){
        for (SysTag tag : list) {
            if(sysTag.getName().equals(tag.getName())){
                return true;
            }
        }
        return false;
    }
}
