// 收费项维护
import React from 'react';
import { Table, Input, Row, Col, Button, Spin, Icon, Modal, Card, Switch, Select } from 'antd';
import { $http } from 'containers/config/https';
import { Util } from 'tools';
import store from 'store';
import MenuTaritmUpdata from './MenuTaritmUpdata'
import StandardClassification from './component/StandardClassification';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import '../../assets/css/system.css';
import '../../assets/css/App.css';

// 主菜单弹框
export default class EditableTable extends React.Component {
	constructor(props) {
		super(props);
		let userData = React.$getSessionData();
		this.state = {
			options: [],
			list: [],
			children: '',
			userInfo: {},
			sessionData: userData,
			Authoritydata: {},
			// 主菜单列表数据
			data: [],
			// 抽屉显示
			visible: true,
			// 主菜单-代码
			code: '',
			// 主菜单-描述
			describe: '',
			// 主菜单-分类
			FindType: '',
			// 主菜单-分类ID
			TypeID: '',
			// 主菜单-别名
			Alias: '',
			// 主菜单分页数据
			total: 0,
			page: 1,
			pageSize: 10,
			flag: '',
			title: '',
			// 是否显示loading
			showLoading: true,
			// 表格loading
			loading: false,
			selectrowid: '',
			ItemData: {},
			modalTypeVisible: false, // modalTypeVisible
			modalTypeSelectData1: [],
			modalTypeSelectData2: [],
			modalTypeSelectDataArr: [],
			newSelectDataArr: [],
			columns: [],
			languageTable1: {}, // 国际化Table1
			languageTable2: {}, // 国际化Table2
			languageData: {}, // 国际化语言包
			language: {},   // 国际化语言
			languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
			defaultFlag: 'Y',
			statusID: 'Y',
			statusSelectData: [{
				id: '',
				descripts: '全部'
			}, {
				id: 'Y',
				descripts: '生效'
			}, {
				id: 'N',
				descripts: '失效'
			}],
			exportLoading: false,
		};

		// this.columns = [
		//     {
		//         title: '序号',
		//         dataIndex: 'tind',
		//         width: '100px',
		//         align: "center",
		//         fixed: 'left',
		//     },
		//     {
		//         title: '代码',
		//         dataIndex: 'itemCode',
		//         width: '100px',
		//         align: "center",
		//         fixed: 'left',
		//     },
		//     {
		//         title: '描述',
		//         dataIndex: 'itemDesc',
		//         width: '100px',
		//         align: "center",
		//         fixed: 'left',
		//     },
		//     {
		//         title: '医院',
		//         dataIndex: 'itemHospDesc',
		//         width: '200px',
		//         align: "center",
		//         fixed: 'left',
		//     },
		//     {
		//         title: '单位',
		//         dataIndex: 'itemUnitDesc',
		//         width: '100px',
		//         align: "center"
		//     },
		//     {
		//         title: '价格',
		//         dataIndex: 'itemPrice',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '收费子类',
		//         dataIndex: 'itemTCsubDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '收费大类',
		//         dataIndex: 'itemTCDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '物价子类',
		//         dataIndex: 'itemPCsubDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '物价大类',
		//         dataIndex: 'itemPCDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '住院子类',
		//         dataIndex: 'itemICsubDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '住院大类',
		//         dataIndex: 'itemICDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '门诊子类',
		//         dataIndex: 'itemOCsubDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '门诊大类',
		//         dataIndex: 'itemOCDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '核算子类',
		//         dataIndex: 'itemECsubDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '核算大类',
		//         dataIndex: 'itemECDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '会计子类',
		//         dataIndex: 'itemACsubDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '会计大类',
		//         dataIndex: 'itemACDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '病案子类',
		//         dataIndex: 'itemMCsubDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '病案大类',
		//         dataIndex: 'itemMCDesc',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '备注',
		//         dataIndex: 'itemRemarks',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '开始日期',
		//         dataIndex: 'itemStDate',
		//         width: '100px',
		//         align: "center"
		//     },
		//     {
		//         title: '结束日期',
		//         dataIndex: 'itemEndDate',
		//         width: '100px',
		//         align: "center"
		//     },
		//     {
		//         title: '创建日期',
		//         dataIndex: 'itemCreateDate',
		//         width: '100px',
		//         align: "center"
		//     },
		//     {
		//         title: '创建时间',
		//         dataIndex: 'itemCreateTime',
		//         width: '100px',
		//         align: "center"
		//     },
		//     {
		//         title: '创建人员',
		//         dataIndex: 'itemCreateUser',
		//         width: '100px',
		//         align: "center"
		//     },
		//     {
		//         title: '项目内含',
		//         dataIndex: 'itemInClusion',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '除外内容',
		//         dataIndex: 'itemExCluded',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '收费说明',
		//         dataIndex: 'itemExplain',
		//         width: '200px',
		//         align: "center"
		//     },
		//     {
		//         title: '所属物价地区类型',
		//         dataIndex: 'itemRegionType',
		//         align: "center",
		//         width: '100px',
		//     },
		//     {
		//         title: 'Rowid',
		//         dataIndex: 'ID',
		//         width: '100px',
		//         align: "center",
		//         //fixed: 'left',
		//     },
		//     {
		//         title: 'hospItemID',
		//         dataIndex: 'hospItemID',
		//         width: '100px',
		//         align: "center",
		//         //fixed: 'left',
		//     }
		// ];
	}

