package com.lightinit.hsdataplatformresdir.impl.admin;

import com.lightinit.hsdataplatformresdir.entity.Dictionary;
import com.lightinit.hsdataplatformresdir.entity.DictionaryExample;
import com.lightinit.hsdataplatformresdir.entity.DictionaryGroup;
import com.lightinit.hsdataplatformresdir.entity.DictionaryGroupExample;
import com.lightinit.hsdataplatformresdir.mapper.DictionaryGroupMapper;
import com.lightinit.hsdataplatformresdir.mapper.DictionaryMapper;
import com.lightinit.hsdataplatformresdir.model.ResultState;
import com.lightinit.hsdataplatformresdir.model.ResultStateCode;
import com.lightinit.hsdataplatformresdir.model.admin.DictionaryDataModel;
import com.lightinit.hsdataplatformresdir.model.admin.TreeModel;
import com.lightinit.hsdataplatformresdir.service.admin.IDictionaryMgrService;
import com.lightinit.hsdataplatformresdir.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;

/**
 * @author WangYao
 * @date 2018/6/6 09:05
 * @description 字典管理业务实现
 */
@Service
public class DictionaryMgrServiceImpl implements IDictionaryMgrService {

    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private DictionaryGroupMapper dictionaryGroupMapper;

    public List<TreeModel> queryTreeData() {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);


        DictionaryGroupExample dictionaryGroupExample = new DictionaryGroupExample();
        final List<DictionaryGroup> groupList = dictionaryGroupMapper.selectByExample(dictionaryGroupExample);
        DictionaryExample dictionaryExample = new DictionaryExample();
        final List<Dictionary> dicList = dictionaryMapper.selectByExample(dictionaryExample);

        Function<Dictionary,TreeModel> mapFunction = (q) -> {
            TreeModel treeModel =  new TreeModel(q.getId().toString(), null, q.getDicName(), null);
            return treeModel;
        };
        List<TreeModel> treeModelList = groupList.stream().map(q -> new TreeModel(q.getId().toString(), null, q.getGroupName(), null)).collect(toList());
        for (TreeModel currentTreeModel : treeModelList){
            List<TreeModel> childTreeModelList = dicList.stream()
                    .filter(q -> q.getGroupId() != null && q.getGroupId().toString().equals(currentTreeModel.getId()))
                    .map(mapFunction)
                    .collect(toList());
            currentTreeModel.setNodes(childTreeModelList);
            List<String> tags = new ArrayList<>();
            tags.add(String.valueOf(childTreeModelList.size()));
            currentTreeModel.setTags(tags);
        }
        return treeModelList;
    }

    @Transactional
    public ResultState<Long> addOrEdit(DictionaryDataModel inputModel){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState;

        if (inputModel.getGroupId() == null){
            resultState = addOrEditDicGroup(inputModel);
        }else {
            resultState = addOrEditDic(inputModel);
        }

        return resultState;
    }

    @Transactional
    public ResultState<Long> addOrEditDicGroup(DictionaryDataModel inputModel){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        int sqlResult1;
        DictionaryGroup entity1 = new DictionaryGroup();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setGroupName(inputModel.getDicName());
        if (inputModel.getId() == null){
            Date createdAt = new Date();
            entity1.setCreatedAt(createdAt);
            sqlResult1 = dictionaryGroupMapper.insert(entity1);
        }else {
            DictionaryGroupExample example1 = new DictionaryGroupExample();
            DictionaryGroupExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andIdEqualTo(inputModel.getId());
            sqlResult1 = dictionaryGroupMapper.updateByExampleSelective(entity1, example1);
        }

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

    @Transactional
    public ResultState<Long> addOrEditDic(DictionaryDataModel inputModel){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        int sqlResult1;
        Dictionary entity1 = new Dictionary();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setDicValue(entity1.getDicName());
        if (inputModel.getId() == null){
            Date createdAt = new Date();
            entity1.setCreatedAt(createdAt);
            sqlResult1 = dictionaryMapper.insert(entity1);
        }else {
            DictionaryExample example1 = new DictionaryExample();
            DictionaryExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andIdEqualTo(inputModel.getId());
            sqlResult1 = dictionaryMapper.updateByExampleSelective(entity1, example1);
        }

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

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

        DictionaryGroupExample childExample1 = new DictionaryGroupExample();
        DictionaryGroupExample.Criteria childCriteria1 = childExample1.createCriteria();
        childCriteria1.andParentIdEqualTo(id);
        long count1 = dictionaryGroupMapper.countByExample(childExample1);

        DictionaryExample childExample2 = new DictionaryExample();
        DictionaryExample.Criteria childCriteria2 = childExample2.createCriteria();
        childCriteria2.andGroupIdEqualTo(id);
        long count2 = dictionaryMapper.countByExample(childExample2);

        if (count1 > 0 || count2 > 0){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("该节点存在子节点，请先删除子节点");
            return resultState;
        }


        DictionaryGroupExample example1 = new DictionaryGroupExample();
        DictionaryGroupExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(id);
        int sqlResult1 = dictionaryGroupMapper.deleteByExample(example1);

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

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

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


        DictionaryExample example1 = new DictionaryExample();
        DictionaryExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(id);
        int sqlResult1 = dictionaryMapper.deleteByExample(example1);

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