package com.lightinit.hsdataplatformresdir.impl.admin;

import com.lightinit.hsdataplatformresdir.dictionary.DicResourceCatelogType;
import com.lightinit.hsdataplatformresdir.entity.ResourceCatelog;
import com.lightinit.hsdataplatformresdir.entity.ResourceCatelogExample;
import com.lightinit.hsdataplatformresdir.mapper.ResourceCatelogMapper;
import com.lightinit.hsdataplatformresdir.model.ResultState;
import com.lightinit.hsdataplatformresdir.model.ResultStateCode;
import com.lightinit.hsdataplatformresdir.model.admin.ResourceCatelogDataModel;
import com.lightinit.hsdataplatformresdir.model.admin.TreeModel;
import com.lightinit.hsdataplatformresdir.service.admin.IResourceCatelogMgrService;
import com.lightinit.hsdataplatformresdir.service.admin.TreeDataBuilder;
import com.lightinit.hsdataplatformresdir.spring.DynamicDataContextHolder;
import org.apache.commons.lang.StringUtils;
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;

/**
 * @author WangYao
 * @date 2018/6/3 10:04
 * @description 目录管理业务实现
 */
@Service
public class ResourceCatelogMgrServiceImpl implements IResourceCatelogMgrService {

    @Autowired
    private ResourceCatelogMapper resourceCatelogMapper;

    public List<TreeModel> queryTreeData(String resourceCatelogType) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        final List<ResourceCatelog> dataList = getAllResourceCatelog(resourceCatelogType);
        Function<ResourceCatelog,TreeModel> mapFunction = (q) -> {
            TreeModel treeModel =  new TreeModel(q.getId().toString(), null, q.getCatelogName(), 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;
    }

    public List<ResourceCatelog> getAllResourceCatelog(String resourceCatelogType){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceCatelogExample example = new ResourceCatelogExample();
        if (StringUtils.isNotEmpty(resourceCatelogType)){
            ResourceCatelogExample.Criteria criteria1 = example.createCriteria();
            criteria1.andCatelogTypeEqualTo(resourceCatelogType);
        }
        return resourceCatelogMapper.selectByExample(example);
    }

    @Transactional
    public ResultState<ResourceCatelog> addOrEdit(ResourceCatelogDataModel inputModel){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<ResourceCatelog> resultState = new ResultState<>();
        if (!DicResourceCatelogType.getInstacne().getDicMap().containsKey(inputModel.getCatelogType())){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("无效的目录类别");
            return resultState;
        }
        if (isCatelogCodeExisting(inputModel.getCatelogCode(), inputModel.getId())){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("目录编码已存在");
            return resultState;
        }

        ResourceCatelog entity1 = new ResourceCatelog();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setIsOpen(inputModel.getIsOpen() != null && inputModel.getIsOpen() ? (byte)1 : (byte)0);
        entity1.setIsShare(inputModel.getIsShare() != null && inputModel.getIsShare() ? (byte)1 : (byte)0);
        entity1.setIsDataCatelog(inputModel.getIsDataCatelog() != null && inputModel.getIsDataCatelog() ? (byte)1 : (byte)0);
        entity1.setIsApiCatelog(inputModel.getIsApiCatelog() != null && inputModel.getIsApiCatelog() ? (byte)1 : (byte)0);
        entity1.setIsMicroappCatelog(inputModel.getIsMicroappCatelog() != null && inputModel.getIsMicroappCatelog() ? (byte)1 : (byte)0);
        int sqlResult1;
        if (inputModel.getId() == null){
            Date createdAt = new Date();
            entity1.setCreatedAt(createdAt);
            sqlResult1 = resourceCatelogMapper.insert(entity1);
        }else {
            ResourceCatelogExample example1 = new ResourceCatelogExample();
            ResourceCatelogExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andIdEqualTo(inputModel.getId());
            sqlResult1 = resourceCatelogMapper.updateByExampleSelective(entity1, example1);
        }

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

    /**
     * @param catelogCode 目录编码
     * @param id 目录ID（排除的ID）
     * @return 目录编码是否存在
     */
    private boolean isCatelogCodeExisting(String catelogCode, Long id){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceCatelogExample example1 = new ResourceCatelogExample();
        ResourceCatelogExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andCatelogCodeEqualTo(catelogCode);
        if (id != null && id > 0){
            criteria1.andIdNotEqualTo(id);
        }
        List<ResourceCatelog> list = resourceCatelogMapper.selectByExample(example1);
        return list != null && list.size() > 0;
    }

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

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


        ResourceCatelogExample example1 = new ResourceCatelogExample();
        ResourceCatelogExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(id);
        int sqlResult1 = resourceCatelogMapper.deleteByExample(example1);

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