package com.artfess.portal.controller;

import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.constants.CacheKeyConst;
import com.artfess.base.context.BaseContext;
import com.artfess.base.controller.BaseController;
import com.artfess.base.id.IdGenerator;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.i18n.persistence.model.I18nMessageError;
import com.artfess.poi.util.ExcelUtil;
import com.artfess.redis.util.RedisUtil;
import com.artfess.sysConfig.constants.CategoryConstants;
import com.artfess.sysConfig.persistence.manager.DataDictManager;
import com.artfess.sysConfig.persistence.manager.SysTypeManager;
import com.artfess.sysConfig.persistence.model.DataDict;
import com.artfess.sysConfig.persistence.model.SysType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 * 描述：数据字典管理
 * 构建组：x5-bpmx-platform
 * 作者:miao
 * 邮箱:miao@jee-soft.cn
 * 日期:2014-1-10-下午3:29:34
 * 版权：广州宏天软件有限公司版权所有
 * </pre>
 */

@RestController
@RequestMapping("/sys/dataDict/v1")
@Api(tags = "数据字典")
@ApiGroup(group = {ApiGroupConsts.GROUP_SYSTEM})
public class DataDictController extends BaseController<DataDictManager, DataDict> {
    @Resource
    DataDictManager dataDictManager;
    @Resource
    SysTypeManager sysTypeManager;
    @Resource
    IdGenerator idGenerator;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    BaseContext baseContext;

    @RequestMapping(value = "listJson", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "字典列表", httpMethod = "POST", notes = "字典列表")
    @ResponseBody
    public PageList<DataDict> listJson(@ApiParam(name = "queryFilter", value = "通用查询对象") @RequestBody QueryFilter<DataDict> queryFilter) throws Exception {
        return dataDictManager.query(queryFilter);
    }

