package com.zcloud.service.system.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.mapper.datasource.system.DictionariesMapper;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.util.Tools;
import com.zcloud.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 说明：按钮权限服务接口实现类
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
@Service
@Transactional //开启事物
public class DictionariesServiceImpl implements DictionariesService {

	@Autowired
	private DictionariesMapper dictionariesMapper;

	/**
	 * 获取所有数据并填充每条数据的子级列表(递归处理)
	 * @param MENU_ID
	 * @return
	 * @throws Exception
	 */
	public List<Dictionaries> listAllDict(String parentId) throws Exception {
		List<Dictionaries> dictList = this.listSubDictByParentId(parentId);
		for(Dictionaries dict : dictList){
			dict.setTreeurl("dictionaries_list.html?DICTIONARIES_ID="+dict.getDICTIONARIES_ID());
			dict.setSubDict(this.listAllDict(dict.getDICTIONARIES_ID()));
			dict.setTarget("treeFrame");
		}
		return dictList;
	}

	/**
	 * 通过ID获取其子级列表
	 * @param parentId
	 * @return
	 * @throws Exception
	 */
	public List<Dictionaries> listSubDictByParentId(String parentId) throws Exception {
//		System.out.println(dictionariesMapper.listSubDictByParentId(parentId));
		return dictionariesMapper.listSubDictByParentId(parentId);
	}

	@Override
	public List<PageData> getTreeById(String id) throws Exception {
		List<Dictionaries> _list = this.listSubDictByParentId(id); //用传过来的ID获取此ID下的子列表数据
		return _list.stream().map(n -> {
			PageData entity = new PageData();
			entity.put("DICTIONARIES_ID", n.getDICTIONARIES_ID());
			entity.put("BIANMA", n.getBIANMA());
			entity.put("NAME", n.getNAME());
			return entity;
		}).collect(Collectors.toList());
	}



	/**
	 * 通过ID获取其子级列表
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<Dictionaries> listSubDictByParent(PageData pd) throws Exception {
		return dictionariesMapper.listSubDictByParent(pd);
	}

	/**
	 * 通过ID获取其子级列表
	 * @param parentId
	 * @return
	 * @throws Exception
	 */
	public List<Dictionaries> listSubDictByParentIdAndCourseware(PageData pd) throws Exception {
		return dictionariesMapper.listSubDictByParentIdAndCourseware(pd);
	}

	/**
	 * 获取所有数据并填充每条数据的子级列表(递归处理)用于代码生成器引用数据字典
	 * @param MENU_ID
	 * @return
	 * @throws Exception
	 */
	public List<Dictionaries> listAllDictToCreateCode(String parentId) throws Exception {
		List<Dictionaries> dictList = this.listSubDictByParentId(parentId);
		for(Dictionaries dict : dictList){
			dict.setTreeurl("setDID('"+dict.getDICTIONARIES_ID()+"');");
			dict.setSubDict(this.listAllDictToCreateCode(dict.getDICTIONARIES_ID()));
			dict.setTarget("treeFrame");
		}
		return dictList;
	}
	/**
	 * 获取所有数据并填充每条数据的子级列表(递归处理)下拉ztree用
	 * @param MENU_ID
	 * @return
	 * @throws Exception
	 */
	public List<PageData> listAllDictToSelect(String parentId, List<PageData> zdicPdList) throws Exception {
		List<PageData>[] arrayDep = this.listAllbyPd(parentId,zdicPdList);
		List<PageData> dicPdList = arrayDep[1];
		for(PageData pd : dicPdList){
			this.listAllDictToSelect(pd.getString("id"),arrayDep[0]);
		}
		return arrayDep[0];
	}
	/**下拉ztree用
	 * @param parentId
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<PageData>[] listAllbyPd(String parentId, List<PageData> zdicPdList) throws Exception {
		List<Dictionaries> dicList = this.listSubDictByParentId(parentId);
		List<PageData> dicPdList = new ArrayList<PageData>();
		for(Dictionaries dic : dicList){
			PageData pd = new PageData();
			pd.put("id", dic.getDICTIONARIES_ID());
			pd.put("parentId", dic.getPARENT_ID());
			pd.put("name", dic.getNAME());
			pd.put("icon", "../../../assets/images/user.gif");
			dicPdList.add(pd);
			zdicPdList.add(pd);
		}
		List<PageData>[] arrayDep = new List[2];
		arrayDep[0] = zdicPdList;
		arrayDep[1] = dicPdList;
		return arrayDep;
	}
	/**列表
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> list(Page page)throws Exception{
		return dictionariesMapper.datalistPage(page);
	}

	/**通过id获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findById(PageData pd)throws Exception{
		return dictionariesMapper.findById(pd);
	}
	/**通过名称获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findByName(PageData pd)throws Exception{
		return dictionariesMapper.findByName(pd);
	}

	/**通过编码获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findByBianma(PageData pd)throws Exception{
		return dictionariesMapper.findByBianma(pd);
	}

	/**新增
	 * @param pd
	 * @throws Exception
	 */
	public void save(PageData pd)throws Exception{
		dictionariesMapper.save(pd);
	}