	GetAuthority = () => {
		let data = {
			params: [{
				logonGroupID: this.state.sessionData.groupID,
				logonHospID: this.state.sessionData.hospID,
				dataType: "grid",
			}]
		}
		$http.post('urlS', this, {
			code: '01040002',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					this.setState({
						Authoritydata: res.result
					})
				}
			}
		})
	}

	componentDidMount() {
		this.tableList();
		this.GetAuthority() //获取权限
		// 数据异步请求，请求成功之后setState
		this.setState({
			showLoading: false
		})
		this.modalTypeSelectData1() // 获取子类下拉框数据
		// 初始化列表数据
		this.handleQuery();
	}

	// 新增
	handleAdd = () => {
		// 显示弹框 
		this.child.resetFields()
		this.setState({ ItemData: '' });
		this.child.showModal()
		// 初始化数据  
		this.setState({ flag: 'add', title: '新增' })
	}

	/**
	* @Byzxz: 分页BUG
	* 需求 #746
	* Create 2022-06-21
	* */
	// 查询
	handleQuery = () => {
		this.setState({ page: 1 }, () => {
			this.getTableDate()
		})
	}

	// 查询
	getTableDate = () => {
		this.setState({ loading: true });
		let { code, describe, page, pageSize, TypeID, Alias, defaultFlag, statusID } = this.state;
		let data = {
			params: [{
				code: code,
				descripts: describe,
				FindType: this.state.newSelectDataArr || [], // 分类,
				TypeID: TypeID,
				alias: Alias,
				include: "Hosp",
				groupID: this.state.sessionData.groupID,
				hospID: this.state.sessionData.hospID,
				HospFlag: defaultFlag,//是否本院
				statusID, // 生效标志
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page,
				sortColumn: "Code",
				sortOrder: "asc"
			}]
		}
		$http.post('urlS', this, {
			code: '05100081',
			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 = i
					}
					this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false })
				} else {
					this.setState({ data: [], total: 0, loading: false })
				}
			},
			error: function () {
				this.setState({ data: [], total: 0, loading: false })
			}
		})
	}
	// 导出
	exportData = () => {
		this.setState({ exportLoading: true });
		let { code, describe, page, pageSize, TypeID, Alias, defaultFlag, statusID } = this.state;
		let data = {
			params: [{
				code: code,
				descripts: describe,
				FindType: this.state.newSelectDataArr || [], // 分类,
				TypeID: TypeID,
				alias: Alias,
				include: "Hosp",
				groupID: this.state.sessionData.groupID,
				hospID: this.state.sessionData.hospID,
				HospFlag: defaultFlag,//是否本院
				statusID, // 生效标志
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page,
				sortColumn: "Code",
				sortOrder: "asc"
			}]
		}
		$http.post('urlS', this, {
			code: '05100412',
			data: data,
			success: function (res) {
				if (res.errorCode == '0') {
					this.setState({
						allPatData: res.FileURL,
						exportLoading: false,
					}, () => {
						// columns && columns.map((item, index) => {
						//   if (item.title.props && item.title.props) {
						//     columns[index].title = columns[index].title.props.children
						//   }
						// })
						//请求
						setTimeout(() => {
							this.setState({
								exportLoading: false,
							}, () => {
								this.downloadFile()
							})
							// handleExcel.exportExcel(columns, this.state.allPatData, '门诊日志表格')
						}, 1000)
					})
				} else {
					this.setState({
						exportLoading: false,
					})
				}
			},
		})
	}
	downloadFile() {
		let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
		try {
			var elemIF = document.createElement('iframe');

			elemIF.src = windowHost + this.state.allPatData;
			elemIF.style.display = 'none';

			document.body.appendChild(elemIF);

			// 防止下载两次

			setTimeout(function () {

				document.body.removeChild(elemIF)

			}, 1000);

		} catch (e) {

			console.log(e);

		}
	}
	// 查询条件 --- 代码
	onChangeCode = (e) => {
		this.setState({ code: e.target.value });
	}

	// 查询条件 --- 描述
	onChangeDescribe = (e) => {
		this.setState({ describe: e.target.value });
	}

	// 调用子组件的连接事件
	onRef = (ref) => {
		this.child = ref
	}

	// 设置行属性
	selectRow = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.selectrowid === "") {
					this.setState({
						selectrowid: record.tind,
					});
					this.child.resetFields()
					var titleTXT = record.itemDesc + "(" + record.itemCode + ")"
					this.setState({ ItemData: record, title: titleTXT + '     ----编辑', flag: 'TUpdate', })
					this.child.showModal()
				} else {
					if (this.state.selectrowid !== record.tind) {
						this.setState({
							selectrowid: record.tind,
						});
						this.child.resetFields()
						var titleTXT = record.itemDesc + "(" + record.itemCode + ")"
						this.setState({ ItemData: record, title: titleTXT + '     ----编辑', flag: 'TUpdate', })
						this.child.showModal()
					} else {
						this.setState({
							selectrowid: "",
						});
						this.child.resetFields()
						var titleTXT = record.itemDesc + "(" + record.itemCode + ")"
						this.setState({ ItemData: record, title: titleTXT + '     ----编辑', flag: 'TUpdate', })
						this.child.showModal()
					}
				}
			},
			// 双击行编辑
			// onClick: () => {

			//     this.child.resetFields()
			//     var titleTXT = record.itemDesc + "(" + record.itemCode + ")"
			//     this.setState({ ItemData: record, title: titleTXT + '     ----编辑', flag: 'TUpdate', })
			//     this.child.showModal()
			//     this.setState({
			//         selectrowid: record.Tind,
			//     });
			// },
		}
	}

	setRowClassName = (record) => {
		return record.tind === this.state.selectrowid ? 'clickRowStyle' : '';
	}

	onTypeChange = (value, selectedOptions) => {
		if (selectedOptions.length > 1) {
			this.setState({ FindType: selectedOptions[0].value });
			this.setState({ TypeID: selectedOptions[1].value });
		}
		else {
			this.setState({ FindType: '' });
			this.setState({ TypeID: '' });
		}
	}

	// 弹框打开
	modalType = () => {
		this.setState({
			modalTypeVisible: true
		})
	}

	modalTypeHandleCancel = () => {
		this.setState({
			modalTypeVisible: false

		}, () => {
			this.handleQuery() // 查询
		})
	}

	msg = (data) => {
		this.setState({
			newSelectDataArr: data,
		});
	}

	// 获取子类下拉框数据
	modalTypeSelectData1 = () => {
		let data = {
			params: [{
				hospID: "",
				tartype: 'SUB'
			}]
		}
		$http.post('urlS', this, {
			code: "05100011",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					var arr = []
					for (let i in res) {
						let o = {};
						o[i] = res[i];
						arr.push(o)
					}
					this.setState({ modalTypeSelectData1: arr }, () => {
						this.modalTypeSelectData2()
					})
				}
			}
		})
	}

	// 获取子类下拉框数据
	modalTypeSelectData2 = () => {
		let data = {
			params: [{
				hospID: "",
				tartype: ''
			}]
		}
		$http.post('urlS', this, {
			code: "05100011",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					var arr = []
					for (let i in res) {
						let o = {};
						o[i] = res[i];
						arr.push(o)
					}
					this.setState({ modalTypeSelectData2: arr }, () => {
						let modalTypeSelectDataArr = this.state.modalTypeSelectData1.concat(this.state.modalTypeSelectData2)
						let arrNew = []
						modalTypeSelectDataArr.forEach((v, i) => {
							Object.keys(v).forEach(v => {
								let o = {}
								o.name = v //取到了key
								o.val = modalTypeSelectDataArr[i][v] //取到了值
								arrNew.push(o)

							})
						})

						let arrNew1 = arrNew.filter((item, i) => {
							return Object.prototype.toString.call(item.val).indexOf('Array') !== -1    //过滤非数组
						})
						arrNew1.map((item, i) => {
							switch (item.name) {
								case "ACSUBData":
									item.label = '会计子类'
									break;
								case "ECSUBData":
									item.label = '核算子类'
									break;
								case "ICSUBData":
									item.label = '住院子类'
									break;
								case "MCSUBData":
									item.label = '病案子类'
									break;
								case "OCSUBData":
									item.label = '门诊子类'
									break;
								case "PCSUBData":
									item.label = '物价子类'
									break;
								case "TCSUBData":
									item.label = '收费子类'
									break;
								case "ACData":
									item.label = '会计科目'
									break;
								case "ECData":
									item.label = '核算项目分类'
									break;
								case "ICData":
									item.label = '住院收据费用'
									break;
								case "MCData":
									item.label = '病案分类'
									break;
								case "OCData":
									item.label = '门诊收据费用'
									break;
								case "PCData":
									item.label = '物价分类'
									break;
								case "TCData":
									item.label = '收费分类'
									break;
								default:
									break;
							}
						})
						this.setState({
							modalTypeSelectDataArr: arrNew1
						})

					})
				}
			}
		})
	}

	changeType = (e, index) => {
		let { modalTypeSelectDataArr } = this.state
		modalTypeSelectDataArr[index].id = e
		this.setState({
			modalTypeSelectDataArr: modalTypeSelectDataArr
		})
	}

	onColumnRef = (ref) => {
		console.log(ref)
		this.columnRef = ref;
	}

	// 获取主列表columns
	tableList = () => {
		var data = {
			params: [{
				"reactCode": ["MenuTaritmment"],
				"compontName": "MenuTaritmment",
				"type": "C"
			}]
		}
		console.log(1, data)
		$http.post('urlS', this, {
			code: '01040073',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let resC = res.result.C
					let { languageCode } = this.state
					for (var i = 0; i < resC.length; i++) {
						resC[i].key = i;
					}
					if (languageCode === "EN") {
						resC.map((item, i) => {
							item.title = item.enDescripts
						})
					}

					if (languageCode === "CN") {
						resC.map((item, i) => {
							item.title = item.descripts
						})
					}
					let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
						return {
							align: item.align,
							widthNum: parseInt(item.width),
							width: item.width,
							dataIndex: item.dataIndex,
							title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
							display: item.display,
							key: item.seqNo
						}
					}) : '';
					let filterArr = arr.filter(function (item) { return item.display === 'Y' });
					this.setState({
						columns: filterArr,
						languageTable1: res.result.B || {},  // 国际化Table1
						languageTable2: res.result.C || {},  // 国际化Table2
						languageData: res.result.language || {},  // 国际化语言包
					}, () => {
						this.LanCNEN(this.state.languageCode)
					})
				}
			}
		})
	}

	LanCNEN = (code) => {
		let { languageData } = this.state
		this.setState({
			language: languageData[code]
		})
	}

	// 页码改变的回调，参数是改变后的页码及每页条数
	appPageChange = (page, pageSize) => {
		this.setState({
			page: page,
			pageSize: pageSize,
		}, () => {
			// 重新调用查询方法
			this.getTableDate();
		});
	}

	// 条数改变的回调
	apponShowSizeChange = (current, size) => {
		this.setState({
			page: current,
			pageSize: size,
		}, () => {
			// 重新调用查询方法
			this.getTableDate();
		});
	}

	//是否默认
	onChangeSwith = (v, dataIndex) => {
		this.state[dataIndex] = v == true ? "Y" : "N";
		this.setState({}, () => {
			this.handleQuery()
		})
	}

	render() {
		let { language, languageCode, defaultFlag, statusSelectData, statusID } = this.state
		return (
			<div>
				<Spin tip={languageCode === "CN" ? "加载中..." : "Loading..."} spinning={this.state.showLoading}>
					<div>
						<Row>
							<Col span={10}>
								<div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
									<Card
										size="small"
										bordered={false}
										className="table-body-height"
										title={<div className="card-title-left-icon"><div></div>收费项列表</div>}
									>
										<div className="flex-wrap-align-items">
											<div style={{ marginBottom: '12px' }}>
												{language.MenuTaritmmentCodeDescAlias && language.MenuTaritmmentCodeDescAlias.descripts}：
												<Input
													placeholder={language.MenuTaritmmentCodeDescAlias && language.MenuTaritmmentCodeDescAlias.message}
													value={this.state.Alias}
													className="common-query-input"
													style={{ width: '300px' }}
													onChange={Util.commonInputChange.bind(this, 'Alias')}
													onPressEnter={this.handleQuery}
												/>
											</div>
											<div style={{ marginBottom: '12px' }}>
												状态：<Select
													allowClear
													showSearch
													placeholder="请选择"
													optionFilterProp="search"
													className="common-query-input"
													value={statusID}
													onChange={Util.handleSelectChange.bind(this, 'statusID')}
												>
													{React.$SelectOptions(statusSelectData)}
												</Select>
											</div>
											<div style={{ marginRight: '12px', marginBottom: '12px' }}>
												{language.MenuTaritmmentclassify && language.MenuTaritmmentclassify.descripts}：
												<Button
													onClick={() => this.modalType()}
												>
													<Icon type="file-add" />
													{languageCode === 'CN' ? "请选择" : 'Select'}
												</Button>
											</div>
											<div style={{ marginBottom: '12px' }}>
												本院：
												<Switch
													checkedChildren="是"
													unCheckedChildren="否"
													checked={defaultFlag == "Y" ? true : false}
													onChange={(v) => { this.onChangeSwith(v, 'defaultFlag') }}
												>
												</Switch>
											</div>
											<Button
												style={{ marginLeft: '30px', marginBottom: '12px' }}
												onClick={this.handleQuery}
											>
												{language.MenuTaritmmentquery && language.MenuTaritmmentquery.descripts}
											</Button>
											<Button type="primary" style={{ marginLeft: '30px', marginBottom: '12px' }} disabled={Util.isEmpty(this.state.data)} loading={this.state.exportLoading}
												onClick={this.exportData}>导出</Button>
										</div>
										<div>
											<Table
												style={{ height: store.getState().tableHeight.y + 50 + 'px' }}
												dataSource={this.state.data}
												columns={this.state.columns}
												className='TableA'
												//rowClassName="editable-row"
												pagination={false}
												scroll={{ x: '5200px', y: store.getState().tableHeight.y }}
												bordered
												loading={this.state.loading}
												onRow={this.selectRow}
												rowClassName={this.setRowClassName}
											/>
											<CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
												onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.data}
												onChange={this.appPageChange} />
											<ColumnAuthoritysModel
												clientWidth='900px'
												compontName='MenuTaritmment'
												configType="C"
												onRef={this.onColumnRef}
												reloadData={this.tableList}
											/>
										</div>
									</Card>
									<div className="common-card-right-split-line" style={{ width: 8 }}></div>
								</div>
							</Col>
							<Col span={14}>
								<div style={{ paddingLeft: '6px', position: 'relative' }}>
									<Card
										size="small"
										bordered={false}
										title={<div className="card-title-left-icon"><div></div>编辑收费项</div>}
										tabIndex={1}
										style={{ outline: 'none' }}
									>
										<div style={{ height: store.getState().tableHeight.y + 181 + 'px', overflow: 'auto' }}>
											<MenuTaritmUpdata
												//size="small"
												onRef={this.onRef}
												ItemData={this.state.ItemData}
												ChargeItemID={this.state.ChargeItemID}
												flag={this.state.flag}
												handelThis={this}
												title={this.state.title}
												Authoritydata={this.state.Authoritydata}
												key={this.state.ChargeItemID}
												getTableDate={this.getTableDate}
											/>
										</div>
									</Card>
								</div>
							</Col>
						</Row>
					</div>
				</Spin>
				<Modal
					visible={this.state.modalTypeVisible}
					title={languageCode === "CN" ? '标准分类' : "Standard Classification"}
					onCancel={this.modalTypeHandleCancel}
					onOk={this.modalTypeHandleCancel}
					width='900px'
				>
					<StandardClassification msg={this.msg} hospID={true} />
				</Modal>
				{/* 新增弹框 */}
			</div>
		);
	}
}