    @RequestMapping(value = "dataDictEdit", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "编辑数据字典信息页面", httpMethod = "GET", notes = "编辑数据字典信息页面")
    public Map<String, Object> edit(
            @ApiParam(name = "id", value = "主键") @RequestParam String id,
            @ApiParam(name = "isAdd", value = "是否是添加") @RequestParam int isAdd,
            @ApiParam(name = "isRoot", value = "是否是根节点", required = false) @RequestParam int isRoot
    ) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("isAdd", isAdd);
        DataDict dataDict = null;
        // 根节点的id = typeId
        if (isRoot == 1 && isAdd == 1) {
            map.put("typeId", id);
            map.put("parentId", id);
            return map;
        }//普通节点添加
        else if (isAdd == 1 && StringUtil.isNotEmpty(id)) {
            map.put("parentId", id);
            dataDict = dataDictManager.get(id);
            map.put("typeId", dataDict.getTypeId());
            return map;
        }// 编辑情况
        else if (StringUtil.isNotEmpty(id)) {
            dataDict = dataDictManager.get(id);
            map.put("dataDict", dataDict);
            return map;
        }
        return map;
    }

    @RequestMapping(value = "getByTypeId", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据分类id获取字典", httpMethod = "POST", notes = "根据分类id获取字典")
    public @ResponseBody
    List<DataDict> getByTypeId(@ApiParam(name = "typeId", value = "分类id", required = true) @RequestBody String typeId) throws Exception {
        if (StringUtil.isEmpty(typeId)) return null;
        SysType dictType = sysTypeManager.get(typeId);
        return getDataDict(dictType, true);
    }

    @RequestMapping(value = "getDicByDicId", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据字典项id获取字典信息", httpMethod = "POST", notes = "根据字典项id获取字典信息")
    public @ResponseBody
    List<DataDict> getDicByDicId(@ApiParam(name = "dicId", value = "字典项id", required = true) @RequestBody String dicId) throws Exception {
        if (StringUtil.isEmpty(dicId)) return null;
        List<DataDict> list = this.dataDictManager.getDicByDicId(dicId,true);
        List<DataDict> rtnList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            rtnList = BeanUtils.listToTree(list);
        }
        return rtnList;
    }

    @RequestMapping(value = "getByDicKey", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据字典项key获取字典", httpMethod = "GET", notes = "根据字典项key获取字典")
    public List<DataDict> getByDicKey(@ApiParam(name = "dicKey", value = "字典项key", required = true) @RequestParam String dicKey) throws Exception {
        if (StringUtil.isEmpty(dicKey)) return null;
        List<DataDict> list = this.dataDictManager.getByDicKey(dicKey);
        List<DataDict> rtnList = BeanUtils.listToTree(list);
        return rtnList;
    }

    @RequestMapping(value = "moveDic", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "移动字典项", httpMethod = "POST", notes = "移动字典项")
    public CommonResult<String> moveDic(@ApiParam(name = "ids", value = "字典项id集合", required = true) @RequestParam List<String> ids,
                                        @ApiParam(name = "gId", value = "目标ID", required = true) @RequestParam String gId,
                                        @ApiParam(name = "type", value = "移动的类型（dic：项，val：值）", required = true) @RequestParam String type) throws Exception {
        if (StringUtil.isEmpty(gId))  return new CommonResult<String>(false, "请选择移动的目标！");
        if (StringUtil.isEmpty(type))  return new CommonResult<String>(false, "请选择移动的字典类型！");
        Boolean flag = this.dataDictManager.moveDic(ids,gId,type);
        if(flag){
            return new CommonResult<String>(true, "移动字典项成功！");
        }else{
            return new CommonResult<String>(false, "移动字典项失败！");
        }

    }

    @RequestMapping(value = "getByTypeKey", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据分类key获取字典", httpMethod = "GET", notes = "根据分类key获取字典")
    public List<DataDict> getByTypeKey(@ApiParam(name = "typeKey", value = "分类id", required = true) @RequestParam String typeKey) throws Exception {
        if (StringUtil.isEmpty(typeKey)) return null;
        SysType dictType = sysTypeManager.getByKey(typeKey);
        return getDataDict(dictType, false);
    }

    @RequestMapping(value = "getByTypeIdForComBo", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据分类id获取字典(ComBo)", httpMethod = "POST", notes = "根据分类id获取字典(ComBo)")
    public List<DataDict> getByTypeIdForComBo(@ApiParam(name = "typeId", value = "分类id", required = true) @RequestBody String typeId) throws Exception {
        if (StringUtil.isEmpty(typeId)) return null;
        SysType dictType = sysTypeManager.get(typeId);
        List<DataDict> list = getDataDict(dictType, false);
        List<DataDict> rtnList = BeanUtils.listToTree(list);
        return rtnList;
    }

    @RequestMapping(value = "getByTypeKeyForComBo", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "通过groupKey、typeKey获取数据字典", httpMethod = "POST", notes = "通过groupKey、typeKey获取数据字典")
    public List<DataDict> getByTypeKeyForComBo(@ApiParam(name = "typeKey", value = "分类key", required = true) @RequestParam String typeKey) throws Exception {
        if (StringUtil.isEmpty(typeKey)) return null;
        SysType dictType = sysTypeManager.getByTypeKeyAndGroupKey(CategoryConstants.CAT_DIC.key(), typeKey);
        List<DataDict> list = getDataDict(dictType, false);
        List<DataDict> rtnList = BeanUtils.listToTree(list);
        return rtnList;
        //todo 修复4465 BUG 注释下面代码
        //if(StringUtil.isEmpty(typeKey)) return null;
        //SysType dictType = sysTypeManager.getByTypeKeyAndGroupKey(CategoryConstants.CAT_DIC.key(), typeKey);
        //if(BeanUtils.isEmpty(dictType))return null;
        //String typeId = dictType.getId();
        //List<DataDict> dataDictList=dataDictManager.getByTypeId(typeId);
        //boolean isChildren=dictType.getStruType()==0;
        //List<DataDict> list = new ArrayList<>();
        //for(DataDict entity : dataDictList){
        //	DataDict dataDicts = new DataDict();
        //	if(isChildren && !entity.getParentId().equals(typeId)){
        //		continue;
        //	}
        //	dataDicts = entity;
        //	dataDicts.setOpen("true");
        //	List<DataDict> listDataDict = dataDictManager.getFirstChilsByParentId(dataDicts.getId());
        //	if(listDataDict!=null && listDataDict.size()==0){
        //		dataDicts.setIsParent("false");
        //	}
        //	list.add(dataDicts);
        //}
        //List<DataDict> rtnList=BeanUtils.listToTree(list);
        //return rtnList;
    }

    @RequestMapping(value = "getMoibleComBoByTypeKey", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "通过typeKey获取数据字典", httpMethod = "GET", notes = "通过typeKey获取数据字典")
    public Map<String, Object> getMoibleComBoByTypeKey(@ApiParam(name = "typeKey", value = "分类key", required = true) @RequestParam String typeKey) throws Exception {
        if (StringUtil.isEmpty(typeKey)) return null;
        SysType dictType = sysTypeManager.getByTypeKeyAndGroupKey(CategoryConstants.CAT_DIC.key(), typeKey);
        List<DataDict> list = getDataDict(dictType, false);
        List<DataDict> rtnList = BeanUtils.listToTree(list);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataDictList", rtnList);
        map.put("dictType", dictType);
        return map;
    }

    @RequestMapping(value = "getAllDicTree", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取所有多维数据字典树", httpMethod = "POST", notes = "获取所有多维数据字典树")
    public  Map<String,  List<DataDict> >  getAllDicTree() throws Exception {
        List<DataDict> list = this.baseService.getAllDataVal();
        List<DataDict> rtnList = BeanUtils.listToTree(list);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        Map<String,  List<DataDict> > map = rtnList.stream().collect(Collectors.groupingBy(DataDict::getDicKey));
        return map;
    }

    @RequestMapping(value = "getAllDicVal", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取所有多维数据字典(平铺)", httpMethod = "POST", notes = "获取所有多维数据字典(平铺)")
    public  Map<String,  List<DataDict> >  getAllDicVal() throws Exception {
        List<DataDict> list = this.baseService.getAllDataVal();
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        Map<String, List<DataDict>> map = list.stream().filter(p->p!=null && StringUtil.isNotEmpty(p.getDicKey())).collect(Collectors.groupingBy(DataDict::getDicKey));
        return map;
    }

    /**
     * 根据数据字典分类获取数据字典值
     *
     * @param dictType
     * @param tileNeedRoot 平铺结构的数据字典是否需要返回根节点（在管理数据字典值得时候需要返回，在使用数据字典的时候不需要返回）
     * @return
     */
    private List<DataDict> getDataDict(SysType dictType, Boolean tileNeedRoot) {
        if (BeanUtils.isEmpty(dictType)){
            return null;
        }
        String typeId = dictType.getId();
        List<DataDict>  dataDictList = dataDictManager.getByTypeId(typeId);
        List<DataDict> list = new ArrayList<>();
        for (DataDict entity : dataDictList) {
            DataDict dataDicts = new DataDict();
            dataDicts = entity;
            dataDicts.setOpen("true");
            List<DataDict> listDataDict = dataDictManager.getFirstChilsByParentId(dataDicts.getId());
            if (listDataDict != null && listDataDict.size() == 0) {
                dataDicts.setIsParent("false");
            }
            list.add(dataDicts);
        }
        //树形结构，将根节点添加到数据项中
        if (tileNeedRoot) {
            //根节点
            DataDict dict = new DataDict();
            dict.setId(dictType.getId());
            dict.setName(dictType.getName());
            dict.setTypeId(typeId);
            dict.setParentId("-1");
            dict.setKey("");
            dict.setOpen("true");
            list.add(dict);
        }
        return list;
    }

    @RequestMapping(value = "dataDictGet", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "数据字典明细页面", httpMethod = "POST", notes = "数据字典明细页面")
    public DataDict get(@ApiParam(name = "id", value = "主键", required = true) @RequestBody String id) throws Exception {
        DataDict dataDict = new DataDict();
        if (StringUtil.isNotEmpty(id)) {
            dataDict = dataDictManager.get(id);
        }
        return dataDict;
    }

    @RequestMapping(value = "saveAndUpdate", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存数据字典信息", httpMethod = "POST", notes = "保存数据字典信息")
    public CommonResult<String> saveAndUpdate(@ApiParam(name = "dataDict", value = "字典", required = true) @RequestBody DataDict dataDict) throws Exception {
        String id = dataDict.getId();
        try {
            if (StringUtil.isEmpty(id)) {
                // 验证字典key 是否已经存在
                String dicType = dataDict.getType();
                if(StringUtil.isEmpty(dicType)){
                    return new CommonResult<String>(false, "请确定字典类型！");
                }
                DataDict dict = null;
                if(dicType.equals("dic")){
                    dict = dataDictManager.getByKey("dic", dataDict.getKey(),"");
                    if (dict != null) {
                        return new CommonResult<String>(false, "该字典项已经存在");
                    }
                }else if(dicType.equals("val")){
                    if(StringUtil.isEmpty(dataDict.getDicId())){
                        return new CommonResult<String>(false, "请选择字典项！");
                    }
                    dict = dataDictManager.getByKey("val", dataDict.getKey(),dataDict.getDicId());
                    if (dict != null) {
                        return new CommonResult<String>(false, "该字典值已经存在");
                    }
                }
                if(dataDict.getSn()==null){
                    Map<String,Object> param =new HashMap<>();
                    param.put("parent_id_",dataDict.getParentId());
                    Integer sn = this.baseService.getNextSequence(param);
                    dataDict.setSn(sn);
                }

                // 如果是root节点添加。typeId = parentId
                dataDict.setId(idGenerator.getSuid());
                if(dicType.equals("dic")){
                    dataDict.setDicId(dataDict.getId());
                }
                if(dicType.equals("val") && dict.getDicId().equals(dict.getParentId())){
                    dataDict.setFullId("/"+dataDict.getId());
                    dataDict.setFullCode("/"+dataDict.getKey());
                    dataDict.setFullName("/"+dataDict.getName());
                }else if(dicType.equals("val") && !dict.getDicId().equals(dict.getParentId())){
                    DataDict parentDict = this.baseService.get(dict.getParentId());
                    dataDict.setFullId(parentDict.getFullId()+"/"+dataDict.getId());
                    dataDict.setFullCode(parentDict.getFullCode()+"/"+dataDict.getKey());
                    dataDict.setFullName(parentDict.getFullName()+"/"+dataDict.getName());
                }
                dataDictManager.create(dataDict);
            } else {
                // 如果改变了key ，验证改字典key 中是否已经存在
                if (!dataDictManager.get(id).getKey().equals(dataDict.getKey())) {
                    DataDict dict = dataDictManager.getByDictKey(dataDict.getTypeId(), dataDict.getKey());
                    if (dict != null) {
                        return new CommonResult<String>(false, "该字典项值已经存在");
                    }
                }
                String dicType = dataDict.getType();
                if(dicType.equals("val")){
                    DataDict parentDict = this.baseService.get(dataDict.getParentId());
                    if(parentDict.getType().equals("dic")){
                        dataDict.setFullId("/"+dataDict.getId());
                        dataDict.setFullCode("/"+dataDict.getKey());
                        dataDict.setFullName("/"+dataDict.getName());
                    }else if(parentDict.getType().equals("val")){
                        dataDict.setFullId(parentDict.getFullId()+"/"+dataDict.getId());
                        dataDict.setFullCode(parentDict.getFullCode()+"/"+dataDict.getKey());
                        dataDict.setFullName(parentDict.getFullName()+"/"+dataDict.getName());
                    }

                }
                dataDictManager.update(dataDict);
            }
            String tenantId = baseContext.getCurrentTenantId();
            redisUtil.del(CacheKeyConst.SYS_DIMENSION_DICT + ":" + tenantId);
            return new CommonResult<String>(true, "保存成功");
        } catch (Exception e) {
            return new CommonResult<String>(true, "保存失败");
        }
    }

    @RequestMapping(value = "saveAndUpdateValBatch", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存数据字典信息", httpMethod = "POST", notes = "保存数据字典信息")
    public CommonResult<String> saveAndUpdateValBatch(@ApiParam(name = "dataDict", value = "字典", required = true) @RequestBody List<DataDict> dataDicts) throws Exception {

        try {
            if(!CollectionUtils.isEmpty(dataDicts)){
                for(DataDict dataDict :dataDicts){
                    String id = dataDict.getId();
                    if (StringUtil.isEmpty(id)) {
                        // 验证字典key 是否已经存在
                        String dicType = dataDict.getType();
                        if(StringUtil.isEmpty(dicType)){
                            return new CommonResult<String>(false, "请确定字典类型！");
                        }
                        DataDict dict = null;
                        if(dicType.equals("dic")){
                            dict = dataDictManager.getByKey("dic", dataDict.getKey(),"");
                            if (dict != null) {
                                return new CommonResult<String>(false, "【"+dataDict.getKey()+"】该字典项已经存在");
                            }
                        }else if(dicType.equals("val")){
                            if(StringUtil.isEmpty(dataDict.getDicId())){
                                return new CommonResult<String>(false, "请选择字典项！");
                            }
                            dict = dataDictManager.getByKey("val", dataDict.getKey(),dataDict.getDicId());
                            if (dict != null) {
                                return new CommonResult<String>(false, "【"+dataDict.getKey()+"】该字典值已经存在");
                            }
                        }
                        if(dataDict.getSn()==null){
                            Map<String,Object> param =new HashMap<>();
                            param.put("parent_id_",dataDict.getParentId());
                            Integer sn = this.baseService.getNextSequence(param);
                            dataDict.setSn(sn);
                        }
                        // 如果是root节点添加。typeId = parentId
                        dataDict.setId(idGenerator.getSuid());
                        if(dicType.equals("val") && dict.getDicId().equals(dict.getParentId())){
                            dict.setFullId("/"+dataDict.getId());
                            dict.setFullCode("/"+dataDict.getKey());
                            dict.setFullName("/"+dataDict.getName());
                        }else if(dicType.equals("val") && !dict.getDicId().equals(dict.getParentId())){
                            DataDict parentDict = this.baseService.get(dict.getParentId());
                            dict.setFullId(parentDict.getFullId()+"/"+dataDict.getId());
                            dict.setFullCode(parentDict.getFullCode()+"/"+dataDict.getKey());
                            dict.setFullName(parentDict.getFullName()+"/"+dataDict.getName());
                        }

                        if(dicType.equals("dic")){
                            dataDict.setDicId(dataDict.getId());
                        }
                    } else {
                        // 如果改变了key ，验证改字典key 中是否已经存在
                        if (!dataDictManager.get(id).getKey().equals(dataDict.getKey())) {
                            DataDict dict = dataDictManager.getByDictKey(dataDict.getTypeId(), dataDict.getKey());
                            if (dict != null) {
                                return new CommonResult<String>(false, "该字典项值已经存在");
                            }
                            String dicType = dataDict.getType();
                            if(dicType.equals("val")){
                                DataDict parentDict = this.baseService.get(dict.getParentId());
                                if(parentDict.getType().equals("dic")){
                                    dict.setFullId("/"+dataDict.getId());
                                    dict.setFullCode("/"+dataDict.getKey());
                                    dict.setFullName("/"+dataDict.getName());
                                }else if(parentDict.getType().equals("val")){
                                    dict.setFullId(parentDict.getFullId()+"/"+dataDict.getId());
                                    dict.setFullCode(parentDict.getFullCode()+"/"+dataDict.getKey());
                                    dict.setFullName(parentDict.getFullName()+"/"+dataDict.getName());
                                }

                            }

                        }
                    }

                }
                dataDictManager.saveOrUpdateBatch(dataDicts);
                String tenantId = baseContext.getCurrentTenantId();
                redisUtil.del(CacheKeyConst.SYS_DIMENSION_DICT + ":" + tenantId);
                return new CommonResult<String>(true, "保存成功");
            }
            return new CommonResult<String>(false, "请添加字典值");
        } catch (Exception e) {
            return new CommonResult<String>(true, "保存失败");
        }
    }

    @RequestMapping(value = "save", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存数据字典信息", httpMethod = "POST", notes = "保存数据字典信息")
    public CommonResult<String> save(@ApiParam(name = "dataDict", value = "字典", required = true) @RequestBody DataDict dataDict) throws Exception {
        String id = dataDict.getId();
        try {
            if (StringUtil.isEmpty(id)) {
                // 验证字典key 是否已经存在
                DataDict dict = dataDictManager.getByDictKey(dataDict.getTypeId(), dataDict.getKey());
                if (dict != null) {
                    return new CommonResult<String>(false, "该字典项值已经存在");
                }
                // 如果是root节点添加。typeId = parentId
                dataDict.setId(idGenerator.getSuid());
                dataDictManager.create(dataDict);
            } else {
                // 如果改变了key ，验证改字典key 中是否已经存在
                if (!dataDictManager.get(id).getKey().equals(dataDict.getKey())) {
                    DataDict dict = dataDictManager.getByDictKey(dataDict.getTypeId(), dataDict.getKey());
                    if (dict != null) {
                        return new CommonResult<String>(false, "该字典项值已经存在");
                    }
                }
                dataDictManager.update(dataDict);
            }
            String tenantId = baseContext.getCurrentTenantId();
            redisUtil.del(CacheKeyConst.SYS_DIMENSION_DICT + ":" + tenantId);
            return new CommonResult<String>(true, "保存成功");
        } catch (Exception e) {
            return new CommonResult<String>(true, "保存失败");
        }
    }

    @RequestMapping(value = "remove", method = RequestMethod.DELETE, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "批量删除数据字典", httpMethod = "DELETE", notes = "删除数据字典")
    public CommonResult<String> remove(@ApiParam(name = "id", value = "字典", required = true) @RequestParam String id) throws Exception {
        try {
            String[] aryIds = StringUtil.getStringAryByStr(id);
            dataDictManager.removeByIds(aryIds);
            String tenantId = baseContext.getCurrentTenantId();
            redisUtil.del(CacheKeyConst.SYS_DIMENSION_DICT + ":" + tenantId);
            return new CommonResult<String>(true, "删除成功");
        } catch (Exception e) {
            return new CommonResult<String>(true, "删除失败");
        }
    }

    @RequestMapping(value = "getDataDictByTypeId", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据分类数据字典", httpMethod = "GET")
    public List<DataDict> getDataDictByType(@ApiParam(name = "typeId", value = "字典", required = true) @RequestBody String typeId) throws Exception {
        List<DataDict> dataDictList = dataDictManager.getByTypeId(typeId);
        List<DataDict> rtnList = BeanUtils.listToTree(dataDictList);
        return rtnList;
    }

    @RequestMapping(value = "sortList", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "排序列表页面", httpMethod = "POST")
    public List<DataDict> sortList(@ApiParam(name = "id", value = "字典", required = false, defaultValue = "-1") @RequestBody String id) throws Exception {
        List<DataDict> dataDictList = dataDictManager.getFirstChilsByParentId(id);
        return dataDictList;
    }

    @RequestMapping(value = "sort", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "排序", httpMethod = "POST")
    public CommonResult<String> sort(@ApiParam(name = "dicIds", value = "字典", required = true) @RequestBody String[] dicIds) throws Exception {
        try {
            if (BeanUtils.isNotEmpty(dicIds)) {
                for (int i = 0; i < dicIds.length; i++) {
                    String dicId = dicIds[i];
                    int sn = i + 1;
                    dataDictManager.updSn(dicId, sn);
                }
            }
        } catch (Exception e) {
            return new CommonResult<String>(true, "排序失败");
        }
        return new CommonResult<String>(true, "排序成功");
    }

    @RequestMapping(value = "removeByTypeId", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据分类id删除分类下的字典", httpMethod = "GET")
    public CommonResult<String> removeByTypeIds(@ApiParam(name = "typeIds", value = "分类id", required = true) @RequestParam String typeIds) throws Exception {
        return dataDictManager.removeByTypeIds(typeIds);
    }

    @RequestMapping(value = "importDic", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "数据字典项导入", httpMethod = "POST", notes = "数据字典项导入")
    public CommonResult<String> importDic(@ApiParam(name = "file", value = "上传的文件流") @RequestBody MultipartFile file) throws Exception {
        dataDictManager.importDic(file);
        return new CommonResult<String>(true, "导入多维字典项成功");
    }

    @RequestMapping(value = "import", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "数据字典导入", httpMethod = "POST", notes = "数据字典导入")
    public CommonResult<String> importData(@ApiParam(name = "files", value = "上传的文件流") @RequestBody List<MultipartFile> file, @ApiParam(name = "typeId", value = "数据字典分类id", required = true) @RequestParam String typeId) throws Exception {
        dataDictManager.importData(file, typeId);
        return new CommonResult<String>(true, "导入数据字典成功");
    }

    @RequestMapping(value = "export", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "数据字典导出", httpMethod = "GET", notes = "数据字典导出")
    public void export(@ApiParam(name = "typeId", value = "类型ID") @RequestParam String typeId, HttpServletResponse response) throws Exception {
        SysType sysType = sysTypeManager.get(typeId);
        List<DataDict> dataDict = getDataDict(sysType, false);
        Map<String, String> exportMap = new LinkedHashMap<>();
        exportMap.put("typeKey", "分类key");
        exportMap.put("typeName", "分类名称");
        exportMap.put("parentKey", "父级字典代码");
        exportMap.put("parentName", "父级字典值");
        exportMap.put("type", "字典类型");
        exportMap.put("key", "字典代码");
        exportMap.put("name", "字典值");
        List<Map<String, Object>> list = new ArrayList<>();
        for (DataDict dict : dataDict) {
            if (StringUtil.isEmpty(dict.getKey())) {
                continue;
            }
            DataDict parentDict = getKeyFromList(dict.getParentId(), dataDict);
            HashMap<String, Object> map = new HashMap<>();
            map.put("typeKey",sysType.getTypeKey());
            map.put("typeName", sysType.getName());
            if(parentDict!=null){
                map.put("parentKey", parentDict.getKey());
                map.put("parentName", parentDict.getName());
            }else{
                map.put("parentKey", sysType.getTypeKey());
                map.put("parentName", sysType.getName());
            }
            if(dict.getType().equals("dic")){
                map.put("type", "字典项");
            }else if(dict.getType().equals("val")){
                map.put("type", "字典值");
            }else{
                map.put("type", dict.getType());
            }
            map.put("key",  dict.getKey());
            map.put("name", dict.getName());
            list.add(map);
        }
        HSSFWorkbook exportFile = ExcelUtil.exportExcel("数据字典", dataDict.size(), exportMap, list);
        ExcelUtil.downloadExcel(exportFile, "字典导出", response);
    }

    /*
     * 从List中根据ID获取key，获取不到则返回""
     * */
    private DataDict getKeyFromList(String id, List<DataDict> list) {
        if (StringUtil.isEmpty(id)) {
            return null;
        }
        for (DataDict dataDict : list) {
            if (id.equals(dataDict.getId())) {
                return dataDict;
            }
        }
        return null;
    }
}