	/**修改
	 * @param pd
	 * @throws Exception
	 */
	public void edit(PageData pd)throws Exception{
		dictionariesMapper.edit(pd);
	}

	/**排查表检查是否被占用
	 * @param pd
	 * @throws Exception
	 */
	public PageData findFromTbs(PageData pd)throws Exception{
		return dictionariesMapper.findFromTbs(pd);
	}

	/**删除
	 * @param pd
	 * @throws Exception
	 */
	public void delete(PageData pd)throws Exception{
		dictionariesMapper.delete(pd);
	}

	/**
	 * 通过IDS获取列表
	 * @param dictionariesIds
	 * @return
	 * @throws Exception
	 */
	public List<Dictionaries> listSubDictByIds(String[] dictionariesIds) throws Exception {
		return dictionariesMapper.listSubDictByIdS(dictionariesIds);
	}

	/**新增(增加在线考试使用人员类别)
	 * @param pd
	 * @throws Exception
	 */
	public PageData saveSelf(PageData pd)throws Exception{
		List<Dictionaries> list = this.listSubDictByParentId("532282f9c48346b8b646531909c739df");
		String BIANMA = "APPLICABLEPERSONNEL000";
		if (list.size()+1 <10) {
			BIANMA = BIANMA.substring(0,BIANMA.length()-1) + (list.size()+1);
		} else if (list.size()+1 <100) {
			BIANMA = BIANMA.substring(0,BIANMA.length()-2) + (list.size()+1);
		} else {
			BIANMA = BIANMA.substring(0,BIANMA.length()-3) + (list.size()+1);
		}
		PageData lc = new PageData();
		lc.put("DICTIONARIES_ID", UuidUtil.get32UUID());
		lc.put("NAME", pd.getString("LEARNERCATEGORY"));
		lc.put("NAME_EN", BIANMA);
		lc.put("BIANMA", BIANMA);
		lc.put("ORDER_BY", list.size()+1);
		lc.put("PARENT_ID", "532282f9c48346b8b646531909c739df");
		this.save(lc);
		return lc;
	}
	/**新增(动态字典信息)
	 * @param pd
	 * @throws Exception
	 */
	public PageData saveByZidongxinzeng(PageData pd)throws Exception{
		PageData lc = dictionariesMapper.getPdByParIdAndName(pd);
		if(null == lc){
			PageData pageDataSize = dictionariesMapper.getCountByParId(pd);
			Integer count = Integer.valueOf(pageDataSize.get("zs").toString()) +1 ;
			String BIANMA = pd.getString("BIANMA") + String.format("%04d", count);
			lc = new PageData();
			lc.put("DICTIONARIES_ID", UuidUtil.get32UUID());
			lc.put("NAME", pd.getString("NAME"));
			lc.put("NAME_EN", BIANMA);
			lc.put("BIANMA", BIANMA);
			lc.put("ORDER_BY", count);
			lc.put("PARENT_ID", pd.getString("PARENT_ID"));
			this.save(lc);
		}
		return lc;
	}
	/**通过编码获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findByName(String name,String PARENT_ID)throws Exception{
		PageData pageData = new PageData();
		pageData.put("NAME",name);
		pageData.put("PARENT_ID",PARENT_ID);
		return dictionariesMapper.getPdByParIdAndName(pageData);
	}

	/**
	 * 获取根节点
	 * @param MENU_ID
	 * @return
	 * @throws Exception
	 */
	public PageData getRootDicById(String id) throws Exception {
		PageData pd = new PageData();
		pd.put("DICTIONARIES_ID", id);
		PageData dic = dictionariesMapper.findById(pd);
		if(dic != null && dic.get("PARENT_ID") != null
				&& Tools.notEmpty(dic.get("PARENT_ID").toString())
				&& !"f2598ba72e864eadabf0ca4b664d26b9".equals(dic.get("PARENT_ID").toString())) {
			dic = getRootDicById(dic.get("PARENT_ID").toString());
		}
		return dic;
	}

