// 科室信息
import React from 'react';
import { Select, Row, Col, Button, Spin, Divider, Popconfirm, message, Icon } from 'antd';
import { $http } from '../../containers/config/https';
import store from 'store';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx'; // 公共table组件
import CommonLibraryImport from './common/CommonLibraryImport.jsx'; // 	公共库导入
import 'assets/css/common.css'

const { Option } = Select;
let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};

export default class DepartmentInformation extends React.Component {

	constructor({ history }) {
		super();
		this.history = history;
		this.state = {
			// 所属医院
			hospitalId: undefined,
			// 科室名称
			locDesc: undefined,
			// 记录状态
			status: undefined,
			// 科室类型
			locType: undefined,
			//重点专科级别
			specialtyGradeId: undefined,
			// 表格数据
			tableData: [],
			// 表格数据总条数
			total: 0,
			showLoading: true,
			page: 1,
			pageSize: 20,
			selectData: {}, // 科室信息下拉框数据
			DepartmentInformation: [], // 科室名称下拉框
			hospitalData: [], // 所属医院
			headerHeight: 0,
			loading: false
		};
		this.columns = [
			{
				key: 0,
				title: '科室ID',
				dataIndex: 'locID',
				align: "center",
				width: '50'
			},
			{
				key: 1,
				title: '科室代码',
				dataIndex: 'locCode',
				align: "center",
				width: '10%'
			},
			{
				key: 2,
				title: '科室名称',
				dataIndex: 'locDesc',
				align: "center",
				width: '12%'
			},
			{
				key: 3,
				title: '科室类型',
				dataIndex: 'locTypeDesc',
				align: "center",
				width: '10%',
			},
			{
				key: 11,
				title: '重点专科级别',
				dataIndex: 'locSpecialtyGradeDesc',
				align: "center",
				width: '8%',
				render(text,record) {
					if(record.locSpecialtyGradeDesc==""){
						return "--"
					}
					return text
				}
			},
			{
				key: 4,
				title: '按开单发药',
				dataIndex: 'locOrdDsp',
				align: "center",
				width: '8%',
				render(locOrdDsp) {
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[locOrdDsp];
				}
			},
			{
				key: 5,
				title: '接收外院项目',
				dataIndex: 'locRecOthHospItem',
				align: "center",
				width: '8%',
				render(locRecOthHospItem) {
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[locRecOthHospItem];
				}
			},
			{
				key: 6,
				title: '向外院开单',
				dataIndex: 'locToOthHospItem',
				align: "center",
				width: '8%',
				render(locToOthHospItem) {
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[locToOthHospItem];
				}
			},
			{
				key: 7,
				title: '接收科室为本科',
				dataIndex: 'locGetRecLoc',
				align: "center",
				width: '8%',
				render(locGetRecLoc) {
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[locGetRecLoc];
				}
			},
			{
				key: 8,
				title: '产科',
				dataIndex: 'locIsObstetricsDep',
				align: "center",
				width: '8%',
				render(locIsObstetricsDep) {
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[locIsObstetricsDep];
				}
			},
			{
				key: 9,
				title: '状态',
				dataIndex: 'states',
				align: "center",
				render(states) {
					let config = {
						'生效': <li style={{ listStyle: 'disc', color: 'rgb(66,185,131)' }}><span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>生效</span></li>,
						'失效': <li style={{ listStyle: 'disc', color: 'rgb(240,65,52)' }}><span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>失效</span></li>
					}
					return config[states];
				}
			},
			{
				title: '操作',
				key: 10,
				align: "center",
				width: 130,
				render: (text, record) => (
					<span>
						<Icon type="edit" style={{ color: '#108EE9' }}></Icon>
						<span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
						{/* 分割线 */}
						<Divider type="vertical" />
						<Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
						<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
							<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
						</Popconfirm>
					</span>
				),
			}
		]
	}

	componentDidMount() {
		console.log("触发了componentDidMount")
		this.initData();
		this.loadspecialtyGrade();
		// console.log(store.getState().tableHeight.y)
	}

