package com.lightinit.hsdataplatform.impl.admin;

import com.lightinit.hsdataplatform.entity.Tag;
import com.lightinit.hsdataplatform.entity.TagExample;
import com.lightinit.hsdataplatform.entity.TagWithBLOBs;
import com.lightinit.hsdataplatform.mapper.TagMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.MainNameAndValue;
import com.lightinit.hsdataplatform.model.admin.TagEditModel;
import com.lightinit.hsdataplatform.model.admin.TreeModel;
import com.lightinit.hsdataplatform.service.admin.ITagSerice;
import com.lightinit.hsdataplatform.service.admin.TreeDataBuilder;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Function;

import static java.util.stream.Collectors.toList;

@Service
public class TagSericeImpl implements ITagSerice {

    @Autowired
    private TagMapper tagMapper ;

    @Override
    public List<TreeModel> tagTreeData(Long selectedId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);

        final List<TagWithBLOBs> dataList = tagMapper.getAllTags();

        Function<Tag,TreeModel> mapFunction = (q) -> {
            TreeModel treeModel =  new TreeModel(q.getId().toString(), null, q.getCategoryName(), null);
            return treeModel;
        };
        List<TreeModel> treeModelList = dataList.stream().filter(q -> q.getParentId() == null).map(mapFunction).collect(toList());
        TreeDataBuilder.buildTreeModelRecursively(treeModelList, dataList, (pCurrentTreeModel, pDataList) -> pDataList.stream()
                .filter(q -> q.getParentId() != null && q.getParentId().toString().equals(pCurrentTreeModel.getId()))
                .map(mapFunction)
                .collect(toList()), (pCurrentTreeModel, pChildTreeModelList) -> {
            List<String> tags = new ArrayList<>();
            tags.add(String.valueOf(pChildTreeModelList.size()));
            pCurrentTreeModel.setTags(tags);
        });
        return treeModelList;
    }

    @Override
    public List<TagWithBLOBs> getAllTag() {
        return tagMapper.getAllTags();
    }

    @Override
    public ResultState<TagWithBLOBs> addOrEdit(TagEditModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<TagWithBLOBs> resultState = new ResultState<>();
//        if (!DicResourceCatelogType.getInstacne().getDicMap().containsKey(inputModel.getCategoryImg())){
//            resultState.setStateCode(ResultStateCode.INVALID_DATA);
//            resultState.setMsg("无效的目录类别");
//            return resultState;
//        }

        TagWithBLOBs entity1 = new TagWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity1);
        int sqlResult1;
        if (inputModel.getId() == null){
            Date createdAt = new Date();
            entity1.setCreatedAt(createdAt);
            sqlResult1 = tagMapper.insert(entity1);
        }else {
            TagExample example1 = new TagExample();
            TagExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andIdEqualTo(inputModel.getId());
            sqlResult1 = tagMapper.updateByExampleSelective(entity1, example1);
        }

        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg(inputModel.getId() == null ? "数据插入失败" : "数据更新失败");
            return resultState;
        }
        resultState.setData(tagMapper.selectByPrimaryKey(entity1.getId()));
        return resultState;
    }

    @Override
    public List<MainNameAndValue> getMains() {
        return tagMapper.getMains() ;
    }

    @Transactional
    public ResultState<Long> delete(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        TagExample childExample = new TagExample();
        TagExample.Criteria childCriteria1 = childExample.createCriteria();
        childCriteria1.andParentIdEqualTo(id);
        long count = tagMapper.countByExample(childExample);
        if (count > 0){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("该节点存在子节点，请先删除子节点");
            return resultState;
        }


        TagExample example1 = new TagExample();
        TagExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(id);
        int sqlResult1 = tagMapper.deleteByExample(example1);

        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据不存在");
        }
        resultState.setData(id);
        return resultState;
    }

}

