package com.hotent.portal.controller;


import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.controller.BaseController2;
import com.hotent.base.id.IdGenerator;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.CommonResultUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.portal.params.dataDict.DictEditVo;
import com.hotent.portal.params.dataDict.MoibleComBoVo;
import com.hotent.sys.constants.CategoryConstants;
import com.hotent.sys.persistence.manager.DataDictManager;
import com.hotent.sys.persistence.manager.SysTypeManager;
import com.hotent.sys.persistence.model.DataDict;
import com.hotent.sys.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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import poi.util.ExcelUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 
 * <pre> 
 * 描述：数据字典管理
 * 构建组：eip平台-bpmx-platform
 * 作者:miao
 * 邮箱:miao@jee-soft.cn
 * 日期:2014-1-10-下午3:29:34
 * 版权：广州宏天软件有限公司版权所有
 * </pre>
 */

@RestController
@RequestMapping("/sys/dataDict/v2")
@Api(tags="数据字典2")
@ApiGroup(group= {ApiGroupConsts.GROUP_PORTAL})
public class DataDictController2 extends BaseController2<DataDictManager,DataDict> {
	@Resource
	DataDictManager dataDictManager;
	@Resource
	SysTypeManager sysTypeManager;

	
	@RequestMapping(value="dataDictEdit", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "编辑数据字典信息页面", httpMethod = "GET", notes = "编辑数据字典信息页面")
	public CommonResult<DictEditVo> edit(
			@ApiParam(name="id",value="主键")@RequestParam String id,
			@ApiParam(name="isAdd",value="是否是添加")@RequestParam Integer isAdd,
			@ApiParam(name="isRoot",value="是否是根节点",required = false)@RequestParam Integer isRoot
			) throws Exception{
		Map<String, Object> map = dataDictManager.edit(id, isAdd, isRoot);
		DictEditVo dictEditVo = new DictEditVo();
		dictEditVo.setIsAdd((Integer) map.get("isAdd"));
		dictEditVo.setTypeId((String) map.get("typeId"));
		dictEditVo.setParentId((String) map.get("parentId"));
		dictEditVo.setDataDict((DataDict) map.get("dataDict"));
		return CommonResult.<DictEditVo>ok().value(dictEditVo);
	}
	
	@RequestMapping(value="getByTypeId", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "根据分类id获取字典", httpMethod = "POST", notes = "根据分类id获取字典")
	public @ResponseBody CommonResult<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);
		List<DataDict> dictList = dataDictManager.getDataDict(dictType, true);
		return CommonResult.<List<DataDict>>ok().value(dictList);
	}
	
	
	@RequestMapping(value="getByTypeKey", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "根据分类key获取字典", httpMethod = "GET", notes = "根据分类key获取字典")
	public CommonResult<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);
		List<DataDict> dictList = dataDictManager.getDataDict(dictType, false);
		return CommonResult.<List<DataDict>>ok().value(dictList);

	}
	
	@RequestMapping(value="getByTypeIdForComBo", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "根据分类id获取字典(ComBo)", httpMethod = "POST", notes = "根据分类id获取字典(ComBo)")
	public CommonResult<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= dataDictManager.getDataDict(dictType,false);
		List<DataDict> rtnList=BeanUtils.listToTree(list);
		return CommonResult.<List<DataDict>>ok().value(rtnList);

	}
	
	@RequestMapping(value="getByTypeKeyForComBo", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "通过groupKey、typeKey获取数据字典", httpMethod = "POST", notes = "通过groupKey、typeKey获取数据字典")
	public CommonResult<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= dataDictManager.getDataDict(dictType,false);
        List<DataDict> rtnList=BeanUtils.listToTree(list);
		return CommonResult.<List<DataDict>>ok().value(rtnList);
	}
	
	@RequestMapping(value="getMoibleComBoByTypeKey", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "通过typeKey获取数据字典", httpMethod = "GET", notes = "通过typeKey获取数据字典")
	public CommonResult<MoibleComBoVo>  getMoibleComBoByTypeKey(@ApiParam(name="typeKey",value="分类key",required = true)@RequestParam String typeKey) throws Exception
	{
		if(StringUtil.isEmpty(typeKey)) {
			return CommonResult.<MoibleComBoVo>ok().message("暂无数据！");
		}
		SysType dictType = sysTypeManager.getByTypeKeyAndGroupKey(CategoryConstants.CAT_DIC.key(), typeKey);
		List<DataDict> list= dataDictManager.getDataDict(dictType,false);
		List<DataDict> rtnList=BeanUtils.listToTree(list);
		MoibleComBoVo moibleComBoVo = new MoibleComBoVo();
		moibleComBoVo.setDictType(dictType);
		moibleComBoVo.setDataDictList(rtnList);
		return CommonResult.<MoibleComBoVo>ok().value(moibleComBoVo);
	}
	
	@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{
		CommonResult<String> commonResult = dataDictManager.saveDataDict(dataDict);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	@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{
		String[] aryIds=StringUtil.getStringAryByStr(id);
		dataDictManager.removeByIds(aryIds);
		return CommonResult.<String>ok().message("删除成功");
	}
	
	
	
	
	@RequestMapping(value="getDataDictByTypeId", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "根据分类数据字典", httpMethod = "GET")
	public CommonResult<List<DataDict>> getDataDictByType(@ApiParam(name="typeId", value="字典", required = true)@RequestParam String typeId) throws Exception{
		List<DataDict> dataDictList = dataDictManager.getByTypeId(typeId);
		List<DataDict> rtnList=BeanUtils.listToTree(dataDictList);
		return CommonResult.<List<DataDict>>ok().value(rtnList);
	}
	
	
	@RequestMapping(value="sortList", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "排序列表页面", httpMethod = "POST")
	public CommonResult<List<DataDict>> sortList(@ApiParam(name="id", value="字典父Id", required = false,defaultValue="-1")@RequestParam String id) throws Exception {
		List<DataDict> dataDictList = dataDictManager.getFirstChilsByParentId(id);
		return CommonResult.<List<DataDict>>ok().value(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 {
		CommonResult<String> commonResult = dataDictManager.sort(dicIds);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	@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 {
		CommonResult<String> commonResult = dataDictManager.removeByTypeIds(typeIds);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	@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 CommonResult.<String>ok().message("导入数据字典成功");
	}

	@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 = dataDictManager.getDataDict(sysType, true);
		Map<String,String> exportMap = new LinkedHashMap<>();
		exportMap.put("parentKey","父节点key");
		exportMap.put("typeKey","分类key");
		exportMap.put("typeName","分类名称");
		List<Map<String,Object>> list = new ArrayList<>();
		for (DataDict dict : dataDict) {
			if(StringUtil.isEmpty(dict.getKey())){
				continue;
			}
			HashMap<String,Object> map = new HashMap<>();
			map.put("parentKey",getKeyFromList(dict.getParentId(),dataDict));
			map.put("typeKey",dict.getKey());
			map.put("typeName",dict.getName());
			list.add(map);
		}
		HSSFWorkbook exportFile = ExcelUtil.exportExcel("数据字典", dataDict.size(), exportMap, list);
		ExcelUtil.downloadExcel(exportFile,"字典导出",response);
	}

	/*
	* 从List中根据ID获取key，获取不到则返回""
	* */
	private String getKeyFromList(String id,List<DataDict> list){
		if(StringUtil.isEmpty(id)){
			return "";
		}
		for (DataDict dataDict : list) {
			if(id.equals(dataDict.getId())){
				return dataDict.getKey();
			}
		}
		return "";
	}
}
