// 病历基础信息
import React from 'react';
import { Card, Table, Input, message, Popconfirm, Form, Icon, Divider, Row, Col, Tree, Modal, Select } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import '../../assets/css/common.css';
import './style/index.less';
import GroupedCatalogTree from './component/GroupedCatalogTree.jsx';
import ProtogenesisTable from '../hospitalPharmacies/component/ProtogenesisTable';
import CommonPagination from 'components/pagination/index';

let { TreeNode } = Tree;
let { Option } = Select;

const EditableContext = React.createContext();

class EditableCell extends React.Component {
	getInput = () => {
		// if (this.props.dataIndex === 'code') {
		return <Input style={{ width: '80%' }} placeholder="请输入" />;
		// }
		// return <Select style={{width: '80%'}} placeholder="请选择">{this.props.option}</Select>;
	};

	renderCell = ({ getFieldDecorator }) => {
		const {
			editing,
			dataIndex,
			title,
			inputType,
			option,
			record,
			index,
			children,
			...restProps
		} = this.props;
		return (
			<td {...restProps}>
				{editing ? (
					<Form.Item style={{ margin: 0 }}>
						{getFieldDecorator(dataIndex, {
							rules: [
								{
									required: true,
									message: `${title}不能为空!`,
								},
							],
							initialValue: record[dataIndex],
						})(this.getInput())}
					</Form.Item>
				) : (
					children
				)}
			</td>
		);
	};

	render() {
		return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
	}
}

class BasicCaseInformation extends React.Component {
	constructor(props) {
		super(props);
		var userData = JSON.parse(sessionStorage.getItem('userData'));
		this.state = {
			user: userData,
			pageSize: 10,
			page: 1,
			total: 0,
			dataSource: [],
			caseTemplateSelectData: [],
			caseTemplateTreeSelectData: {}, // 病历模板树选中行数据
			caseTemplateSelectedKeys: [],
			visible: false,
			treeData: [],
			selectedKeys: [], //选中树key值
			expandedKeys: [], // 默认展开的树节点
			departmentTableData: [],
			departmentCheckbox: [],
			roleTableData: [],
			roleCheckbox: [],
			basicHeight: 0,
			loading: false,
			checkedKeys: [],
			checkedRowData: [],
			copyCheckedRowData: [],
			departmentJurisdictionTableData: [], // 模板分组绑定科室权限列表数据
			departmentJurisdictionCheckbox: [], // 模板分组绑定科室选中数据
			groupingRowData: {}, // 病历模板分组点击科室权限
			templateVisible: false,
			DepartmentInformation: [], // 科室下拉框数据
			templateArrID: [], // 模板选中ID
			defaultTemplateVisible: false,
			defaultTemplateRowData: {}, // 默认模板行数据
			defaultTemplateDataSource: [], // 默认模板列表数据
			defaultTemplateSelectData: [], // 默认模板下拉框数据
			templateName: "",
			locType: "O^I^E^W^OI^OP"
		};
		this.columns = [{
			title: '分组代码',
			dataIndex: 'code',
			editable: true,
			align: "center",
			width: '150px',
		}, {
			title: '分组描述',
			dataIndex: 'descripts',
			align: "center",
			width: '150px',
			editable: true,
		}, {
			title: '创建人名称',
			dataIndex: 'createdUserDesc',
			align: "center",
			width: '100px',
		}, {
			title: '创建日期',
			dataIndex: 'createdDateTime',
			align: "center",
			width: '100px',
		}, {
			title: '最后修改人名称',
			dataIndex: 'updateUserDesc',
			align: "center",
			width: '100px',
		}, {
			title: '最后修改日期',
			dataIndex: 'updateDateTime',
			align: "center",
			width: '100px',
		}, {
			title: '操作',
			dataIndex: 'operation',
			align: "center",
			width: '150px',
			render: (text, record) => {
				const { editingKey } = this.state;
				const editable = this.isEditing(record);
				return editable ? (
					<span>
						<Icon type="form" style={{ color: '#108EE9' }}></Icon>
						<EditableContext.Consumer>
							{form => (
								<a
									onClick={() => this.handleSave(form, record)}
									style={{ marginRight: 8 }}
								>
									保存
								</a>
							)}
						</EditableContext.Consumer>
						<Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
						<Popconfirm title={record && record.ID ? "是否要取消编辑?" : "该数据没有保存是否确定取消?"} onConfirm={() => this.cancel(record)}>
							<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>取消</span>
						</Popconfirm>
					</span>
				) : (
					<div>
						<Icon type="edit" style={{ color: '#108EE9' }}></Icon>
						<span className='span' disabled={editingKey !== ''} onClick={(e) => this.handleCompile(record.key, e)}>
							编辑
						</span>
						<Divider type="vertical" />
						<Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
						<Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onClick={this.handlePopconfirm} onConfirm={() => this.handleDelete(record)}>
							<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
						</Popconfirm>
						<Divider type="vertical" />
						<span className='span' onClick={(e) => this.handleDepartmentAuthority(record, e)}>
							科室权限
						</span>
						<Divider type="vertical" />
						<span className='span' onClick={(e) => this.settingsDepartmentDefaultTemplate(record, e)}>
							科室默认模板
						</span>
					</div>
				);
			},
		}];
		this.departmentColumns = [{
			key: 2,
			title: '科室名称',
			dataIndex: 'locDesc',
			align: "center",
			width: 100
		}, {
			key: 3,
			title: '科室类型',
			dataIndex: 'locTypeDesc',
			align: "center",
			width: 100
		}];
		this.roleColumns = [{
			key: 1,
			title: '角色名称',
			dataIndex: 'Descripts',
			align: "center",
			width: 100
		}];
	}

	componentDidMount() {
		this.getTableData();
		this.getTreeData();
		this.getCaseTemplateSelectData();
		this.initDefaultValue()
	}