	public List<PageData> listSubDictByParentIdAndSunCount(String parentId) throws Exception {
		return dictionariesMapper.listSubDictByParentIdAndSunCount(parentId);
	}

	/**
	 * 从下而上查询树（无分支）
	 * @param dic
	 * @return
	 * @throws Exception
	 */
	public List<PageData> getTreeFromBelow(List<PageData> nextList, PageData dic) throws Exception{
		List<PageData> dicList = dictionariesMapper.listBySameParent(dic.get("PARENT_ID").toString());
		if(nextList != null && dicList != null && nextList.size() > 0 && dicList.size() > 0) {
			for(PageData d : dicList) {
				if(dic.getString("DICTIONARIES_ID").equals(d.getString("id"))) {
					d.put("children", nextList);
				}
			}
		}
		PageData parDic = new PageData();
		parDic.put("DICTIONARIES_ID", dic.get("PARENT_ID"));
		parDic.put("NOROOT", "1");
		parDic = dictionariesMapper.findById(parDic);
		if(parDic != null && parDic.get("DICTIONARIES_ID") != null && !"0".equals(parDic.get("PARENT_ID").toString())) {
			dicList = getTreeFromBelow(dicList,parDic);
		}
		return dicList;
	}

	public List<PageData> getIdsByRecuByParentId(String parentId) throws Exception {
		return dictionariesMapper.getIdsByRecuByParentId(parentId);
	}
	public void importAreaFromJson(){
		try {
			BufferedReader br = new BufferedReader(new FileReader("D:\\educationWorkSpace\\untitled\\index_2022__level_5.json"));
			String buf = br.readLine();
			StringBuffer json = new StringBuffer();
			while (buf != null) {
				json.append(buf);
				buf = br.readLine();
			}
			List<JSONObject> jsonList = (List<JSONObject>) JSON.parse(json.toString());
			for (JSONObject provinces : jsonList) {
				for (JSONObject city : (List<JSONObject>)provinces.get("children")){
					PageData cipd = new PageData();
					cipd.put("BIANMA",city.getString("value").substring(0,6));
					cipd = findByBianma(cipd);

					for (JSONObject county : (List<JSONObject>)city.get("children")){
						PageData cpd = new PageData();
						cpd.put("BIANMA",county.getString("value").substring(0,6));
						cpd = findByBianma(cpd);
						if(cpd==null){
							PageData pd = new PageData();
							pd.put("DICTIONARIES_ID", UuidUtil.get32UUID());	//主键
							pd.put("NAME", county.get("label"));
							pd.put("NAME_EN", county.getString("value").substring(0,9));
							pd.put("BIANMA", county.getString("value").substring(0,9));
							pd.put("ORDER_BY", county.getString("value").substring(0,9));
							pd.put("PARENT_ID", cipd.get("DICTIONARIES_ID"));
							save(pd);
							cpd = pd;
						}

						for (JSONObject village : (List<JSONObject>)county.get("children")){
							PageData vpd = new PageData();
							vpd.put("BIANMA",village.getString("value").substring(0,9));
							vpd = findByBianma(vpd);
							if(vpd==null){
								PageData pd = new PageData();
								pd.put("DICTIONARIES_ID", UuidUtil.get32UUID());	//主键
								pd.put("NAME", village.get("label"));
								pd.put("NAME_EN", village.getString("value").substring(0,9));
								pd.put("BIANMA", village.getString("value").substring(0,9));
								pd.put("ORDER_BY", village.getString("value").substring(0,9));
								pd.put("PARENT_ID", cpd.get("DICTIONARIES_ID"));
								save(pd);
								vpd = pd;
							}

							int order = 0;
							for (JSONObject street : (List<JSONObject>)village.get("children")){
								PageData spd = new PageData();
								spd.put("BIANMA",street.get("value"));
								spd = findByBianma(spd);
								if(spd==null){
									PageData pd = new PageData();
									pd.put("DICTIONARIES_ID", UuidUtil.get32UUID());	//主键
									pd.put("NAME", street.get("label"));
									pd.put("NAME_EN", street.get("value"));
									pd.put("BIANMA", street.get("value"));
									pd.put("ORDER_BY", order);
									pd.put("PARENT_ID", vpd.get("DICTIONARIES_ID"));
									save(pd);
									order ++;
								}
							}
						}
					}
				}
			}
			System.out.println("=====================导入完成===================");
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		String s = "110101001000";
		System.out.println(s.substring(0,9));
	}
}
