// 知识库维护
import React from 'react';
import {Radio, Tabs, message, Input, Row, Col, Tree, InputNumber, Icon, Button, Table, Modal, Popover, Collapse, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import './style/index.less';
import AddKnowledgeBaseTree from './component/AddKnowledgeBaseTree.jsx';
import AddAddKnowledgeBase from './component/AddAddKnowledgeBase.jsx';
import AddNodeDirectory from './component/AddNodeDirectory.jsx';
import OtherCustomData from './component/OtherCustomData.jsx';
import RangeMaintenance from './component/RangeMaintenance.jsx';
import SettingsDocumentSize from './component/SettingsDocumentSize';
import ElectronicCaseTemplate from 'pages/common/ElectronicCaseTemplate.jsx';
import EMRToolLibrary from './component/EMRToolLibrary.jsx';
import '../../assets/css/common.css';

const { TabPane } = Tabs;
const { TreeNode } = Tree;
const { Panel } = Collapse;

export default class KnowledgeBaseMaintenance extends React.Component {
	constructor() {
		super();
		this.state = {
			value: 'PDF',
			align: 'AlignBottomRight',
			flag: true,
			selectData: {},
			selectValue: 'locType',
			backgroundColor: 'red',
      index: 1,
      knowledgeBaseTreeData: [], // 知识库树数据
			knowledgeBaseSelectedKeys: [], // 知识库选中的树节点
			counterObj: {},
			insertTemplateArr: [],
			customDataSet: [], // 自定义数据集
			dataSetSelectedKeys: [], // 自定义数据集选中操作
			dataSource: [], // 元素数据源信息
			basicsDataSetColumns: [], // 基础数据集表头数据
			basicsDataSetDataSource: [],
			visible: false,
			rowId: '',
			modalTreeSelectData: {},
			inputId: '', // 双击模板中的输入域ID
			customDataColumns: [], // 自定义数据表头
			customDataTableData: [],
			insertTypeVisible: false,
			frameType: undefined,
			customRowData: {}, // 自定义选中行数据
			trangeListData: [], // 值域数据
			citingResourcesKeys: "1",
			knowledgeAutoExpandParent: true,
			knowledgeExpandedKeys: [],
			dataSetAutoExpandParent: true,
			dataSetExpandedKeys: [],
			dataSetValue: "",
			customDataRowId: "",
			customDataRowData: {},
			fontTyle: undefined,
			colorTemplateFlag: '',
			isShowCustomPopUps: false,
			nodeDirectoryTreeData: [], // 知识库节点目录树
			knowledgeBaseTreeSelectData: {},
			popoverVisible: false
		}
	}

	componentDidMount() {
    this.getBasicsDataSetColumns(); // 初始化基本数据集表头数据
    this.getBasicsDataSetDataSource();
    this.getKnowledgeBaseTreeData();
	}
	
	componentWillUnmount() {
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state,callback)=>{ return; }
	}

	// 保存
	handleSave = () => {
		let {nodeDirectoryTreeSelectData, insertTemplateArr} = this.state;
		if (!(nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.treeType === "TEMPLATE")) {
			return;
		}
		let xmlStrAndDataSource = this.caseTemplateChild.getTemplateXml();
		let data = {
			params: [{
				ID: nodeDirectoryTreeSelectData.ID,
				code: nodeDirectoryTreeSelectData.code,
				descripts: nodeDirectoryTreeSelectData.descripts,
				nodeContent: xmlStrAndDataSource.xmlStr,
				dataSource: xmlStrAndDataSource.dataSource
			}]
		}
    $http.post('urlADS', this, {
			code: "06020028",
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					// 成功提示
					message.success('保存成功');
				}
			}
		})
	}

	// 获取自定义数据集
	getCustomDataSet = () => {
		let data = {
			params: [{
				ID: '', // 表ID
				code: '', // 数据集代码
				descripts: '', // 数据集描述
				serviceCode: '', // 服务代码
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: "06010017",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.data.length; i++) {
						res.result.data[i].key = 'main' + res.result.data[i].ID;
					}
					this.setState({ customDataSet: res.result.data })
				}
			}
		})
	}

	// 异步加载数据集的子数据数据
	onLoadData = treeNode =>
		new Promise(resolve => {
			console.log(treeNode)
			if (!treeNode.props.serviceCode || treeNode.props.children) {
				resolve();
				return;
			}
			let ID = treeNode.props.dataRef.ID;
			let data = {
				params: [{
					code: "", // 数据集代码
					descripts: "", // 数据集描述
					CBEMRDSRParRef: ID,
				}],
				pagination: [{
					pageSize: 1000,
					currentPage: 1
				}]
			}
			$http.post('urlS', this, {
				code: "06010025",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0 && res.result) {
						for(var i = 0; i < res.result.length; i++) {
							res.result[i].key = res.result[i].ID;
							res.result[i].isLeaf = true;
							res.result[i].serviceCode = treeNode.props.serviceCode;
							res.result[i].type = 'C',
							res.result[i].customID = res.result[i].ID; 
						}
						treeNode.props.dataRef.children = res.result;
						this.setState({
							customDataSet: [...this.state.customDataSet],
						});
						resolve();
					} else {
						resolve();
					}
				}
			})
		}
	)

	renderCustomDataSetTreeNodes = data =>
		data.map(item => {
			const index = item.descripts.indexOf(this.state.dataSetValue);
			const beforeStr = item.descripts.substr(0, index);
			const afterStr = item.descripts.substr(index + this.state.dataSetValue.length);
			const title = index > -1 ? (
					<span>
					{beforeStr}
					<span style={{ color: '#FF7F00' }}>{this.state.dataSetValue}</span>
					{afterStr}
					</span>
			) : <span>{item.descripts}</span>;
			if (item.children&&item.children.length > 0) {
				return (
					<TreeNode title={title} key={item.key} dataRef={item}>
						{this.renderCustomDataSetTreeNodes(item.children)}
					</TreeNode>
				);
			}
			return <TreeNode title={title} key={item.key} {...item} dataRef={item} />;
		}
	);

	// 双击自定义数据集树
	dataSetDBClickTreeNodes = (status, record) => {
		if (!record.props.isLeaf) { // 如果不是子集数据择不将这条数据插入到模板中
			return;
		}
		let key = [];
		let obj = JSON.parse(JSON.stringify(record.props.dataRef));
		let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
		key.push(record.props.dataRef.ID);
		this.setState({dataSetSelectedKeys: key}, () => {
			caseTemplateThis.InsertDynamicList(obj)
		})
	}

	// 获取基础数据集表头数据
	getBasicsDataSetColumns = () => {
		let columns = [
			{
				title: '数据集代码',
				dataIndex: 'code',
				align: "center",
				width: '100px'
			},
			{
				title: '数据集名称',
				dataIndex: 'descripts',
				align: "center",
				width: '100px'
			},
		];
		this.setState({basicsDataSetColumns: columns})
	}

	// 获取基础数据集列表数据
	getBasicsDataSetDataSource = () => {
		let data = {
			params: [{
				ID: '', // 表ID
				code: '', // 数据集代码
				descripts: '', // 数据集描述
				dataSetType: '', // 数据集类型
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: "06010013",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.length; i++) {
						res.result[i].key = i;
						res.result[i].type = 'B';
					}
					this.setState({ basicsDataSetDataSource: res.result})
				}
			}
		})
	}

	// 3.3.22.清除模板版本加载缓存
	clearLoadCache = (fileName) => {
		if (!fileName) return;
		let data = {
			params: [{
				patch: fileName
			}]
		}
		$http.post('urlS', this, {
			code: "06020026",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					console.log("清除缓存成功")
				}
			}
		})
	}

	// 操作行
	onClickOnRow = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.rowId === '') {
					// 保存行数据以及ID
					this.setState({rowId: record.key})
				} else {
					if (this.state.rowId !== record.key) {
						this.setState({rowId: record.key})
					}
				}
			},
			onDoubleClick: () => {
				let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
				this.setState({rowId: record.key}, () => {
					caseTemplateThis.dynamicDropDownList(record);
				})
			}
		}
	}

	// 选中行操作
	setRowClassNameLeftTable = (record) => {
		return record.key === this.state.rowId ? 'clickRowStyle' : '';
	}

	// 重置界面操作数据
	resetInterfaceData = () => {
		this.setState({dataSetSelectedKeys: [], rowId: ''})
	}

	// 获取自定义数据表头数据
	getCustomDataColumns = () => {
		let columns = [
			{
				title: '代码',
				dataIndex: 'code',
				align: "center",
				width: '80px'
			},
			{
				title: '描述',
				dataIndex: 'descripts',
				align: "center",
				width: '120px'
			},
			{
				title: '是否下拉框标志',
				dataIndex: 'listBoxOrNot',
				align: "center",
				width: '120px',
				render(listBoxOrNot){
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[listBoxOrNot];
				}
			},
			{
				title: '是否单选框标志',
				dataIndex: 'radioOrNot',
				align: "center",
				width: '120px',
				render(radioOrNot){
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[radioOrNot];
				}
			},
			{
				title: '是否复选框标志',
				dataIndex: 'checkBoxOrNot',
				align: "center",
				width: '120px',
				render(checkBoxOrNot){
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[checkBoxOrNot];
				}
			},
			{
				title: '操作',
				align: "center",
				width: 80,
				fixed: 'right',
				render: (text, record) => (
					<span>
						<span onClick={() => this.rangeMaintenanceChild.showModal(record)} className='span' style={{color: 'rgb(77, 193, 130)'}}>维护值域</span>
				  </span>
				),
			}
		];
		this.setState({customDataColumns: columns});
	}

	// 获取自定义列表数据
	getCustomDataTableData = () => {
		let data = {
			params: [{}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: "06010043",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.length; i++) {
						res.result[i].key = i;
					}
					this.setState({ customDataTableData: res.result})
				}
			}
		})
	}

	// 编辑自定义数据
	handleCustomDataCompile = () => {
		this.otherCustomDataChild.showModal(this.state.customDataRowData, 'compile')
	}

	// 删除自定义数据
	handleCustomDataDelete = () => {
		let data = {
			params: [{
				ID: this.state.customDataRowData.ID
			}]
		}
		$http.post('urlADS', this, {
			code: "06010039",
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
					// 刷新列表数据
					this.getCustomDataTableData();
				}
			}
		})
	}

	otherCustomDataOnRef = ref => {
		this.otherCustomDataChild = ref;
	}

	rangeMaintenanceOnRef = ref => {
		this.rangeMaintenanceChild = ref;
	}

	// 自定义数据操作行
	customDataOnRow = record => {
		return {
			onClick: () => {
				if (this.state.customDataRowId === '') {
					// 保存行数据以及ID
					this.setState({customDataRowId: record.ID, customDataRowData: record});
				} else {
					if (this.state.customDataRowId !== record.ID) {
						this.setState({customDataRowId: record.ID, customDataRowData: record});
					}
				}
			},
			onDoubleClick: () => {
				let {checkBoxOrNot, listBoxOrNot, radioOrNot} = record;
				let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
				if (checkBoxOrNot === 'Y' && listBoxOrNot === 'N' && radioOrNot === 'N') {
					// 直接插入checkbox
					this.geTrangeListData(record, 'checkbox');
				} else if (checkBoxOrNot === 'N' && listBoxOrNot === 'Y' && radioOrNot === 'N') {
					// 直接插入下拉列表
					caseTemplateThis.dynamicDropDownList(record);
				} else if (checkBoxOrNot === 'N' && listBoxOrNot === 'N' && radioOrNot === 'Y') {
					// 直接插入radio
					this.geTrangeListData(record, 'radio');
				} else if (checkBoxOrNot === 'N' && listBoxOrNot === 'N' && radioOrNot === 'N') {
					// 直接插入radio
					return;
				} else {
					this.handleInsertTypeShowModal(record)
				}
			}
		}
	}

	customDataRowClassName = record => {
		return record.ID === this.state.customDataRowId ? 'clickRowStyle' : '';
	}

	// 请求自定义数据所在行的维护值域
	geTrangeListData = (record, flag) => {
		let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
		let data = {
			params: [{
				othCode: record.code
			}]
		}
		$http.post('urlADS', this, {
			code: "06010036",
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					let arr = res.result;
					for (var i = 0; i < arr.length; i++) {
						arr[i].ToolTip = arr[i].descripts;
						arr[i].Text = arr[i].descripts;
						arr[i].Value = arr[i].ID;
					}
					this.setState({trangeListData: arr}, () => {
						if (flag === 'checkbox' || flag === 'radio') {
							caseTemplateThis.insertCheckboxRadio(this.state.trangeListData, flag, record);
						}
					})
				}
			}
		})
	}

	// 打开选择插入类型弹窗
	handleInsertTypeShowModal = (record) => {
		this.setState({insertTypeVisible: true, customRowData: record});
	}

	// 关闭选择插入类型弹窗
	handleInsertTypeCancel = () => {
		this.setState({insertTypeVisible: false});
	}

	// 确认
	handleInsertTypeOk = () => {
		let {customRowData, frameType} = this.state;
		let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
		if (frameType === 'radio') {
			this.geTrangeListData(customRowData, frameType);
			this.handleInsertTypeCancel();
		} else if (frameType === 'checkbox') {
			this.geTrangeListData(customRowData, frameType);
			this.handleInsertTypeCancel();
		} else if (frameType === 'select') {
			caseTemplateThis.dynamicDropDownList(customRowData);
			this.handleInsertTypeCancel();
		}
	}

	handleFrameTypeOnChange = e => {
		this.setState({
			frameType: e.target.value,
		});
	}

	documentSetRef = ref => {
		this.documentSetChild = ref;
	}

	// 引用资源tabs切换
	citingResourcesOnChange = key => {
		this.setState({citingResourcesKeys: key}, () => {
      if (this.state.citingResourcesKeys === '3') {
				if (!(this.state.customDataSet&&this.state.customDataSet.length > 0)) {
					this.getCustomDataSet(); // 获取自定义数据集
				}
			} else if (this.state.citingResourcesKeys === '4') {
				if (!(this.state.customDataColumns&&this.state.customDataColumns.length > 0)) {
					this.getCustomDataColumns(); // 初始化其他自定义表头数据
				}
				this.getCustomDataTableData();
			}
		})
	}

	getParentKey = (key, tree) => {
		let parentKey;
		for (let i = 0; i < tree.length; i++) {
			const node = tree[i];
			if (node.children) {
				if (node.children.some(item => item.key === key)) {
					parentKey = node.key;
				} else if (this.getParentKey(key, node.children)) {
					parentKey = this.getParentKey(key, node.children);
				}
			}
		}
		return parentKey;
	};

	knowledgeOnExpand = (knowledgeExpandedKeys) => {
		this.setState({
			knowledgeExpandedKeys,
			knowledgeAutoExpandParent: false,
		});
	}

	dataSetOnExpand = (dataSetExpandedKeys) => {
		this.setState({
			dataSetExpandedKeys,
			dataSetAutoExpandParent: false,
		});
	}

	//以下是Tree展开搜索
	dataList = [];
	generateList = (data) => {
		for (let i = 0; i < data.length; i++) {
			const node = data[i];
			const key = node.key;
			this.dataList.push({ key, title: node.title });
			if (node.children) {
				this.generateList(node.children);
			}
		}
	};

	handleDataSetValueChange = e => {
		const dataSetValue=e.target.value;
		const dataSetExpandedKeys = this.dataList.map((item) => {
			if (dataSetValue.length===0) return null;
			if (item.title.indexOf(dataSetValue) > -1) {
				return this.getParentKey(item.key, this.state.customDataSet);
			}
			return null;
		}).filter((item, i, self) => item && self.indexOf(item) === i);
		this.setState({
			dataSetExpandedKeys,
			dataSetValue,
			dataSetAutoExpandParent: true,
		});
	}

	handleCustomPopUpsCancel = () => {
		this.setState({isShowCustomPopUps: false});
	}

	// 
	handleCustomPopUpsOk = () => {
		var ctl = document.getElementById("myWriterControl");
		var result = ctl.SetElementTextByID(this.state.initID, "柿子");//赋值
		if (result) {
			this.handleCustomPopUpsCancel();
		}
	}

	// 去除表格边框
	removeBorders = () => {
		var ctl = document.getElementById("myWriterControl");
		var tableDom = ctl.CurrentTable(); // 获取光标所在的表格
		var tables= ctl.GetContentDocument().getElementById(tableDom.id);
		tables.children[1].children[0].children[0].style.border = 0
	}
  
	// 处理tree数据
	filterTreeData = treeData => {
		let data = treeData&&treeData.map(item => {
			return {
				title: item.descripts,
				key: item.treeType + item.ID,
				...item,
				children: this.filterTreeData(item.subCatalogue)
			}
		});
		return data;
	}
  
	// 获取知识库树数据
	getKnowledgeBaseTreeData = () => {
		let data = {
			params: [{}]
		}
		$http.post('urlS', this, {
			code: "06020013",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = this.filterTreeData(res.result);
					this.setState({
						knowledgeBaseTreeData: arr, 
						knowledgeBaseSelectedKeys: [], 
						knowledgeBaseTreeSelectData: {}, 
						nodeDirectoryTreeData: [], 
						nodeDirectorySelectedKeys: [],
						nodeDirectoryTreeSelectData: {}
					})
				}
			}
		})
  }
  
	// 知识库树选中操作
	knowledgeBaseOnSelect = (keys, event) => {
		this.setState({knowledgeBaseSelectedKeys: keys}, () => {
			if (this.state.knowledgeBaseSelectedKeys&&this.state.knowledgeBaseSelectedKeys.length > 0) {
				this.setState({knowledgeBaseTreeSelectData: event.node.props.dataRef}, () => {
					if (this.state.knowledgeBaseTreeSelectData&&this.state.knowledgeBaseTreeSelectData.treeType === "TEMPLATE") {
						this.getNodeDirectoryTreeData()
					}
				})
			} else{
				this.setState({knowledgeBaseTreeSelectData: {}})
			}
		})
  }

  renderTreeNodes = (data) => data.map(item => {
      let type = item.treeType === 'CATALOG' ? 'folder-open' : (item.treeType === 'TEMPLATE' ? 'folder' : 'file');
      if (item.children) {
        return (
          <TreeNode icon={<Icon type={type} />} title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode icon={<Icon type={type} />} title={item.title} key={item.key} dataRef={item} />;
  });
  
	onKnowledgeBaseTreeRef = ref => {
		this.knowledgeBaseTreeChild = ref;
  }
  
	onKnowledgeBaseRef = ref => {
		this.knowledgeBaseChild = ref;
	}

	nodeDirectoryRef = ref => {
		this.nodeDirectoryChild = ref;
	}

  // 添加目录、知识库
	handleAddknowledgeBase = (flag) => {
		let {knowledgeBaseTreeSelectData} = this.state;
		if (knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.addOrNot === 'N') {
			return;
		}
		
		let obj = {
			knowledgeBaseTreeSelectData,
			flag: 'add'
		}
		if (flag === 'catalog') {
			if (knowledgeBaseTreeSelectData.catalogFlag === 'N') {
				return;
			}
			this.knowledgeBaseTreeChild.showModal(obj); // 目录
		} else {
			if (knowledgeBaseTreeSelectData.templateFlag === 'Y') {
				this.knowledgeBaseChild.showModal(obj); // 知识库
			} else {
				return;
			}
		}
  }
  
	// 编辑模板
	handleCompileCatalog = () => {
		let {knowledgeBaseTreeSelectData} = this.state;
		if(!(knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.updateOrNot === 'Y')) {
			return;
		}
		let obj = {
			knowledgeBaseTreeSelectData,
			flag: 'compile'
		}
		if(knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.ID) {
			if (knowledgeBaseTreeSelectData.treeType === 'CATALOG') {
				this.knowledgeBaseTreeChild.showModal(obj);
			} else if (knowledgeBaseTreeSelectData.treeType === 'TEMPLATE') {
				this.knowledgeBaseChild.showModal(obj);
			} else {
				return;
			}
		} else {
			return;
		}
	}

	// 删除模板
	handleDeleteCatalog = () => {
		let {knowledgeBaseTreeSelectData} = this.state;
		if (!(knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.deleteOrNot === 'Y')) {
			return;
		}
		let code = '';
		if(knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.ID) {
			if (knowledgeBaseTreeSelectData.treeType === 'CATALOG') {
				code = '06020016';
			} else if (knowledgeBaseTreeSelectData.treeType === 'TEMPLATE') {
				code = '06020019';
			}
		} else {
			return;
		}
		let data = {
			params: [{
				ID: knowledgeBaseTreeSelectData.ID
			}]
		}
		$http.post('urlADS', this, {
			code: code,
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
					// 刷新列表数据
					this.getKnowledgeBaseTreeData();
				}
			}
		})
	}

	// 双击知识库目录树
	// knowledgeBaseDoubleClick = (status, record) => {
	// 	// if (!record.props.isLeaf) { // 如果不是子集数据择不将这条数据插入到模板中
	// 	// 	return;
	// 	// }
	// 	let key = [];
	// 	let obj = JSON.parse(JSON.stringify(record.props.dataRef))
	// 	key.push(record.props.dataRef.treeType + record.props.dataRef.ID);
	// 	this.setState({knowledgeBaseSelectedKeys: key, knowledgeBaseTreeSelectData: obj}, () => {
	// 		this.getNodeDirectoryTreeData()
	// 	})
	// }

	// 获取知识库节点目录树
	getNodeDirectoryTreeData = (ID) => {
		let {knowledgeBaseTreeSelectData} = this.state;
		let data = {
			params: [{
				knowledgeID: knowledgeBaseTreeSelectData.ID
			}]
		}
		$http.post('urlS', this, {
			code: "06020030",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = this.filterTreeData(res.result);
					this.setState({nodeDirectoryTreeData: arr, nodeDirectorySelectedKeys: [], nodeDirectoryTreeSelectData: {}}, () => {
						if (ID) {
							let key = [];
							let obj = {
								ID,
								treeType: 'TEMPLATE', 
								deleteOrNot: "Y",
								updateOrNot: "Y",
								addOrNot: "N",
							};
							key.push('TEMPLATE' + ID);
							this.setState({nodeDirectorySelectedKeys: key, nodeDirectoryTreeSelectData: obj});
						}
					})
				} else {
					this.setState({nodeDirectoryTreeData: [], nodeDirectorySelectedKeys: [], nodeDirectoryTreeSelectData: {}})
				}
			}
		})
	}

	// 知识库节点目录选中操作
	nodeDirectoryOnSelect = (keys, event) => {
		this.setState({nodeDirectorySelectedKeys: keys}, () => {
			if (this.state.nodeDirectorySelectedKeys&&this.state.nodeDirectorySelectedKeys.length > 0) {
				this.setState({nodeDirectoryTreeSelectData: event.node.props.dataRef})
			} else {
				this.setState({nodeDirectoryTreeSelectData: {}})
			}
		})
  }
	
	// 新增知识库节点目录以及j节点数据
	handleAddnodeDirectory = (code) => {
		let {knowledgeBaseTreeSelectData, nodeDirectoryTreeSelectData} = this.state;
		this.nodeDirectoryChild.showModal('add', code, knowledgeBaseTreeSelectData, nodeDirectoryTreeSelectData, nodeDirectoryTreeSelectData)
	}

	// 修改知识库节点目录以及j节点数据
	handleCompileNodeDirectory = () => {
		let {knowledgeBaseTreeSelectData, nodeDirectoryTreeSelectData} = this.state;
		let code = "";
		if (nodeDirectoryTreeSelectData.treeType === "CATALOG") {
			code = "06020021"
		} else if (nodeDirectoryTreeSelectData.treeType === "TEMPLATE") {
			code = "06020028"
		}
		this.nodeDirectoryChild.showModal('compile', code, knowledgeBaseTreeSelectData, nodeDirectoryTreeSelectData, nodeDirectoryTreeSelectData)
	}

	// 删除知识库节点目录
	handleDeleteNodeDirectory = () => {
		let {nodeDirectoryTreeSelectData, nodeDirectorySelectedKeys} = this.state;
		let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
		let code = '';
		if(nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.ID) {
			if (nodeDirectoryTreeSelectData.treeType === 'CATALOG') {
				code = '06020022';
			} else if (nodeDirectoryTreeSelectData.treeType === 'TEMPLATE') {
				code = '06020029';
			}
		} else {
			return;
		}
		let data = {
			params: [{
				ID: nodeDirectoryTreeSelectData.ID
			}]
		}
		$http.post('urlADS', this, {
			code: code,
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
					// 刷新列表数据
					this.getNodeDirectoryTreeData();
					if (nodeDirectorySelectedKeys&&nodeDirectorySelectedKeys.length > 0) {
						let key = "TEMPLATE" + nodeDirectoryTreeSelectData.ID;
						(code === '06020029')&&(key === nodeDirectorySelectedKeys[0]) ? caseTemplateThis.operableShow() : '';
					}
				}
			}
		})
	}

	// 双击加载模板
	nodeDirectoryDoubleClick = (status, record) => {
		let key = [];
		let obj = JSON.parse(JSON.stringify(record.props.dataRef));
		if (obj.treeType !== 'TEMPLATE') {
			return;
		} else {
			if (this.state.nodeDirectoryTreeSelectData&&(this.state.nodeDirectoryTreeSelectData.ID === obj.ID)) { // 双击相同模板不做操作
				return; 
			}
			key.push(obj.treeType + obj.ID);
			this.setState({nodeDirectorySelectedKeys: key, nodeDirectoryTreeSelectData: obj}, () => {
				this.handleLoadingDocuments()
			})
		}
	}
	
	// 获取需要加载的模板路径
	handleLoadingDocuments = () => {
		let ID = this.state.nodeDirectoryTreeSelectData&&this.state.nodeDirectoryTreeSelectData.ID ? this.state.nodeDirectoryTreeSelectData.ID : "";
		let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
		let data = {
			params: [{
				ID, // 模板版本ID
			}]
		}
		$http.post('urlS', this, {
			code: "06020031",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({templatePath: res.result.templatePath}, () => {
						this.state.templatePath ? caseTemplateThis.setElementTextByID(this.state.templatePath, res.result.dataSource, "N", "boolTrue") : caseTemplateThis.NewFile();
					})
				}
			}
		})
	}

	// 解锁知识库
	unlockKnowledgeBase = () => {
		let ID = this.state.nodeDirectoryTreeSelectData&&this.state.nodeDirectoryTreeSelectData.ID ? this.state.nodeDirectoryTreeSelectData.ID : "";
		let data = {
			params: [{
				ID, // 模板版本ID
			}]
		}
		$http.post('urlS', this, {
			code: "06020033",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success("解锁知识库成功")
				}
			}
		})
	}

	handleCaseTemplateRef = ref => {
		this.caseTemplateChild = ref;
	}

	// 新建模板
	newTemplate = () => {
		let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
		caseTemplateThis.NewFile();
	}

	render() {
		let {knowledgeBaseSelectedKeys, knowledgeBaseTreeData, customDataSet, dataSetSelectedKeys, basicsDataSetDataSource, basicsDataSetColumns, customDataTableData,
			customDataColumns, insertTypeVisible, frameType, customRowData, citingResourcesKeys, knowledgeAutoExpandParent, knowledgeExpandedKeys, dataSetAutoExpandParent,
			dataSetExpandedKeys, dataSetValue, isShowCustomPopUps, nodeDirectoryTreeData, nodeDirectorySelectedKeys, 
			knowledgeBaseTreeSelectData, nodeDirectoryTreeSelectData
		} = this.state;

		let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this

		let param = {
			num: '11111111111111111111'
		}

		return (
			<div className="emr-style">
				<div style={{width: "440px", height: '100%', display: 'inline-block', overflow: 'hidden'}}>
          <div style={{textAlign: "center", height: '34px', lineHeight: '34px', fontWeight: 900, fontSize: "14px", background: "#fafafa", borderBottom: "1px solid #e8e8e8"}}>
						知识库目录导航
					</div>
          <Row style={{height: "calc(100% - 34px)"}}>
            <Col span={12} style={{borderRight: '1px solid #e8e8e8', height: '100%'}}>
              <div className="navigation-operation-icon" style={{background: "#fafafa"}}>
                <span style={{
									color: knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.addOrNot === 'N' ? "#666" : (knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.catalogFlag === 'N' ? "#666" : "#1999db"), 
									cursor: (knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.addOrNot === 'N' ? "no-drop" : (knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.catalogFlag === 'N') ? "no-drop" : "pointer"),
								}} 
									onClick={() => this.handleAddknowledgeBase("catalog")} 
								>
                  <Icon type="plus" />
                  目录
                </span>
								<span 
									style={{
										color: (knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.addOrNot === 'N' ? "#666" : (knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.templateFlag === 'Y') ? "#1999db" : "#666"),
										cursor: (knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.addOrNot === 'N' ? "no-drop" : (knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.templateFlag === 'Y') ? "pointer" : "no-drop"),
									}} 
									onClick={() => this.handleAddknowledgeBase("template")}
								>
                  <Icon type="plus" />
                  模板
                </span>
								{knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.deleteOrNot === 'Y' ? (<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDeleteCatalog} >
									<span style={{
										color: "rgb(240, 65, 52)", 
										cursor: "pointer",
									}} >
										<Icon type="delete" />
										删除
									</span>
								</Popconfirm>) : (
									<span style={{
										color: "#666", 
										cursor: "no-drop",
									}} >
										<Icon type="delete" />
										删除
									</span>
								)}
								<span 
									style={{ 
										color: knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.updateOrNot === 'Y' ? "#1890ff" : "#666",
										cursor: knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.updateOrNot === 'Y' ? "pointer" : "no-drop",
									}} 
									onClick={this.handleCompileCatalog} >
                  <Icon type="edit" />
                  修改
                </span>
              </div>
              <Tree showIcon 
                autoExpandParent={knowledgeAutoExpandParent}
                onExpand={this.knowledgeOnExpand}
                expandedKeys={knowledgeExpandedKeys}
                onSelect={this.knowledgeBaseOnSelect} 
								selectedKeys={knowledgeBaseSelectedKeys}
								// onDoubleClick={this.knowledgeBaseDoubleClick}
							>
                {this.renderTreeNodes(knowledgeBaseTreeData)}
              </Tree>
              <AddKnowledgeBaseTree onRef={this.onKnowledgeBaseTreeRef} handleQuery={this.getKnowledgeBaseTreeData} />
              <AddAddKnowledgeBase onRef={this.onKnowledgeBaseRef} handleQuery={this.getKnowledgeBaseTreeData} />
            </Col>
            <Col span={12} style={{height: '100%'}}>
							<div className="navigation-operation-icon" style={{background: "#fafafa"}}>
								<span 
									style={{
										color: knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.treeType === "TEMPLATE" ? (nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.addOrNot === 'N' ? "#666" : (nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.catalogFlag === 'N' ? "#666" : "#1999db")) : "#666", 
										cursor: knowledgeBaseTreeSelectData&&knowledgeBaseTreeSelectData.treeType === "TEMPLATE" ? (nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.addOrNot === 'N' ? "no-drop" : (nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.catalogFlag === 'N' ? "no-drop" : "pointer")) : "no-drop",
									}} 
									onClick={() => this.handleAddnodeDirectory("06020020")}
								>
                  <Icon type="plus" />
                  目录
                </span>
								<span 
									style={{
										color: nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.addOrNot === 'N' ? "#666" : (nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.templateFlag === 'Y' ? "#1999db" : "#666"), 
										cursor: nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.addOrNot === 'N' ? "no-drop" : (nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.templateFlag === 'Y' ? "pointer" : "no-drop"), 
									}} 
									onClick={() => this.handleAddnodeDirectory("06020027")} >
                  <Icon type="plus" />
                  节点
                </span>
								{nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.deleteOrNot === 'Y' ? (<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDeleteNodeDirectory} >
									<span 
										style={{
											color: "rgb(240, 65, 52)", 
											cursor: "pointer"
										}} 
									>
										<Icon type="delete" />
										删除
									</span>
								</Popconfirm>) : (
									<span 
									style={{
											color: "#666", 
											cursor: "no-drop"
										}} 
									>
										<Icon type="delete" />
										删除
									</span>
								)}
								<span 
									style={{
										color: nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.updateOrNot === 'Y' ? "#1890ff" : "#666", 
										cursor: nodeDirectoryTreeSelectData&&nodeDirectoryTreeSelectData.updateOrNot === 'Y' ? "pointer" : "no-drop"
									}}
									onClick={this.handleCompileNodeDirectory} 
								>
                  <Icon type="edit" />
                  修改
                </span>
              </div>
              {nodeDirectoryTreeData&&nodeDirectoryTreeData.length > 0 ? (
								<Tree showIcon 
									onSelect={this.nodeDirectoryOnSelect} 
									selectedKeys={nodeDirectorySelectedKeys}
									onDoubleClick={this.nodeDirectoryDoubleClick}
								>
                {this.renderTreeNodes(nodeDirectoryTreeData)}
              </Tree>
							) : <div style={{padding: "12px 34px", color: "#999"}}>请选择左侧目录树获取知识库节点数据</div>}
							<AddNodeDirectory onRef={this.nodeDirectoryRef} handleQuery={this.getNodeDirectoryTreeData} newTemplate={this.newTemplate} />
            </Col>
          </Row>
        </div>
				<div style={{width: "calc(100% - 800px)", height: '100%', display: 'inline-block', overflow: 'auto', padding: '0 6px', position: 'relative',}}>
					<ElectronicCaseTemplate 
						param={param}
						onRef={this.handleCaseTemplateRef}
						handleSave={this.handleSave}
						unlockKnowledgeBase={this.unlockKnowledgeBase}
					/>
					<div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%'}}></div>
					<div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%'}}></div>
				</div>
				<div style={{width: "360px", height: '100%', display: 'inline-block', overflow: 'hidden'}}>
					<Tabs defaultActiveKey="1" className="right-tabs" style={{height: "100%", overflow: 'auto'}}>
						<TabPane tab="引用资源" key="1">
							<div>
								<Tabs activeKey={citingResourcesKeys} onChange={this.citingResourcesOnChange} tabPosition="left" type="card" className="word-wrap">
									<TabPane tab="基础字典" key="1">
										<Table
											pagination={false}
											dataSource={basicsDataSetDataSource}
											columns={basicsDataSetColumns} 
											onRow={this.onClickOnRow}
											rowClassName={this.setRowClassNameLeftTable}
										/>
									</TabPane>
									<TabPane tab="自定义数据集" key="3">
										<Input value={dataSetValue} onChange={this.handleDataSetValueChange} placeholder="请输入名称搜索" />
										<Tree 
											loadData={this.onLoadData} 
											autoExpandParent={dataSetAutoExpandParent}
											onExpand={this.dataSetOnExpand}
											expandedKeys={dataSetExpandedKeys}
											selectedKeys={dataSetSelectedKeys} 
											onDoubleClick={this.dataSetDBClickTreeNodes}>
											{this.renderCustomDataSetTreeNodes(customDataSet)}
										</Tree>
									</TabPane>
									<TabPane tab="自定义组件" key="4">
										<div style={{textAlign: "right"}}>
											<Button style={{background: "#1999db", color: "#fff"}} onClick={() => this.otherCustomDataChild.showModal({}, 'add')} >新增</Button>
											<Button style={{margin: '0 12px', background: '#3399ff', color: "#fff"}} onClick={this.handleCustomDataCompile}>编辑</Button>
											<Button style={{background: "#ff0000", color: "#fff"}} onClick={this.handleCustomDataDelete}>删除</Button>
										</div>
										<Table
											pagination={false}
											dataSource={customDataTableData}
											columns={customDataColumns} 
											onRow={this.customDataOnRow}
											rowClassName={this.customDataRowClassName}
											scroll={{x: 760}}
										/>
									</TabPane>
									<TabPane tab="关联历史病历模块" key="5">
										<div>
											暂无数据
										</div>
									</TabPane>
								</Tabs>
							</div>
						</TabPane>
						<TabPane tab="工具库" key="2">
							<EMRToolLibrary caseTemplateThis={caseTemplateThis} />
						</TabPane>
					</Tabs>
				</div>
				
				<OtherCustomData onRef={this.otherCustomDataOnRef} handleQuery={this.getCustomDataTableData} />
				<RangeMaintenance onRef={this.rangeMaintenanceOnRef} />
				<Modal
					title="选择插入类型"
					visible={insertTypeVisible}
					onOk={this.handleInsertTypeOk}
					onCancel={this.handleInsertTypeCancel}
				>
					<div style={{textAlign: 'center'}}>
						<Radio.Group onChange={this.handleFrameTypeOnChange} value={frameType}>
							{customRowData&&customRowData.listBoxOrNot === 'Y' ? <Radio value="select">下拉框</Radio> : ''}
							{customRowData&&customRowData.radioOrNot === 'Y' ? <Radio value="radio">单选框</Radio> : ''}
							{customRowData&&customRowData.checkBoxOrNot === 'Y' ? <Radio value="checkbox">复选框</Radio> : ''}
						</Radio.Group>
					</div>
				</Modal>
				{/* 页面设置 */}
				<SettingsDocumentSize onRef={this.documentSetRef} ctlDom={document.getElementById("myWriterControl")}  />
				<Modal
					title="自定义弹窗"
					visible={isShowCustomPopUps}
					onOk={this.handleCustomPopUpsOk}
					onCancel={this.handleCustomPopUpsCancel}
				>
					功能完善中请耐心等待
				</Modal>
			</div>
		)
	}
}