	componentWillUnmount() {
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state, callback) => { return; }
	}

	initData = () => {
		// 初始化下拉框数据
		this.getSelectData();
		this.loadHospitalMsg()
		// 组件加载完毕关闭loading
		this.setState({ showLoading: false });
		// 初始化列表数据
		this.handleQuery();
		var box = document.querySelector(".department-header");
		if (box) { //此处在加一层判断，更加严密，如果box存在的情况下获取
			this.setState({ headerHeight: box.offsetHeight })
		}
	}

	// 获取下拉框数据
	getSelectData = () => {
		let data = {
			params: [
				{
					locTypeFlag: '1',
					statusFlag: '1',
					buildFlag: '1',
					floorFlag: '1',
				}
			]
		}
		$http.post('urlS', this, {
			code: "01040009",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ selectData: res })
				} else {
					this.setState({ selectData: {} })
				}
			}
		})
	}

	// 3.13.23.获取科室信息
	getDepartmentInformation = (id) => {
		if (id) {
			let data = {
				params: [
					{ hospID: id }
				]
			}
			$http.post('urlS', this, {
				code: "04020008",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ DepartmentInformation: res.result.Data })
					} else {
						this.setState({ DepartmentInformation: [] })
					}
				}
			})
		} else {
			this.setState({ DepartmentInformation: [] })
		}
	}

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

	// 调用子组件公共库导入的连接事件
	libraryOnRef = (ref) => {
		this.libraryChild = ref
	}

	onFocusLocDesc = () => {
		if (this.state.hospitalId === undefined) {
			message.info("请先选择所属医院");
		}
	}

	// 查询条件 --- 所属医院
	onChangehospitalId = (e) => {
		// console.log(e.target.value)
		this.setState({ hospitalId: e, locDesc: undefined }, () => {
			this.getDepartmentInformation(e)
		});
	}

	// 查询条件 --- 科室名称
	onChangeLocDesc = (e) => {
		this.setState({ locDesc: e });
	}

	// 查询条件 --- 科室类型
	onChangelocType = (e) => {
		this.setState({ locType: e });
	}

	// 查询条件 --- 记录状态
	onChangeStatus = (e) => {
		this.setState({ status: e });
	}
	// 查询条件 --- 专科级别
	onChangeSpecialtyGradeId = (e) => {
		this.setState({ specialtyGradeId : e });
	}

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			let { status, hospitalId, locDesc, locType,specialtyGradeId } = this.state;
			this.getTableData(status, hospitalId, locDesc, locType,specialtyGradeId)
		})
	}

	// 请求列表数据
	getTableData = (status, hospitalId, locDesc, locType,specialtyGradeId) => {
		let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {}
		this.setState({ loading: true })
		let { page, pageSize } = this.state;
		let data = {
			params: [{
				hospID: hospitalId ? hospitalId : userData && userData.hospID ? userData.hospID : '', // 所属医院
				locID: locDesc, // 科室名称
				status: status, // 记录状态
				detailFlag: 1,
				type: locType,
				linkFlag: '',
				docFlag: '',
				specialtyGradeID:specialtyGradeId||"",
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page
			}]
		}
		$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 = i;
						if (res.result.Data[i].locStopDate === '') {
							res.result.Data[i].states = "生效";
						} else {
							let start = new Date();
							let end = new Date(res.result.Data[i].locStopDate);
							if (start > end) {
								res.result.Data[i].states = "失效";
							} else {
								res.result.Data[i].states = "生效";
							}
						}
					}
					this.setState({ tableData: res.result.Data, total: res.result.TotalCount, loading: false })
					// 数据加载成功关闭loading
					this.child.handleLoading();
				} else {
					this.setState({ tableData: [], total: 0, loading: false })
					// 数据加载失败关闭loading
					this.child.handleLoading();
				}
			},
			error: function (error) {
				this.setState({ tableData: [], total: 0, loading: false }, () => {
					// 数据加载成功关闭loading
					this.child.handleLoading();
				})
			}
		})
	}

	//获取所属医院
	loadHospitalMsg = () => {
		let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {}
		var data = {
			params: [{
				hospID: '', // 医院id
				logonGroupID: userData && userData.groupID ? userData.groupID : '', //登录角色id
				logonHospID: userData && userData.hospID ? userData.hospID : '', // 登录医院id
			}]
		}
		$http.post('urlS', this, {
			code: "01040001",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						hospitalData: res.depDoctor,
						// hospitalId: res.depDoctor ? res.depDoctor[0].id : undefined
					})
					var result = res.depDoctor && res.depDoctor.some(item => {
						if (item.id === userData.hospID) {
							return true
						}
					})
					if (!result) {
						this.setState({
							hospitalId: undefined
						})
					} else {
						this.setState({ hospitalId: userData.hospID ? userData.hospID : undefined })
						this.getDepartmentInformation(userData.hospID)
					}
				}
			}
		});
	}

	// 查询
	handleQuery = () => {
		this.setState({ page: 1 }, () => {
			let { status, hospitalId, locDesc, locType,specialtyGradeId } = this.state;
			this.getTableData(status, hospitalId, locDesc, locType,specialtyGradeId)
		})
	}

	// 点击公共库导入显示弹框
	handleLibraryImport = () => {
		this.libraryChild.showModal();
	}

	// 新增科室跳转到新增界面
	handleAdd = () => {
		// 点击跳转导航栏新加新增角色
		this.props.openWindowBySubTab({
			title: '新增科室',
			path: '/6002/001',
			Paras: {
				targetKey: '新增科室',
				flag: 'add',
			},
			component: "pages/departmentInformation/NewDepartment.jsx"
		});
	}

	// 编辑
	handleCompile = (record) => {
		this.props.openWindowBySubTab({
			title: '编辑科室',
			path: '/6002/001',
			Paras: {
				targetKey: '编辑科室',
				flag: 'compile',
				userInfo: record
			},
			component: "pages/departmentInformation/NewDepartment.jsx"
		});
	}

	// 删除
	handleDelete = (record) => {
		let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		let data = {
			params: [{
				locID: record.locID,
				updateUserID: userData && userData.userID ? userData.userID : ''
			}]
		}
		$http.post('urlADS', this, {
			code: '01050005',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success('操作成功：状态值已变更成失效');
					// 刷新列表数据
					let { status, hospitalId, locDesc, locType,specialtyGradeId } = this.state;
					this.getTableData(status, hospitalId, locDesc, locType,specialtyGradeId)
				}
			}
		})
	}

	//获取重点专科级别下拉
	loadspecialtyGrade = () => {
		var data = {
			params: [{

			}]
		}
		$http.post('urlS', this, {
			code: "01040186",
			data: data,
			success: function (res) {
				// console.log(res)
				if (+res.errorCode === 0) {
					this.setState({
						specialtyGradeData: res.result.data
					})
				}
			}
		});
	}

	render() {
		// 组件所需参数
		const param = {
			// 表头配置
			columns: this.columns,
			// 表格数据
			data: this.state.tableData,
			// 数据总条数
			total: this.state.total,
			// 当前页数
			page: this.state.page,
			loading: this.state.loading,
			pageSize: "20",
			// 表格的宽度
			x: 900,
			y: store.getState().tableHeight.y + 114 - this.state.headerHeight,
			height: store.getState().tableHeight.y + 158 - this.state.headerHeight + 'px',
		}
		return (
			<Spin tip="加载中..." spinning={this.state.showLoading} className="department">
				<div>
					<div className="department-header">
						<Row style={{ minHeight: '64px', padding: '0 24px' }}>
							<Col span={20}>
								所属医院：<Select showSearch optionFilterProp="seatchprop" allowClear value={this.state.hospitalId} onChange={this.onChangehospitalId} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择所属医院">
									{this.state.hospitalData && this.state.hospitalData.map(item => {
										return <Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
									})}
								</Select>
								{/* showSearch 支持搜索功能；allowClear 支持清除; optionFilterProp 搜索过滤的值 */}
								科室名称：<Select showSearch optionFilterProp="seatchprop" allowClear value={this.state.locDesc} onChange={this.onChangeLocDesc} onFocus={this.onFocusLocDesc} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择科室名称">
									{this.state.DepartmentInformation && this.state.DepartmentInformation.map(item => {
										return <Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
									})}
								</Select>
								科室类型：<Select showSearch optionFilterProp="seatchprop" allowClear value={this.state.locType} onChange={this.onChangelocType} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择科室类型">
									{this.state.selectData.locType && this.state.selectData.locType.map(item => {
										return <Option key={item.id} value={item.code} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
									})}
								</Select>
								记录状态：<Select showSearch optionFilterProp="seatchprop" allowClear value={this.state.status} onChange={this.onChangeStatus} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择记录状态">
									{this.state.selectData.status && this.state.selectData.status.map(item => {
										return <Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
									})}
								</Select>
								重点专科级别：<Select showSearch allowClear optionFilterProp="seatchprop"  value={this.state.specialtyGradeId} onChange={this.onChangeSpecialtyGradeId} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择专科级别">
									{this.state.specialtyGradeData && this.state.specialtyGradeData.map(item => {
										return <Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
									})}
								</Select>
								<Button onClick={this.handleQuery} style={{ margin: '23px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
							</Col>
							<Col span={4} style={{ textAlign: 'right' }}>
								<Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '23px 15px 0 0' }}>新科室</Button>
								<Button icon="import" onClick={this.handleLibraryImport} style={{ margin: '23px 15px 0 0' }}>公共库导入</Button>
							</Col>
						</Row>
					</div>
					<div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
					<div style={{ padding: "24px 24px 12px 24px" }} className="table-body-height">
						{/* handelThis将夫组件的属性与方法给子组件访问 */}
						<PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
					</div>
					{/* 导入科室 */}
					<CommonLibraryImport onRef={this.libraryOnRef} selectData={this.state.selectData} hospitalData={this.state.hospitalData} />
				</div>
			</Spin>
		)
	}
}