	// 获取病历模板下拉框数据
	getCaseTemplateSelectData = () => {
		let data = {
			params: [{}],
		}
		$http.post('urlS', this, {
			code: "06030002",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					this.setState({ caseTemplateSelectData: res.result, });
				}
			}
		})
	}

	// 点击删除时阻止事件冒泡
	handlePopconfirm = (e) => {
		e.stopPropagation();
	};

	// 获取病历模板分组数据
	getTableData = (ID) => {
		this.setState({ loading: true });
		let { pageSize, page } = this.state;
		let data = {
			params: [{

			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page
			}]
		}
		$http.post('urlS', this, {
			code: "06030001",
			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 + 1;
						res.result[i].createdDateTime = res.result[i].createdDate + ' ' + res.result[i].createdTime;
						res.result[i].updateDateTime = res.result[i].updateDate + ' ' + res.result[i].updateTime;
					}
					this.setState({ dataSource: res.result, total: res.totalNum, editingKey: '', rowId: ID ? ID : res.result[0].ID, loading: false }, () => {
						ID ? "" : this.getCaseTemplateTreeData();
						this.setState({ basicHeight: document.getElementById("template-grouping").clientHeight })
					});
				} else {
					this.setState({ loading: false })
				}
			}
		})
	}

	// 删除
	handleDelete = record => {
		if (record && record.ID) {
			let data = {
				params: [{
					ID: record.ID
				}]
			}
			$http.post('urlADS', this, {
				code: '06030006',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						message.success('删除成功');
						// 刷新列表数据
						this.getTableData();
					}
				}
			})
		} else { // 当ID值不存在时本地删除
			const dataSource = [...this.state.dataSource];
			this.setState({ dataSource: dataSource.filter(item => item.key !== record.key) });
		}
	};

	// 新增
	handleAdd = () => {
		const { dataSource } = this.state;
		let leg = dataSource && dataSource.length ? dataSource.length + 1 : 1
		const newData = {
			key: leg,
			code: undefined,
			descripts: undefined,
			createdUserDesc: undefined,
			createdDateTime: undefined,
			updateDateTime: undefined,
			updateUserDesc: undefined,
		};
		this.setState({
			dataSource: [...dataSource, newData],
		}, () => {
			if (!this.state.editingKey) {
				this.setState({ editingKey: leg })
			}
		});
	};

	isEditing = record => record.key === this.state.editingKey;

	// 取消
	cancel = (record) => {
		if (record && record.ID) {
			this.setState({ editingKey: '' });
		} else {
			this.handleDelete(record)
		}

	};

	addAndCompile = (row) => {
		let ID = row && row.ID ? row.ID : undefined;
		let data = {
			params: [{
				ID,
				code: row.code,
				descripts: row.descripts
			}]
		}
		$http.post('urlADS', this, {
			code: ID ? "06030005" : "06030004",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					// 成功提示
					message.success(ID ? '编辑成功' : '新增成功');
					this.getTableData(ID);
				}
			}
		})
	}

	// 保存
	handleSave = (form, record) => {
		form.validateFields((error, row) => {
			if (error) {
				return;
			}
			row.ID = record && record.ID ? record.ID : undefined;
			this.addAndCompile(row)
		});
	}

	getDisableData = (record) => {
		let arr = JSON.parse(JSON.stringify(this.state.dataSource));
		let disabledArr = [];
		arr = arr.filter(function (item) { return JSON.stringify(record) !== JSON.stringify(item) });
		for (var i = 0; i < arr.length; i++) {
			disabledArr = disabledArr.concat(arr[i] && arr[i].groupLinkLoc ? arr[i].groupLinkLoc : [])
		}
		return disabledArr;
	}

	// 科室权限
	handleDepartmentAuthority = (record, e) => {
		e.stopPropagation();
		this.setState({ visible: true, groupingRowData: record }, () => {
			if (!(this.state.departmentJurisdictionTableData && this.state.departmentJurisdictionTableData.length > 0)) {
				this.getDepartmentTableData("modal");
			} else {
				let departmentJurisdictionTableData = this.echoDisplayCheckboxData(this.state.departmentJurisdictionTableData, this.state.groupingRowData.groupLinkLoc, 'locID');
				this.setState({ departmentJurisdictionTableData }, () => {
					let disableArr = this.handleTemplateDisable(this.state.departmentJurisdictionTableData, this.getDisableData(this.state.groupingRowData));
					this.setState({ departmentJurisdictionTableData: disableArr })
				})
			}
		});
	}

	// 科室默认模板设置
	settingsDepartmentDefaultTemplate = (record, e) => {
		e.stopPropagation();
		this.setState({ defaultTemplateVisible: true, defaultTemplateRowData: record }, () => {
			this.getDefaultTemplateDataSource();
		});
	}

	// 编辑
	handleCompile = (key, e) => {
		e.stopPropagation();
		this.setState({ editingKey: key });
	}

	// 显示分页总条数
	showTotal(total) {
		return `共 ${total} 条`;
	}

	// 页码改变的回调，参数是改变后的页码及每页条
	onChangePage = (page, pageSize) => {
		this.setState({ page, pageSize }, () => {
			this.getTableData();
		})
	}

	// 条数改变的回调
	onChangePageSize = (current, size) => {
		this.setState({ page: 1, pageSize: size }, () => {
			this.getTableData();
		})
	}

	onClickRowPublic = (record) => {
		return {
			onDoubleClick: () => {
				this.setState({ rowId: record.ID }, () => {
					this.getCaseTemplateTreeData();
					this.resetCheckboxOperation();
				})
			}
		}
	}

	setRowClassNamePublic = (record) => {
		return record.ID === this.state.rowId ? 'clickRowStyle' : '';
	}

	// 处理tree数据
	filterTreeData = (treeData, childrenTitle) => {
		let data = treeData && treeData.map(item => {
			return {
				title: item.descripts,
				key: childrenTitle === 'subCatalog' ? item.ID : (item.treeType + item.ID),
				...item,
				// selectable: item.treeType&&item.treeType === "TEMPLATE" ? true : false,
				children: this.filterTreeData(childrenTitle === 'subCatalog' ? item.subCatalog : item.subCatalogue, childrenTitle)
			}
		});
		return data;
	}

	// 将check重置为true
	handleCheckStatus = (data) => {
		return data && data.map(item => {
			return {
				...item,
				check: false
			}
		})
	}

	// 清除操作痕迹
	resetCheckboxOperation = () => {
		let { departmentTableData, roleTableData } = this.state;

		this.setState({
			caseTemplateSelectedKeys: [], selectedKeys: [], expandedKeys: [],
			departmentTableData: this.handleCheckStatus(departmentTableData),
			roleTableData: this.handleCheckStatus(roleTableData),
		});
	}

	// 获取选中的模板树ID
	getTemplateArrID = (arr, type, collback) => {
		let arrLen = arr && arr.length ? arr : [];
		let filterArr = [];
		for (var i = 0; i < arrLen.length; i++) {
			if (type === 'getDataID') {
				filterArr.push(arr[i]?.ID);
			} else {
				filterArr.push(arr[i]?.templateID || arr[i]?.ID);
			}
		}
		if (type === 'getData' || type === 'getDataID') {
			return filterArr;
		} else {
			this.setState({ templateArrID: filterArr }, () => {
				collback && collback();
			});
		}
	}

	// 获取病历模板树数据
	getCaseTemplateTreeData = (fn) => {
		let { caseTemplateTreeSelectData } = this.state;
		let data = {
			params: [{
				groupID: this.state.rowId
			}]
		}
		$http.post('urlS', this, {
			code: "06030003",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = this.filterTreeData(res.result, 'subCatalog');
					this.setState({ caseTemplateTreeData: arr }, () => {
						// 点击树
						if (caseTemplateTreeSelectData && caseTemplateTreeSelectData.ID) {
							for (var i = 0; i < this.state.caseTemplateTreeData.length; i++) {
								if (this.state.caseTemplateTreeData[i].ID === caseTemplateTreeSelectData.ID) {
									let checkedRowData = this.state.caseTemplateTreeData[i].template
									this.setState({ checkedRowData, copyCheckedRowData: checkedRowData }, () => {
										this.getTemplateArrID(this.state.checkedRowData, '', fn)
									});
								} else if (this.state.caseTemplateTreeData[i].subCatalog && this.state.caseTemplateTreeData[i].subCatalog.length > 0) {
									for (var j = 0; j < this.state.caseTemplateTreeData[i].subCatalog.length; j++) {
										if (this.state.caseTemplateTreeData[i].subCatalog[j].ID === caseTemplateTreeSelectData.ID) {
											let checkedRowData = this.state.caseTemplateTreeData[i].subCatalog[j].template;
											this.setState({ checkedRowData, copyCheckedRowData: checkedRowData }, () => {
												this.getTemplateArrID(this.state.checkedRowData, '', fn)
											});
											return;
										}
									}
								}
							}
						}
					})
				} else {
					this.setState({ caseTemplateTreeData: [] })
				}
			},
			error: function () {
				this.setState({ caseTemplateTreeData: [] })
			}
		})
	}

	// 回显选中的科室及角色数据
	echoDisplayCheckboxData = (data, checkboxData, type) => {
		let arr = JSON.parse(JSON.stringify(data));
		if (checkboxData && checkboxData.length > 0) {
			for (var i = 0; i < arr.length; i++) {
				arr[i].check = false;
				for (var j = 0; j < checkboxData.length; j++) {
					if (+arr[i][type] === +checkboxData[j]) {
						arr[i].check = true;
					}
				}
			}
		} else {
			for (var i = 0; i < arr.length; i++) {
				arr[i].check = false;
			}
		}
		return arr;
	}

	// 将其他分组绑定过的科室置灰
	handleTemplateDisable = (data, disableArr) => {
		let arr = JSON.parse(JSON.stringify(data));
		console.dir(data)
		console.dir(disableArr)
		if (disableArr && disableArr.length > 0) {
			for (var i = 0; i < arr.length; i++) {
				arr[i].disabled = false;
				for (var j = 0; j < disableArr.length; j++) {
					if (+arr[i].locID === +disableArr[j]) {
						if (arr[i].locTypeCode !== "OI") {
							arr[i].disabled = true;
						}
					}
				}
			}
		} else {
			for (var i = 0; i < arr.length; i++) {
				arr[i].disabled = false;
			}
		}
		return arr;
	}

	renderTreeNodes = (data, childTitle) =>
		// childTitle === "subCatalog" ? (item.treeType === "TEMPLATE" ? true : false) : true
		data && data.map(item => {
			let type = childTitle === 'subCatalog' ? (item.parentID ? 'folder' : 'folder-open') : (item.treeType === 'CATALOG' ? 'folder-open' : (item.treeType === 'TEMPLATE' ? 'folder' : 'file'));
			let disableCheckbox = childTitle === "subCatalogue" && item.treeType !== 'TEMPLATE' ? true : false
			const index = item.title.indexOf(this.state.templateName);
			const beforeStr = item.title.substr(0, index);
			const afterStr = item.title.substr(index + this.state.templateName.length);
			const title = index > -1 ? (
				<span>
					{beforeStr}
					<span style={{ color: '#FF7F00' }}>{this.state.templateName}</span>
					{afterStr}
				</span>
			) : <span>{item.title}</span>;
			if (item.children) {
				return (
					<TreeNode icon={<Icon type={type} />} title={title} key={item.key} dataRef={item} disableCheckbox={disableCheckbox}>
						{this.renderTreeNodes(item.children, childTitle)}
					</TreeNode>
				);
			}
			return <TreeNode icon={<Icon type={type} />} title={title} key={item.key} dataRef={item} disableCheckbox={disableCheckbox} />;
		});

	// 新增分组目录数
	handleCaseTemplateTreeAddAndCompile = (flag) => {
		let { caseTemplateTreeSelectData, rowId } = this.state;
		if (!rowId) {
			return;
		}
		if (flag === 'compile' && !(caseTemplateTreeSelectData && caseTemplateTreeSelectData.ID)) {
			message.info("请选择一条需要编辑的数据");
			return;
		}
		this.groupedCatalogChild.showModal(flag, rowId, caseTemplateTreeSelectData, flag === 'compile' ? caseTemplateTreeSelectData : {});
	}

	// 删除分组目录树
	handleCaseTemplateTreeDelete = () => {
		let ID = this.state.caseTemplateTreeSelectData && this.state.caseTemplateTreeSelectData.ID ? this.state.caseTemplateTreeSelectData.ID : '';
		if (!ID) {
			message.info("请选择一条需要编辑的数据");
			return;
		}
		let data = {
			params: [{
				ID
			}]
		}
		$http.post('urlADS', this, {
			code: "06030009",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success('删除成功');
					// 刷新列表数据
					this.setState({ caseTemplateSelectedKeys: [], caseTemplateTreeSelectData: {} }, () => {
						this.resetCheckboxOperation();
						this.getCaseTemplateTreeData();
					})
				}
			}
		})
	}

	groupedCatalogRef = ref => {
		this.groupedCatalogChild = ref;
	}

	// 绑定模板
	handleBindingTemplate = (fn) => {
		let { caseTemplateTreeSelectData, templateArrID } = this.state;
		if (!(caseTemplateTreeSelectData && caseTemplateTreeSelectData.ID)) {
			message.info("请选中需要绑定的病历模板分组目录树");
			return;
		}
		if (fn && !(templateArrID && templateArrID.length > 0)) {
			message.info('请先勾选需要设置的模板！');
			return;
		}
		// 绑定模板ID
		// let ID = caseTemplateTreeSelectData.template&&caseTemplateTreeSelectData.template.length > 0 ? caseTemplateTreeSelectData.template[0].ID : undefined;
		let data = {
			params: [{
				HBEMRWTParRef: caseTemplateTreeSelectData.ID,
				templateID: templateArrID,
			}]
		}
		$http.post('urlADS', this, {
			code: "06030010",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					fn ? '' : message.success('绑定模板成功');
					// if (ID) {
					// 	caseTemplateTreeSelectData.template[0].ID = res.ID;
					// } else {
					// 	caseTemplateTreeSelectData.template = [];
					// 	let obj = {};
					// 	obj.ID = res.ID;
					// 	caseTemplateTreeSelectData.template.push(obj);
					// }
					// this.setState({caseTemplateTreeSelectData}, () => {
					this.getCaseTemplateTreeData(fn);
					// })
				}
			}
		})
	}

	// 获取tree数据
	getTreeData = () => {
		let data = {
			params: [{}]
		}
		$http.post('urlS', this, {
			code: "06020002",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = this.filterTreeData(res.result, 'subCatalogue');
					this.setState({ treeData: arr, selectedKeys: [], checkedKeys: [], copyCheckedRowData: [], checkedRowData: [], templateArrID: [] }, () => {
						this.generateList(this.state.treeData)
					})
				}
			}
		})
	}

	// 病历模板树树选中操作
	caseTemplateOnSelect = (keys, event) => {
		let dataRef = event.node.props.dataRef;
		let checkedKeys = []; // 绑定模板树选中keys
		let expandedKeys = [];
		let templateArrID = [];

		let template = dataRef.template && dataRef.template.length > 0 ? dataRef.template : [];
		for (var i = 0; i < template.length; i++) {
			checkedKeys.push("TEMPLATE" + template[i].templateID);
			templateArrID.push(template[i].templateID);
			expandedKeys = expandedKeys.concat(template[i].parentCatlog);
		}

		this.setState({ caseTemplateSelectedKeys: keys, checkedKeys, copyCheckedRowData: template, checkedRowData: template, templateArrID, expandedKeys }, () => {
			if (this.state.caseTemplateSelectedKeys && this.state.caseTemplateSelectedKeys.length > 0) {
				this.setState({ caseTemplateTreeSelectData: dataRef });
			} else {
				this.setState({ caseTemplateTreeSelectData: {} });
			}
		})
	}

	//模糊查询
	handleTemplateNameChange = e => {
		const templateName = e.target.value;
		const expandedKeys = this.dataList.map((item) => {
			if (templateName.length === 0) return null;
			if (item.title.indexOf(templateName) > -1) {
				return this.getParentKey(item.key, this.state.treeData);
			}
			return null;
		}).filter((item, i, self) => item && self.indexOf(item) === i);
		this.setState({
			expandedKeys,
			templateName: e.target.value,
			autoExpandParent: true,
		});
	}

	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;
	};

	//以下是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);
			}
		}
		// // 默认进来tree全部加载
		// const expandedKeys = this.dataList.map((item) => {
		// 	return this.getParentKey(item.key, this.state.treeData);
		// }).filter((item, i, self) => item && self.indexOf(item) === i);
		// this.setState({
		// 	expandedKeys,
		// });
	};

	// 病历模板树选中操作
	onSelect = (keys, event) => {
		this.setState({ selectedKeys: keys })
	};

	onExpand = expandedKeys => {
		this.setState({
			expandedKeys
		});
	}

	//查询默认数据
	initDefaultValue = () => {
		let data = {
			params: [{
				defaultAppObj: {
					EMRBaseConfiger: ['BasicCaseInformationFormLocType'],
				}
			}]
		}
		$http.post('urlS', this, {
			code: "04110023",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					const regex = /@/g;
					this.setState({
						// defaultValueObj: res.result,
						locType: res.result.BasicCaseInformationFormLocType ? (res.result.BasicCaseInformationFormLocType.replace(regex, '^')) : this.state.locType,
					})
				}
			}
		})
	}

	// 获取科室列表数据
	getDepartmentTableData = (flag) => {
		let { user, groupingRowData, locType, dbRowData } = this.state;
		let data = {
			params: [{
				hospID: flag === "modal" ? groupingRowData.hospID : user.hospID, // 所属医院
				locID: "", // 科室名称
				status: "", // 记录状态
				detailFlag: 1,
				type: locType,
				linkFlag: '',
				docFlag: ''
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1,
				sortColumn: "Describe",
				sortOrder: "asc"
			}]
		}
		$http.post('urlS', this, {
			code: "04020008",
			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 = res.result.Data[i].locID;
						res.result.Data[i].check = false;
						res.result.Data[i].disabled = false;
					}
					if (flag === "modal") {
						this.setState({ departmentJurisdictionTableData: res.result.Data }, () => {
							let departmentJurisdictionTableData = this.echoDisplayCheckboxData(this.state.departmentJurisdictionTableData, this.state.groupingRowData.groupLinkLoc, 'locID');
							this.setState({ departmentJurisdictionTableData }, () => {
								let disableArr = this.handleTemplateDisable(this.state.departmentJurisdictionTableData, this.getDisableData(this.state.groupingRowData));
								this.setState({ departmentJurisdictionTableData: disableArr })
							})
						});
					} else {
						this.setState({ departmentTableData: res.result.Data }, () => {
							if (dbRowData && 'locArray' in dbRowData && Array.isArray(dbRowData.locArray) && dbRowData.locArray.length > 0) {
								let departmentTableData = this.echoDisplayCheckboxData(this.state.departmentTableData, dbRowData.locArray, 'locID');
								this.setState({ departmentTableData, departmentCheckbox: dbRowData.locArray });
							}
						});
					}
				} else {
					if (flag === "modal") {
						this.setState({ departmentJurisdictionTableData: [] });
					} else {
						this.setState({ departmentTableData: [], departmentCheckbox: [] });
					}
				}
			}
		})
	}

	// 获取角色数据
	getRoleTableData = () => {
		let { dbRowData } = this.state;
		let data = {
			params: [{
				Descripts: "",
				PostDr: "", // 岗位
				Status: "", // 记录状态
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1,
				sortColumn: "Describe",
				sortOrder: "asc"
			}]
		}
		$http.post('urlS', this, {
			code: "2101",
			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 = res.result.Data[i].ID;
						res.result.Data[i].check = false;
					}
					this.setState({ roleTableData: res.result.Data }, () => {
						if (dbRowData && 'groupArray' in dbRowData && Array.isArray(dbRowData.groupArray) && dbRowData.groupArray.length > 0) {
							let roleTableData = this.echoDisplayCheckboxData(this.state.roleTableData, this.state.dbRowData?.groupArray || [], 'ID');;
							this.setState({ roleTableData, roleCheckbox: this.state.dbRowData?.groupArray || [] })
						}
					});
				} else {
					this.setState({ roleTableData: [], roleCheckbox: [] })
				}
			}
		})
	}

	// 保存科室权限/保存角色权限
	handleSaveAuthority = (type, save) => {
		let { checkedRowData, departmentCheckbox, roleCheckbox, dblclickTreeID, departmentTableData, roleTableData } = this.state;
		let ID = "";
		let template = checkedRowData && checkedRowData.length > 0 ? checkedRowData : [];
		for (var i = 0; i < template.length; i++) {
			if (template[i].templateID === dblclickTreeID) {
				ID = template[i].ID
				break;
			}
		}
		if (!ID) {
			message.info(`请选中需要绑定${type === 'loc' ? '科室' : '角色'}权限的病历模板分组目录数`);
			return;
		}
		let data = {
			params: [{
				locID: this.filterLocAndGroup(departmentCheckbox, 'loc'),
				groupID: this.filterLocAndGroup(roleCheckbox, 'role'),
				templateID: ID,
			}]
		}
		$http.post('urlADS', this, {
			code: type === "loc" ? "06040001" : "06040004",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					if (save) {
						// 清空选中科室以及角色
						this.setState({
							templateVisible: false,
							departmentTableData: this.handleCheckStatus(departmentTableData),
							roleTableData: this.handleCheckStatus(roleTableData),
						});
						this.getCaseTemplateTreeData()
					} else {
						message.success(`保存${type === 'loc' ? '科室' : '角色'}权限成功`);
						this.handleSaveAuthority(type === 'loc' ? "role" : "loc", true);
					}
				}
			}
		})
	}

	// 获取科室或者角色信息
	filterLocAndGroup = (dataSource, type) => {
		let filterArr = [];
		for (var i = 0; i < dataSource.length; i++) {
			if (type === "loc") {
				if (dataSource[i].locID) {
					filterArr.push(dataSource[i].locID)
				} else {
					filterArr.push(dataSource[i])
				}
			} else {
				if (dataSource[i].ID) {
					filterArr.push(dataSource[i].ID)
				} else {
					filterArr.push(dataSource[i])
				}
			}
		}
		return filterArr;
	}

	// 分组目录绑定模板check操作
	handleOnCheck = (checkedKeys, info) => {
		let { copyCheckedRowData } = this.state;
		let checkedRowData = [];
		let arr = info.checkedNodes && info.checkedNodes.length > 0 ? info.checkedNodes : [];
		let coypTemplateArr = this.getTemplateArrID(copyCheckedRowData, 'getData');
		for (var i = 0; i < arr.length; i++) {
			let ID = arr[i].props.dataRef.ID;
			if (coypTemplateArr.indexOf(ID) > -1) { // 取原数据
				for (var j = 0; j < copyCheckedRowData.length; j++) {
					if (copyCheckedRowData[j].templateID === ID) {
						checkedRowData.push(copyCheckedRowData[j]);
						break;
					}
				}
			} else {
				checkedRowData.push({
					...arr[i].props.dataRef,
					ID: undefined,
					templateID: ID
				});
			}
		}
		this.setState({ checkedKeys, checkedRowData, templateArrID: this.getTemplateArrID(checkedRowData, 'getData') })
	};

	// 关闭科室弹窗界面
	handleCancel = () => {
		this.setState({ visible: false })
	}

	// 确定设置权限
	handleOk = () => {
		let { groupingRowData, departmentJurisdictionCheckbox } = this.state;
		let arr = [];
		for (var i = 0; i < departmentJurisdictionCheckbox.length; i++) {
			arr.push(departmentJurisdictionCheckbox[i].locID)
		}
		let data = {
			params: [{
				HBEMRWGLParRef: groupingRowData.ID,
				// locID: arr.concat(groupingRowData.groupLinkLoc),
				locID: arr
			}]
		}
		$http.post('urlADS', this, {
			code: "06030025",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success("权限设置成功");
					this.handleCancel();
					this.getTableData(this.state.rowId);
				}
			}
		})
	}

	// 关闭设置模板权限
	handleTemplateCancel = () => {
		let { departmentTableData, roleTableData } = this.state;
		this.setState({
			templateVisible: false,
			departmentTableData: this.handleCheckStatus(departmentTableData),
			roleTableData: this.handleCheckStatus(roleTableData),
		});
	}

	// 双击分组目录绑定模板树
	dblclickTreeNodes = (status, record) => {
		let { checkedRowData } = this.state;
		let ID = record.props.dataRef.ID;
		let isError = true;
		console.log("checkedRowData", checkedRowData)
		for (var i = 0; i < checkedRowData.length; i++) {
			if (checkedRowData[i] && 'templateID' in checkedRowData[i] && checkedRowData[i].templateID === ID) {
				isError = !('ID' in checkedRowData[i] && checkedRowData[i].ID); // 绑定过则可以直接设置模板权限 - 勾选后需点击绑定模板
				break;
			} else {
				isError = true;
			}
		}
		if (isError) {
			message.error("请先将模板关联分组目录树，确认是否勾选后进行绑定模板操作！");
			return;
		}
		let obj = {};
		for (var i = 0; i < this.state.checkedRowData.length; i++) {
			if (this.state.checkedRowData[i].templateID === ID) {
				obj = this.state.checkedRowData[i]
				break;
			}
		}
		this.setState({ templateVisible: true, dbRowData: obj, dblclickTreeID: ID }, () => {
			if (!(this.state.departmentTableData && this.state.departmentTableData.length > 0)) {
				this.getDepartmentTableData()
			} else {
				let departmentTableData = this.echoDisplayCheckboxData(this.state.departmentTableData, obj.locArray, 'locID');
				this.setState({ departmentTableData, departmentCheckbox: obj.locArray });
			}
			if (!(this.state.roleTableData && this.state.roleTableData.length > 0)) {
				this.getRoleTableData()
			} else {
				let roleTableData = this.echoDisplayCheckboxData(this.state.roleTableData, obj.groupArray, 'ID');
				this.setState({ roleTableData, roleCheckbox: obj.groupArray });
			}
		})
	}

	// 关闭默认模板弹窗
	hiddenDefaultTemplate = () => {
		this.setState({ defaultTemplateVisible: false });
	}

	// 获取默认模板列表数据
	getDefaultTemplateDataSource = () => {
		let { defaultTemplateRowData } = this.state;
		let data = {
			params: [{
				eMRGroupID: defaultTemplateRowData && defaultTemplateRowData.ID ? defaultTemplateRowData.ID : ""
			}]
		}
		$http.post('urlADS', this, {
			code: "06010091",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ defaultTemplateDataSource: res.result.dataAry })
				}
			}
		})
	}

	// 获取默认模板下拉框数据
	getDefaultTemplateSelectData = (record) => {
		let { defaultTemplateRowData } = this.state;
		let data = {
			params: [{
				eMRGroupID: defaultTemplateRowData && defaultTemplateRowData.ID ? defaultTemplateRowData.ID : "",
				locID: record.locID
			}]
		}
		$http.post('urlADS', this, {
			code: "06010092",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ defaultTemplateSelectData: res.result.dataAry })
				}
			}
		})
	}

	// 默认模板操作
	handleDefaultTemplateChange = (record, e) => {
		let defaultTemplateDataSource = JSON.parse(JSON.stringify(this.state.defaultTemplateDataSource));
		for (var i = 0; i < defaultTemplateDataSource.length; i++) {
			if (defaultTemplateDataSource[i].locID === record.locID) {
				defaultTemplateDataSource[i].eMRTemplateID = e;
				break;
			}
		}
		this.setState({ defaultTemplateDataSource }, () => {
			this.saveDefaultTemplate(record, e)
		});
	}

	// 保存默认模板
	saveDefaultTemplate = (record, e) => {
		let data = {
			params: [{
				wGroupLinkLocID: record.groupLinkLocID,
				eMRWTemplateID: e
			}]
		}
		$http.post('urlADS', this, {
			code: "06010093",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success(res.errorMessage);
					this.getDefaultTemplateDataSource();
				}
			}
		})
	}

	// 批量设置权限
	handleBatchSettings = () => {
		let { dblclickTreeID } = this.state;
		if (dblclickTreeID !== 'batchSettings') {
			this.state.departmentCheckbox = [];
			this.state.roleCheckbox = [];
			this.state.dbRowData = {};
			this.state.dblclickTreeID = 'batchSettings';
		}
		this.setState({ templateVisible: true }, () => {
			if (!(this.state.departmentTableData && this.state.departmentTableData.length > 0)) {
				this.getDepartmentTableData()
			}
			if (!(this.state.roleTableData && this.state.roleTableData.length > 0)) {
				this.getRoleTableData()
			}
		})
	}

	// 确认批量设置
	handleConfirmSettings = async () => {
		try {
			let { departmentCheckbox, roleCheckbox, checkedRowData } = this.state;
			// console.log("params", checkedRowData);
			let data = {
				params: [{
					locID: this.filterLocAndGroup(departmentCheckbox, 'loc'),
					groupID: this.filterLocAndGroup(roleCheckbox, 'role'),
					templateID: this.getTemplateArrID(checkedRowData, 'getDataID'), // 获取分组目录绑定的模板ID
				}]
			}
			let res = await React.$asyncPost(this, '06040010', data);
			message.success(res?.errorMessage || '保存成功');
			this.handleTemplateCancel();
			this.getCaseTemplateTreeData();
		} catch (error) {
			console.log(error);
		}
	}

	render() {
		const { dataSource, caseTemplateSelectData, total, page, caseTemplateSelectedKeys, caseTemplateTreeData, treeData, selectedKeys, dblclickTreeID,
			expandedKeys, departmentTableData, roleTableData, basicHeight, checkedKeys, visible, departmentJurisdictionTableData, templateVisible,
			defaultTemplateVisible, defaultTemplateDataSource, defaultTemplateSelectData, templateName
		} = this.state;
		// 发药单位
		let caseTemplateOption = caseTemplateSelectData && caseTemplateSelectData.map((item, index) => {
			return (<Option key={index} value={item.descripts} title={item.descripts}>{item.descripts}</Option>)
		})
		const components = {
			body: {
				cell: EditableCell,
			},
		};

		const columns = this.columns.map(col => {
			if (!col.editable) {
				return col;
			}
			return {
				...col,
				onCell: record => ({
					record,
					dataIndex: col.dataIndex,
					title: col.title,
					option: caseTemplateOption,
					editing: this.isEditing(record),
				}),
			};
		});

		let departmentParams = {
			data: departmentTableData,
			columns: this.departmentColumns,
			height: store.getState().tableHeight.y + 174 - basicHeight + 'px',
			// 选中数据
			onChange: (filterData, data) => {
				this.setState({ departmentCheckbox: filterData, departmentTableData: data });
			}
		}

		// 发要明细当中的组件所需参数
		let roleParams = {
			data: roleTableData,
			columns: this.roleColumns,
			height: store.getState().tableHeight.y + 174 - basicHeight + 'px',
			// 选中数据
			onChange: (filterData, data) => {
				this.setState({ roleCheckbox: filterData, roleTableData: data })
			}
		}

		// 病历模板分组设置科室权限
		let departmentJurisdictionParams = {
			data: departmentJurisdictionTableData,
			columns: this.departmentColumns,
			height: store.getState().tableHeight.y + 174 - basicHeight + 'px',
			// 选中数据
			onChange: (filterData, data) => {
				this.setState({ departmentJurisdictionCheckbox: filterData, departmentJurisdictionTableData: data });
			}
		}

		let defaultTemplateOption = defaultTemplateSelectData && defaultTemplateSelectData.map((item, index) => {
			return <Option key={index} value={item.wtemplateID} title={item.templateDesc}>{item.templateDesc}</Option>
		})

		// 默认模板表头数据
		let defaultTemplateColumns = [
			{
				key: 1,
				title: '科室名称',
				dataIndex: 'locDesc',
				align: "center",
				width: "50%"
			},
			{
				key: 2,
				title: '默认模板',
				dataIndex: 'locDesc',
				align: "center",
				width: "50%",
				render: (text, record) => {
					return (<div>
						<Select style={{ width: "90%" }} onFocus={() => this.getDefaultTemplateSelectData(record)}
							value={record.eMRTemplateDesc} onChange={(e) => this.handleDefaultTemplateChange(record, e)}
						>
							{defaultTemplateOption}
						</Select>
					</div>)
				}
			}
		]

		return (
			<div className="basic-case-information">
				<div id="template-grouping">
					<Card
						size="small"
						title={<div className="card-title-left-icon">
							<div></div>
							病历模板分组
							<div style={{ float: 'right', marginRight: '12px' }}>
								<span onClick={this.handleAdd} style={{ color: 'rgba(77,193,130,1)', fontWeight: 900, fontSize: '14px', cursor: 'pointer' }}>新增</span>
							</div>
						</div>}
						className="card-title-bg"
					>
						<EditableContext.Provider value={this.props.form}>
							<Table
								style={{ maxHeight: '250px', overflow: 'auto' }}
								components={components}
								bordered
								dataSource={dataSource}
								columns={columns}
								// rowClassName="editable-row"
								pagination={false}
								onRow={this.onClickRowPublic}
								rowClassName={this.setRowClassNamePublic}
							/>
							<CommonPagination size="small" current={page} total={total} search="search"
								onShowSizeChange={this.onChangePageSize} complete={true} dataSource={dataSource}
								loading={this.state.loading} onChange={this.onChangePage} />
						</EditableContext.Provider>
					</Card>
				</div>
				<div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
				<Row>
					<Col span={12}>
						<Card
							size="small"
							title={<div className="card-title-left-icon">
								<div></div>
								病历模板分组目录树
								<div style={{ float: 'right', marginRight: '12px' }}>
									<span onClick={() => this.handleCaseTemplateTreeAddAndCompile("add")} style={{ color: 'rgba(77,193,130,1)', fontWeight: 900, fontSize: '14px', cursor: 'pointer' }}>新增</span>
									<Divider type="vertical" />
									<span onClick={() => this.handleCaseTemplateTreeAddAndCompile("compile")} style={{ color: '#1890ff', fontWeight: 900, fontSize: '14px', cursor: 'pointer' }}>编辑</span>
									<Divider type="vertical" />
									<span onClick={this.handleCaseTemplateTreeDelete} style={{ color: 'rgba(240,65,52,1)', fontWeight: 900, fontSize: '14px', cursor: 'pointer' }}>删除</span>
								</div>
							</div>}
							className="card-title-bg"
						>
							<Tree showIcon
								onSelect={this.caseTemplateOnSelect}
								selectedKeys={caseTemplateSelectedKeys}
								style={{ height: store.getState().tableHeight.y + 174 - basicHeight + 'px', overflow: 'auto' }}
							>
								{this.renderTreeNodes(caseTemplateTreeData, 'subCatalog')}
							</Tree>
						</Card>
					</Col>
					<Col span={12}>
						<div style={{ paddingLeft: '6px', position: 'relative' }}>
							<Card
								size="small"
								className="bci-right-card"
								title={<div className="card-title-left-icon">
									<div></div>
									分组目录绑定模板
									<Input style={{ marginLeft: '30px', width: '280px' }} placeholder="请输入内容查询" value={templateName} onChange={this.handleTemplateNameChange} />
									{/* <Divider type="vertical" /> */}
									{/* <span onClick={this.deleteBindingTemplate} style={{color: 'rgba(240,65,52,1)', fontWeight: 900, fontSize: '14px', cursor: 'pointer'}}>解除绑定</span> */}
								</div>}
								extra={
									<div>
										<span onClick={() => this.handleBindingTemplate('')} style={{ color: '#1890ff', fontWeight: 900, fontSize: '14px', cursor: 'pointer' }}>绑定模板</span>
										<Divider type="vertical" />
										<Popconfirm title="批量设置会覆盖之前保存的权限数据，确认批量设置吗?" onConfirm={() => this.handleBindingTemplate(this.handleBatchSettings)}>
											<span style={{ color: '#1890ff', fontWeight: 900, fontSize: '14px', cursor: 'pointer' }}>批量设置模板权限</span>
										</Popconfirm>
									</div>
								}
							>
								<Tree
									showIcon
									checkable
									onSelect={this.onSelect}
									selectedKeys={selectedKeys}
									checkedKeys={checkedKeys}
									onDoubleClick={this.dblclickTreeNodes}
									style={{ height: store.getState().tableHeight.y + 174 - basicHeight + 'px', overflow: 'auto' }}
									onExpand={this.onExpand}
									expandedKeys={expandedKeys}
									onCheck={this.handleOnCheck}
								>
									{this.renderTreeNodes(treeData, 'subCatalogue')}
								</Tree>
							</Card>
							<div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%' }}></div>
						</div>
					</Col>
				</Row>
				<GroupedCatalogTree onRef={this.groupedCatalogRef} handleQuery={this.getCaseTemplateTreeData} />
				<Modal
					title="科室权限设置"
					visible={visible}
					onOk={this.handleOk}
					onCancel={this.handleCancel}
				>
					<ProtogenesisTable params={departmentJurisdictionParams} />
				</Modal>
				<Modal
					width={900}
					okText="保存"
					title={dblclickTreeID === 'batchSettings' ? '批量设置模板权限' : '模板权限设置'}
					visible={templateVisible}
					onCancel={this.handleTemplateCancel}
					onOk={dblclickTreeID === 'batchSettings' ? this.handleConfirmSettings : () => this.handleSaveAuthority('loc')}
				>
					<Row>
						<Col span={12}>
							<Card
								size="small"
								title={<div className="card-title-left-icon">
									<div></div>
									分组模板绑定科室权限
									{/* <div style={{ float: 'right', marginRight: '12px', display: dblclickTreeID === 'batchSettings' ? 'none' : 'block' }}>
										<span onClick={() => this.handleSaveAuthority("loc")} style={{ color: '#1890ff', fontWeight: 900, fontSize: '14px', cursor: 'pointer' }}>保存科室权限</span>
									</div> */}
								</div>}
							>
								<ProtogenesisTable params={departmentParams} />
							</Card>
						</Col>
						<Col span={12}>
							<div style={{ paddingLeft: '24px', position: 'relative' }}>
								<Card
									size="small"
									title={<div className="card-title-left-icon">
										<div></div>
										分组模板绑定角色权限
										{/* <div style={{ float: 'right', marginRight: '12px', display: dblclickTreeID === 'batchSettings' ? 'none' : 'block' }}>
											<span onClick={() => this.handleSaveAuthority("role")} style={{ color: '#1890ff', fontWeight: 900, fontSize: '14px', cursor: 'pointer' }}>保存角色权限</span>
										</div> */}
									</div>}
								>
									<ProtogenesisTable params={roleParams} />
								</Card>
								<div style={{ width: '24px', background: '#fff', position: 'absolute', top: 0, left: 0, height: '100%' }}></div>
							</div>
						</Col>
					</Row>
				</Modal>
				<Modal
					title="科室默认模板设置"
					visible={defaultTemplateVisible}
					onCancel={this.hiddenDefaultTemplate}
					width={600}
					footer={null}
				>
					<div style={{ minHeight: "230px", maxHeight: "500px", overflow: "auto" }}>
						<Table
							bordered
							dataSource={defaultTemplateDataSource}
							columns={defaultTemplateColumns}
							pagination={false}
						/>
					</div>
				</Modal>
			</div>
		)
	}
};

const BasicCaseInformationForm = Form.create()(BasicCaseInformation);
export default BasicCaseInformationForm;