/*
 * Creater:     gjg
 * CreateDate:  2022/05/19
 * Describe：   科室医嘱插入配置
 * */
import React, { Component } from 'react';
import { Row, Col, Input, Select, Button, Card, message, Popconfirm, Divider, Icon } from 'antd';
import store from 'store';
import { Util } from 'tools';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import iconListvisits from 'assets/images/icon_listvisits.png';
import { $http } from '../../containers/config/https';

class RegTriageLocMedItem extends Component {
	constructor(props) {
		super(props);
		this.state = {
			desc: undefined, // 模糊搜索条件
			status: undefined,
			mainTableData: [],
			mainFormData: [], // 主表表单数据
			mainTotal: 0,
			mainPage: 1,
			mainPageSize: 20,
			mainLoading: false,
			rowID: '',
			rowData: {},
			detailTableData: [],
			detailFormData: [], // 明细表单数据
			detailTotal: 0,
			detailPage: 1,
			detailPageSize: 20,
			detailLoading: false,
			detailRowData: {},
			locArr: [],
			statusArr: [],
			medTypeArr: [],
			ICDSelectData: [],
			ICDFormData: [],
			itemSelectData: []
		};
		// 主表表头数据
		this.mainColumns = [{
			key: 1,
			title: '代码',
			dataIndex: 'code',
			align: "center",
			width: "100px"
		}, {
			key: 2,
			title: '名称',
			dataIndex: 'descripts',
			align: "center",
			width: "200px"
		}, {
			key: 3,
			title: '医院描述',
			dataIndex: 'hospDesc',
			align: "center",
			width: "200px"
		}, {
			key: 4,
			title: '科室描述',
			dataIndex: 'locDesc',
			align: "center",
			width: "200px"
		}, {
			key: 5,
			title: '单行字段数',
			dataIndex: 'fieldNum',
			align: "center",
			width: "100px"
		}, {
			key: 6,
			title: 'ICD代码',
			dataIndex: 'iCDCode',
			align: "center",
			width: "200px"
		}, {
			key: 7,
			title: 'ICD诊断',
			dataIndex: 'iCDDesc',
			align: "center",
			width: "300px"
		}, {
			key: 8,
			title: '生效时间',
			dataIndex: 'startDate',
			align: "center",
			width: "100px"
		}, {
			key: 9,
			title: '失效时间',
			dataIndex: 'stopDate',
			align: "center",
			width: "100px"
		}];
		// 明细表头数据
		this.detailColumns = [{
			key: 1,
			title: '顺序号',
			dataIndex: 'seqNo',
			align: "center",
			width: "80px"
		}, {
			key: 2,
			title: '类型',
			dataIndex: 'typeDesc',
			align: "center",
			width: "100px"
		}, {
			key: 3,
			title: '项目诊断',
			dataIndex: 'itemDesc',
			align: "center",
			width: "200px"
		}, {
			key: 4,
			title: 'ICD诊断',
			dataIndex: 'iCDDesc',
			align: "center",
			width: "320px"
		}, {
			key: 5,
			title: '开始时间',
			dataIndex: 'startDate',
			align: "center",
			width: "100px"
		}, {
			key: 6,
			title: '结束时间',
			dataIndex: 'stopDate',
			align: "center",
			width: "100px"
		}, {
			key: 7,
			title: '操作',
			dataIndex: 'opertion',
			align: 'center',
			width: "150px",
			fixed: 'right',
			render: (text, data) => {
				return (
					<span>
						<Icon type="edit" style={{ color: '#108EE9' }}></Icon>
						<span className='span' onClick={() => this.handleDetailModify(data)}>编辑</span>
						<Divider type="vertical" />
						<Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
						<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDetailDelete(data)} >
							<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
						</Popconfirm>
					</span >
				)
			}
		}];
	}

	componentDidMount() {
		this.handleQuery();
		this.getSeleceData();
	}

	handleQuery = () => {
		this.setState({ mainPage: 1, mainLoading: true, rowID: '', detailTableData: [], detailTotal: 0 }, () => {
			this.getTableData();
		})
	}

	// 请求下拉数据
	getSeleceData = async () => {
		try {
			let res = await React.$asyncPost(this, '01040260');
			this.setState({ locArr: res.result.loc, statusArr: res.result.status, medTypeArr: res.result.medType }, () => {
				this.getMainFormData(); // 获取主表表单数据
				this.getDetailFormData(); // 获取明细表表单数据
			});
		} catch (error) {
			this.setState({ mainTableData: [], mainTotal: 0, mainLoading: false })
		}
	}

	// ICD诊断搜索
	handleChargeSearch = (value, dataSource, index) => {
		this.state[dataSource][index].loading = true;
		this.setState({})
		this.fetchCharge(value, ICDSelectData => this.setState({ ICDSelectData }, () => {
			this.state[dataSource][index].loading = false;
			this.getDetailFormData();
			this.getMainFormData();
		}));
	}

	fetchCharge = (value, callback) => {
		value = value.replace(/^\s+/, "").replace(/\s+$/, "");
		if (value === "") {
			let resData = [];
			callback(resData);
			return;
		}
		if (this.timeout) {
			clearTimeout(this.timeout);
			this.timeout = null;
		}
		function fakeCharge() {
			let data = {
				params: [{
					desc: value
				}]
			}
			$http.post('urlS', this, {
				code: "01040268",
				data,
				success: function (res) {
					if (res.errorCode === '0') {
						// 按照接口返回数据截取前1000条，数据多了会导致下拉框卡死效果，建议精准搜索
						let resultData = res.result && 'rows' in res.result && Array.isArray(res.result.rows) ? res.result.rows.slice(0, 1000) : [];
						callback(resultData);
					}
				}
			});
		}
		this.timeout = setTimeout(fakeCharge, 500);
	}

	// 项目诊断
	handleItemChargeSearch = (value) => {
		let formValues = this.detailModalRef?.getFieldsValue();
		this.state.detailFormData[2].loading = true;
		this.setState({})
		this.fetchChargeItem(value, formValues?.type, itemSelectData => this.setState({ itemSelectData }, () => {
			this.state.detailFormData[2].loading = false;
			this.getDetailFormData();
		}));
	}

	fetchChargeItem = (value, type, callback) => {
		value = value.replace(/^\s+/, "").replace(/\s+$/, "");
		if (value === "") {
			let resData = [];
			callback(resData);
			return;
		}
		if (this.timeout) {
			clearTimeout(this.timeout);
			this.timeout = null;
		}
		function fakeCharge() {
			let data = {
				params: [{
					desc: value,
					type
				}]
			}
			$http.post('urlS', this, {
				code: "01040267",
				data,
				success: function (res) {
					if (res.errorCode === '0') {
						// 按照接口返回数据截取前1000条，数据多了会导致下拉框卡死效果，建议精准搜索
						let resultData = res.result && 'rows' in res.result && Array.isArray(res.result.rows) ? res.result.rows.slice(0, 1000) : [];
						callback(resultData);
					}
				}
			});
		}
		this.timeout = setTimeout(fakeCharge, 300);
	}

	// 获取主表表单数据
	getMainFormData = () => {
		let mainFormData = [{
			dataIndex: 'code',
			title: '代码',
			typeCode: 'Input',
			required: 'Y'
		}, {
			dataIndex: 'descripts',
			title: '描述',
			typeCode: 'Input',
			required: 'Y'
		}, {
			dataIndex: 'locID',
			title: '科室',
			typeCode: 'Select',
			required: 'Y',
			detailItem: this.state.locArr || []
		}, {
			dataIndex: 'fieldNum',
			title: '单行字段数',
			typeCode: 'Input'
		}, {
			dataIndex: 'iCDDesc',
			title: 'ICD诊断',
			typeCode: 'SearchSelect',
			valueindex: 'descripts', // 下拉value对应的值
			valueID: 'iCDID', // 选择的valueID
			onSearch: (e) => this.handleChargeSearch(e, 'mainFormData', 4),
			detailItem: this.state.ICDSelectData,
			loading: false
		},
		{
			dataIndex: 'startDate',
			title: '开始日期',
			typeCode: 'Date',
			required: 'Y',
			default: 0,
		}, {
			dataIndex: 'stopDate',
			title: '结束日期',
			typeCode: 'Date'
		}];
		this.setState({ mainFormData })
	}

	// 提供修改page和pageSize的回调函数
	handleCompilePage = (page, pageSize) => {
		// 修改page，或者pageSize
		this.setState({ mainPage: page, mainPageSize: pageSize, mainLoading: true, rowID: '', detailTableData: [], detailTotal: 0 }, () => {
			// 重新调用查询方法
			this.getTableData();
		})
	}

	// 请求列表数据
	getTableData = async () => {
		try {
			let { desc, status, mainPage, mainPageSize } = this.state;
			let data = {
				params: [{
					desc,
					status
				}],
				pagination: [{
					pageSize: mainPageSize,
					currentPage: mainPage
				}]
			}
			let res = await React.$asyncPost(this, '01040261', data);
			let mainTableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
			this.setState({ mainTableData, mainTotal: res.result.total, mainLoading: false });
		} catch (error) {
			this.setState({ mainTableData: [], mainTotal: 0, mainLoading: false })
		}
	}

	// 新增医院组信息
	handleAdd = () => {
		let { rowData } = this.state;
		if (rowData && 'regTriageLocID' in rowData && rowData.regTriageLocID) {
			this.setState({ rowData: {} })
		}
		this.mainModalRef && this.mainModalRef.modifyVisible(true);
	}

	// 编辑
	handleModify = (record, e) => {
		e?.stopPropagation();
		this.setState({ rowData: record }, () => {
			this.mainModalRef && this.mainModalRef.modifyVisible(true);
		})
	}

	// 删除
	handleDelete = async (record, e) => {
		this.handlePopconfirm(e);
		try {
			if (!(record && record.regTriageLocID)) return;
			let { rowID } = this.state;
			let data = {
				params: [{
					regTriageLocID: record?.regTriageLocID
				}]
			}
			let res = await React.$asyncPost(this, '01040265', data);
			message.success(res.errorMessage ? res.errorMessage : '删除成功');
			if (record.regTriageLocID === rowID) {
				this.setState({ rowID: '', detailTableData: [], detailTotal: 0 })
			}
			this.getTableData();
		} catch (error) {
			console.log(error)
		}
	}

	handleDetailDelete = async record => {
		try {
			if (!(record && record.regTriageLocMedItemID)) return;
			let data = {
				params: [{
					regTriageLocMedItemID: record?.regTriageLocMedItemID
				}]
			}
			let res = await React.$asyncPost(this, '01040266', data);
			message.success(res.errorMessage ? res.errorMessage : '删除成功');
			this.getDetailTableData();
		} catch (error) {
			console.log(error)
		}
	}

	// 记录表单的值
	recordMainFormInput = record => {
		this.setState({ rowData: { ...this.state.rowData, ...record } })
	}

	// 主表保存
	handleMainSave = async values => {
		try {
			let { rowData } = this.state;
			let data = {
				params: [{
					...values,
					regTriageLocID: rowData?.regTriageLocID
				}]
			}
			let res = await React.$asyncPost(this, '01040262', data);
			message.success(res.errorMessage ? res.errorMessage : '保存成功');
			this.mainModalRef && this.mainModalRef.modifyVisible(false, 'Y');
			this.setState({ rowData: {} }, () => {
				this.getTableData();
			});
		} catch (error) {
			this.setState({ tableData: [], mainTotal: 0, loading: false })
		}
	}

	// 操作行
	onClickRowPublic = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.rowID === '') {
					// 保存行数据以及ID
					this.setState({ rowID: record.regTriageLocID }, () => {
						this.getDetailTableData()
					});
				} else {
					if (this.state.rowID !== record.regTriageLocID) {
						this.setState({ rowID: record.regTriageLocID }, () => {
							this.getDetailTableData()
						});
					} else {
						this.setState({ rowID: "", detailTableData: [], detailTotal: 0, detailLoading: false });
					}
				}
			}
		}
	}

	// 选中行操作
	setRowClassNamePublic = (record) => {
		return record.regTriageLocID === this.state.rowID ? 'clickRowStyle' : '';
	}

	// 提供修改page和pageSize的回调函数
	handleDetailCompilePage = (page, pageSize) => {
		// 修改page，或者pageSize
		this.setState({ detailPage: page, detailPageSize: pageSize, detailLoading: true }, () => {
			// 重新调用查询方法
			this.getDetailTableData();
		})
	}

	// 获取主表表单数据
	getDetailFormData = () => {
		let detailFormData = [{
			dataIndex: 'seqNo',
			title: '序号',
			typeCode: 'Input',
		}, {
			dataIndex: 'type',
			title: '类型',
			typeCode: 'Select',
			detailItem: this.state.medTypeArr || [],
			required: 'Y',
			callBackResult: 'Fn',
			changeCallBack: this.handleTypeChange
		}, {
			dataIndex: 'itemDesc',
			title: '项目诊断',
			typeCode: 'SearchSelect',
			valueindex: 'descripts', // 显示在界面上的值 -> 对应下拉数据返回的描述
			valueID: 'itemID', // 需要存到后台的字段对应的id值
			onSearch: this.handleItemChargeSearch,
			detailItem: this.state.itemSelectData,
			loading: false
		}, {
			dataIndex: 'iCDDesc',
			title: 'ICD诊断',
			typeCode: 'SearchSelect',
			valueindex: 'descripts', // 显示在界面上的值 -> 对应下拉数据返回的描述
			valueID: 'iCDID', // 需要存到后台的字段对应的id值
			onSearch: (e) => this.handleChargeSearch(e, 'detailFormData', 3),
			detailItem: this.state.ICDSelectData,
			loading: false
		},
		{
			dataIndex: 'startDate',
			title: '开始日期',
			typeCode: 'Date',
			required: 'Y',
			default: 0,
		}, {
			dataIndex: 'stopDate',
			title: '结束日期',
			typeCode: 'Date'
		}];
		this.setState({ detailFormData })
	}

	// 类型change事件
	handleTypeChange = (e) => {
		this.detailModalRef && this.detailModalRef.setFieldsValue({
			itemDesc: undefined
		});
		this.setState({ itemSelectData: [] }, () => {
			this.getDetailFormData();
		})
	}

	// 获取明细列表数据
	getDetailTableData = async () => {
		try {
			let data = {
				params: [{
					regTriageLocID: this.state.rowID
				}]
			}
			let res = await React.$asyncPost(this, '01040263', data);
			let detailTableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
			this.setState({ detailTableData, detailTotal: res.result.total, detailLoading: false });
		} catch (error) {
			this.setState({ detailTableData: [], detailTotal: 0, detailLoading: false })
		}
	}

	// 记录表单的值
	recordDetailFormInput = record => {
		this.setState({ detailRowData: { ...this.state.detailRowData, ...record } })
	}

	// 添加明细
	handleDetailAdd = () => {
		let { rowID } = this.state;
		if (rowID === '') {
			message.info('请选中一条主记录后再添加！')
			return
		}
		let { detailRowData } = this.state;
		if (detailRowData && 'regTriageLocID' in detailRowData && detailRowData.regTriageLocID) {
			this.setState({ detailRowData: {} })
		}
		this.detailModalRef && this.detailModalRef.modifyVisible(true);
	}

	// 编辑
	handleDetailModify = record => {
		this.setState({ detailRowData: record }, () => {
			this.detailModalRef && this.detailModalRef.modifyVisible(true);
		})
	}

	// 明细保存
	handleDetailSave = async values => {
		try {
			let { rowID, detailRowData } = this.state;
			let data = {
				params: [{
					...values,
					regTriageLocMedItemID: detailRowData.regTriageLocMedItemID || '',
					regTriageLocID: rowID
				}]
			}
			let res = await React.$asyncPost(this, '01040264', data);
			message.success(res.errorMessage ? res.errorMessage : '保存成功');
			this.detailModalRef && this.detailModalRef.modifyVisible(false, 'Y');
			this.setState({ detailRowData: {} }, () => {
				this.getDetailTableData();
			});
		} catch (error) {
			this.setState({ detailTableData: [], detailTotal: 0, detailLoading: false })
		}
	}

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

	render() {
		let { desc, status, statusArr, mainFormData, rowData, mainTableData, mainTotal, mainPage, mainLoading, detailTableData, detailTotal, detailPage, detailLoading, detailFormData,
			detailRowData,
		} = this.state;

		// 主表操作信息
		let mainOpertion = {
			key: 11,
			title: '操作',
			dataIndex: 'opertion',
			align: 'center',
			width: "150px",
			fixed: 'right',
			render: (text, data) => {
				return (
					<span>
						<Icon type="edit" style={{ color: '#108EE9' }}></Icon>
						<span className='span' onClick={(e) => this.handleModify(data, 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={(e) => this.handleDelete(data, e)} >
							<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
						</Popconfirm>
					</span >
				)
			}
		}

		// 组件所需参数
		const mainParam = {
			// 表头配置
			columns: [...this.mainColumns, mainOpertion],
			// 表格数据
			data: mainTableData,
			// 数据总条数
			total: mainTotal,
			// 当前页数
			page: mainPage,
			pageSize: "20",
			// 表格的宽度
			x: 1400,
			y: store.getState().tableHeight.y + 47,
			height: store.getState().tableHeight.y + 97 + "px",
			isOnRow: true,
			rowClassName: true,
			loading: mainLoading,
		};

		const detailParam = {
			// 表头配置
			columns: this.detailColumns,
			// 表格数据
			data: detailTableData,
			// 数据总条数
			total: detailTotal,
			// 当前页数
			page: detailPage,
			pageSize: '20',
			x: 900,
			y: store.getState().tableHeight.y + 47,
			height: store.getState().tableHeight.y + 97 + 'px',
			loading: detailLoading,
		};
		return (
			<div>
				<Row>
					<Col span={12}>
						<div style={{ paddingRight: '6px', position: 'relative' }}>
							<Card
								size="small"
								title={
									<div className='card-title-left-img'>
										<img src={iconListvisits} alt='' />
										科室医嘱列表
									</div>
								}
							>
								<div className='table-body-height'>
									<div style={{ marginBottom: '12px' }}>
										代码/描述：<Input title="输入内容后可回车检索" placeholder="请输入( Enter )"
											value={desc} onChange={Util.commonInputChange.bind(this, 'desc')} onPressEnter={this.handleQuery}
											style={{ width: '150px', marginRight: '15px' }}
										/>
										状态：<Select
											allowClear
											showSearch
											optionFilterProp="seachprop"
											placeholder="状态"
											value={status}
											onChange={Util.handleSelectChange.bind(this, 'status')}
											style={{ width: '150px', marginRight: '20px' }}
										>
											{statusArr && statusArr.length > 0 ? React.$SelectOptions(statusArr) : ''}
										</Select>
										<Button onClick={this.handleQuery}>查询</Button>
										<Button
											className="add-btn-nohover"
											icon="plus"
											style={{ background: 'rgba(247,128,93,1)', color: '#fff', float: 'right' }}
											onClick={this.handleAdd}
										>新增</Button>
									</div>
									<PubilcTablePagination
										param={mainParam}
										compilePage={this.handleCompilePage}
										onClickRowPublic={this.onClickRowPublic}
										setRowClassNamePublic={this.setRowClassNamePublic}
									/>
								</div>
							</Card>
							<div
								style={{
									width: '6px',
									background: 'rgba(240, 242, 245, 1)',
									position: 'absolute',
									top: 0,
									right: 0,
									height: '100%',
								}}
							></div>
						</div>
					</Col>
					<Col span={12}>
						<Card
							size="small"
							title={
								<div className='card-title-left-img'>
									<img src={iconListvisits} alt='' />
									关联医嘱列表
								</div>
							}
						>
							<div className='table-body-height'>
								<div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between' }}>
									<div>
									</div>
									<div>
										<Button
											className="add-btn-nohover"
											icon="plus"
											style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}
											onClick={this.handleDetailAdd}
										>新增</Button>
									</div>
								</div>
								<PubilcTablePagination
									param={detailParam}
									compilePage={this.handleDetailCompilePage}
								/>
							</div>
						</Card>
					</Col>
				</Row>

				{/* 主表新增弹窗 */}
				<PublicModalFormHooks
					onRef={ref => this.mainModalRef = ref}
					formData={mainFormData}
					rowData={rowData}
					formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
					recordFormInput={this.recordMainFormInput}
					handleSave={this.handleMainSave}
				/>

				{/* 明细新增弹窗 */}
				<PublicModalFormHooks
					onRef={ref => this.detailModalRef = ref}
					formData={detailFormData}
					rowData={detailRowData}
					formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
					recordFormInput={this.recordDetailFormInput}
					handleSave={this.handleDetailSave}
				/>
			</div>
		)
	}
};

export default RegTriageLocMedItem;