// 根据医院配置病历
import React from 'react';
import {Row, Col, Button, Select, Icon, message, Divider, Popconfirm, Modal, Form, Switch } from "antd";
import { $http } from 'containers/config/https';
import store from 'store';
import { Util } from 'tools'

import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx'; // 公共table组件

let {Option} = Select;

class CaseAllocation extends React.Component {
	constructor() {
		super();
		var userData = JSON.parse(sessionStorage.getItem('userData'));
		this.state={
			userData,
			hospID: undefined, // 所属医院
			hospitalSelectData: [], // 医院下拉框数据
			tableData: [], 
			total: 0, 
			page: 1,
			pageSize: 20,
			loading: false,
			visible: false,
			flag: "add",
			userInfo: {}
		};
		this.columns = [
			{
				title: '医院名称',
				dataIndex: 'hospDesc',
				align: "center",
			},
			{
			  title: '删除患者未提交病历',
			  dataIndex: 'deleteable',
				align: "center",
				render(deleteable){
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[deleteable];
				}
			},
			{
			  title: '自动保存',
			  dataIndex: 'autoSave',
				align: "center",
				render(autoSave){
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[autoSave];
				}
			},
			{
			  title: '操作',
			  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() {
		this.getHospitalSelectData();
		this.getTableData();
	}

	//获取所属医院
	getHospitalSelectData = () => {
		let {userData} = this.state;
		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({
						hospitalSelectData: res.depDoctor,
					})
				}
			}
		})
	}

	// 所属医院change
	handleHospChange = e => {
		this.setState({hospID: e})
	}

	handleQuery = () => {
		this.setState({page: 1}, () => {
			this.getTableData()
		})
	}

	// 获取表格数据
	getTableData = () =>　{
		let {hospID, userData, pageSize, page} = this.state;
		let data = {
			params: [{
				hospID: hospID ? hospID : "", // 所属医院
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page
			}]
		}
		$http.post('urlS', this, {
			code: "06050014",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.length; i++) {
						res.result.key=i
					}
					this.setState({ tableData: res.result, total: res.TotalCount })
					// 数据加载成功关闭loading
					this.child.handleLoading();
				} else {
					this.setState({ tableData: [], total: 0 })
					// 数据加载失败关闭loading
					this.child.handleLoading();
				}
			},
			error: function (error) {
				this.setState({ tableData: [], total: 0 }, () => {
					// 数据加载成功关闭loading
					this.child.handleLoading();
				})
			}
		})
	}

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

	// 新增
	handleAdd = () =>{
		this.setState({visible: true, flag: "add", userInfo: {}})
	}

	// 编辑
	handleCompile = record => {
		this.setState({visible: true, flag: "compile", userInfo: record})
	}

	// 删除
	handleDelete = record => {
		let data = {
			params: [{
				ID: record.ID
			}]
		}
		$http.post('urlADS', this, {
			code: '06050013',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success(res.errorMessage);
					this.getTableData()
				}
			}
		})
	}

	onRef = ref => {
		this.child=ref
	}

	handleOk = () => {
		let {flag, userInfo} = this.state;
		const { form: { validateFields } } = this.props;
		validateFields((errors, values) => {
			// 验证成功
			if (errors === null) {
					let data = {
						params: []
					}
					let obj = JSON.parse(JSON.stringify(values));
					// 当增加时点击复制把ID值传给后天然后后台根据ID值去复制权限，编辑时则根据ID去保存修改
					if (flag === 'compile') {
						obj.ID = userInfo.ID
					}
					obj.deleteable = Util.replaceTrueFalse(obj.deleteable);
					obj.autoSave = Util.replaceTrueFalse(obj.autoSave);

					// 处理需要传递的obj
					data.params.push(obj);
					$http.post('urlADS', this, {
						code: "06050012",
						data: data,
						success: function (res) { 
							if (+res.errorCode === 0) {
								// 成功提示
								message.success(res.errorMessage);
								if (flag === "add") {
									this.resetFields();
								}
								this.handleCancel()
								this.getTableData();
							}
						}
					})
			}
		});
	}

	handleCancel = () => {
		let {flag} = this.state;
		this.setState({visible: false}, () => {
			if (flag === "compile") {
				this.setState({userInfo: {}})
				this.resetFields()
			}
		})
	}

	// 重置表单
	resetFields() {
		this.props.form.resetFields();
	}

	render() {
		let {hospID, hospitalSelectData, tableData, total, page, pageSize, loading, visible, flag, userInfo} = this.state;
		const { getFieldDecorator } = this.props.form;

		let param={
			// 表头配置
			columns: this.columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			total,
			// 当前页数
			page,
			pageSize: pageSize,
			loading,
			// 表格的宽度
			x: 900,
			y: store.getState().tableHeight.y + 78 - 56,
			height: store.getState().tableHeight.y + 123 - 56 + 'px',
		}

		const formItemInput  = {
			labelCol: {span: 5},
			wrapperCol: {span: 19}
		};

		const formItemSwitch  = {
			labelCol: {span: 16},
			wrapperCol: {span: 8}
		};

		let hospOption = hospitalSelectData && hospitalSelectData.map(item => {
			return <Option value={item.id} key={item.id} title={item.descripts}>{item.descripts}</Option>
		})
		return (
			<div className="case-allocation">
				<div>
					<Row style={{minHeight: '64px', padding: '0 24px'}}>
						<Col span={20}>
							所属医院：<Select allowClear value={hospID} onChange={this.handleHospChange} style={{width: '150px',  margin: '23px 15px 0 0'}} placeholder="请选择">
													{hospOption}
											</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>
						</Col>
					</Row>
				</div>
				<div style={{widht: '100%', height: '10px', background: '#f0f2f5'}}></div>
				<div style={{ padding: 24}} className="table-body-height">
					{/* handelThis将夫组件的属性与方法给子组件访问 */}
					<PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
				</div>
				<Modal
					title={flag === "add" ? "新增病历配置" : "编辑病历配置"}
					visible={visible}
					onOk={this.handleOk}
					onCancel={this.handleCancel}
					width={600}
				>
					<div style={{width: '100%', height: '500px'}}>
						<Form>
							<Form.Item label="所属医院" {...formItemInput}>
								{getFieldDecorator('hospID', {
									initialValue: userInfo.hospID ? userInfo.hospID: undefined,
									rules: [{ required: true, message: '请选择所属医院' }]
								})(
									<Select placeholder="请选择">
										{hospOption}
									</Select>
								)}
							</Form.Item>
							<Row>
								<Col span={12}>
									<Form.Item label="删除患者未提交病历：" {...formItemSwitch}>
										{getFieldDecorator('deleteable', {
												valuePropName: 'checked',
												initialValue: userInfo.deleteable === "Y" ? true : false,
										})(
												<Switch checkedChildren="是" unCheckedChildren="否" />
										)}
									</Form.Item>
								</Col>
								<Col span={12}>
									<Form.Item label="自动保存：" {...formItemSwitch}>
										{getFieldDecorator('autoSave', {
												valuePropName: 'checked',
												initialValue: userInfo.autoSave === "Y" ? true : false,
										})(
												<Switch checkedChildren="是" unCheckedChildren="否" />
										)}
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</div>
				</Modal>
			</div>
		)
	}
}
const CaseAllocationForm = Form.create()(CaseAllocation);
export default CaseAllocationForm;