// 角色维护基本信息
import React from 'react';
import {
	Form, Button, Col, Row, Input, Select, DatePicker, message, Switch, Modal, Checkbox, Table
} from 'antd';
import Moment from 'moment';
import { $http } from 'containers/config/https';
import { Util } from 'tools'
import store from 'store';
import 'assets/css/system.css'

const { Option } = Select;

const BasicInformation = Form.create()(
	// eslint-disable-next-line
	class extends React.Component {
		constructor() {
			super();
			var userData = JSON.parse(sessionStorage.getItem('userData'));
			this.state = {
				visible: false, //弹框显示状态
				confirmLoading: false, // 组件loading
				name: '', // 角色名称
				checked: false, // 是否仅显示生效
				tableData: [], // 表格数据
				tableLoading: true, // 表格loading
				rowId: '', // 选中行ID
				rowClassName: '', // 选中行class名
				userInfo: {}, // form初始化数据
				sideMenu: [], // 侧菜单
				headerMenu: [], // 头菜单
				routerData: [], // 路由数据
				user: userData && userData.sessionID ? userData : {},
				groupID: '', // 角色ID
			};
			this.myRef1 = React.createRef();
			this.myRef2 = React.createRef();
			this.myRef3 = React.createRef();
			this.myRef4 = React.createRef();
			this.myRef5 = React.createRef();
			this.myRef6 = React.createRef();
			this.myRef7 = React.createRef();
			this.myRef8 = React.createRef();
			this.myRef9 = React.createRef();
			this.myRef10 = React.createRef();
			this.myRef11 = React.createRef();
			this.myRef12 = React.createRef();
			this.myRef13 = React.createRef();
			this.myRef14 = React.createRef();
			// 表格行设置
			this.columns = [{
				key: 1,
				title: '角色名称',
				dataIndex: 'Descripts',
				align: "left",
				width: 100,
			},
			{
				key: 2,
				title: '默认菜单类型',
				dataIndex: 'DefaultMenuType',
				align: "left",
				width: 100,
				render(DefaultMenuType) {
					let config = {
						'1': '头菜单',
						'2': '侧菜单'
					}
					return config[DefaultMenuType];
				}
			},]
		}

		componentDidMount() {
			if (this.props.flag === 'compile') {
				this.setUserInfoId(this.props.userInfo ? this.props.userInfo.ID : '')
			}
			this.props.onRef(this);
			Util.changeEnter(this.myRef1)
		}

		setUserInfoId = (rowId) => {
			this.setState({ rowId }, () => {
				this.handleOk()
			})
		}

		// 显示弹框
		showModal = () => {
			this.setState({
				visible: true,
			}, () => {
				this.handleQuery()
			});
		}

		// 点击确定--根据行ID请求数据
		handleOk = (flag) => {
			this.resetFields();
			this.setState({ routerData: [] })
			if (this.state.rowId) {
				let data = {
					params: [{
						ID: this.state.rowId
					}]
				}
				$http.post('urlS', this, {
					code: "2105",
					data: data,
					success: function (res) {
						if (+res.errorCode === 0) {
							this.setState({ userInfo: res.result, groupID: res.result.ID }, () => {
								this.state.userInfo && this.state.userInfo.DefaultMenuType ? this.getRouterData(this.state.userInfo.DefaultMenuType) : '';
								if (flag === 'modal') {
									this.handleCancel()
								}
							})
						} else {
							this.setState({ userInfo: {}, groupID: '' })
						}
					}
				})
			} else {
				message.info('请选择需要复制的角色')
			}
		}

		// 关闭弹框
		handleCancel = () => {
			this.setState({
				visible: false,
			});
		}

		// 重置表单
		resetFields = () => {
			this.props.form.resetFields(); //清空所有
		}

		// 新增保存调的方法
		handelFunction(code, msg) {
			const { form: { validateFields } } = this.props;
			validateFields((errors, values) => {
				// 验证成功
				if (errors === null) {
					let data = {
						params: []
					}
					// 取到登录后用户的信息
					let { user } = this.state;
					let obj = JSON.parse(JSON.stringify(values));
					obj.CreateUserDr = this.props.flag === 'compile' ? this.props.userInfo.CreateUserDr : (user && user.userID ? user.userID : '');
					// 当增加时点击复制把ID值传给后天然后后台根据ID值去复制权限，编辑时则根据ID去保存修改
					if (msg === '编辑') {
						obj.ID = this.props.userInfo.ID
					} else {
						obj.CopyGroupId = this.props.userInfo.ID
					}
					// 将开关的值转化
					obj.StartDate = obj.StartDate ? Moment(obj.StartDate).format("YYYY-MM-DD") : '';
					obj.StopDate = obj.StopDate ? Moment(obj.StopDate).format("YYYY-MM-DD") : '';
					obj.AllOrder = Util.replaceTrueFalse(obj.AllOrder);
					obj.OperCodeTable = Util.replaceTrueFalse(obj.OperCodeTable);
					obj.SendMsgToAllUser = Util.replaceTrueFalse(obj.SendMsgToAllUser);
					obj.LayoutEdit = Util.replaceTrueFalse(obj.LayoutEdit);
					obj.CancelExecStatus = Util.replaceTrueFalse(obj.CancelExecStatus);
					obj.ColumnEdit = Util.replaceTrueFalse(obj.ColumnEdit);

					// 处理需要传递的obj
					data.params.push(Util.disposeData(obj));
					$http.post('urlADS', this, {
						code: code,
						data: data,
						success: function (res) {
							if (+res.errorCode === 0) {
								// 成功提示
								message.success(msg + '成功');
								// 新增成功重置form表单
								// this.resetFields();
								// this.props.handelThis.resetUserInfo()
								if (this.props.flag === 'add') {
									// 菜单授权可操作
									this.props.handelThis.unlockAuthorization(res.gropuId); // 保存成功后传入返回的ID值
									// this.props.handelThis.compileFlag(); // 修改flag的值
								}
							}
						}
					})
				}
			});
		}

		// 保存
		handelSave = () => {
			let { flag } = this.props;
			if (flag === 'compile') {
				this.handelFunction('2103', '编辑');
			} else {
				this.handelFunction('2102', '新增');
			}
		}

		// 新增
		handelAdd = () => {
			this.props.handelThis.addFlag()
		}

		// 查询条件 --- 角色名称
		onChangeName = (e) => {
			// console.log(e.target.value)
			this.setState({ name: e.target.value });
		}

		// 获取Checkbox操作后的值
		handleCheckbox = (e) => {
			this.setState({ checked: e.target.checked });
		}

		// 查询所有角色
		handleQuery = () => {
			let checked = '';
			if (this.state.checked === true) {
				checked = '可用'
			} else {
				checked = '不可用'
			}
			let data = {
				params: [{
					Descripts: this.state.name, // 角色名称
					PostDr: '', // 岗位
					Status: checked, // 记录状态
				}],
				pagination: [{
					pageSize: '',
					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 = i;
							res.result.Data[i].children = [];
							res.result.Data[i].rowClassName = i + 'class';
						}
						this.setState({ tableData: res.result.Data, tableLoading: false });
					} else {
						// 数据加载失败关闭loading
						this.setState({ tableData: [], tableLoading: false });
					}
				},
				error: function () {
					// 数据加载失败关闭loading
					this.setState({ tableData: [], tableLoading: false });
				}
			})
		}

		// 设置行属性
		onClickRow = (record) => {
			return {
				// 单击行选中
				onClick: () => {
					// console.log(record)
					this.setState({ rowClassName: record.rowClassName, rowId: record.ID })
				},
				// 双击行编辑
				onDoubleClick: () => {
					this.setState({ rowClassName: record.rowClassName, rowId: record.ID }, () => {
						// 关闭弹窗
						this.handleOk('modal');
						this.handleCancel();
					})
				},
			}
		}

		// 表格行的类名
		setRowClassName = (record) => {
			return record.rowClassName === this.state.rowClassName ? 'clickRowStyle' : '';
		}

		// 返回到列表页面
		// goBack = () => {
		// 	this.props.handelThis.goBack()
		// }

		// 点击图标查询该角色所有的菜单
		handleOnExpand = (expanded, record) => {
			let data = {
				params: [{
					GroupDr: record.ID
				}]
			}
			$http.post('urlS', this, {
				code: "2612",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						for (let i = 0; i < res.result.length; i++) {
							if (res.result[i].MenuDesc === '头菜单') {
								this.setState({ headerMenu: res.result[i].Menu })
							} else if (res.result[i].MenuDesc === '侧菜单') {
								this.setState({ sideMenu: res.result[i].Menu })
							}
						}
					} else {
						this.setState({ headerMenu: [], sideMenu: [] })
					}
				}
			})
		}

		// 展开的行变化时触发
		handelOnExpandedRowsChange = (expandedRows) => {
			if (expandedRows.length > 1) {
				// shift()：移除数组中的第一个元素，即第一次点击所得到的那个对象
				expandedRows.shift()
			}
		}

		// 下拉框选中事件
		handleOnSelect = (num) => {
			switch (num) {
				case 1:
					this.props.form.setFieldsValue({
						MainInterface: undefined
					})
					setTimeout(() => {
						this.myRef3.current.focus();
					}, 300)
					break;
				// case 2:
				// 	setTimeout(() => {
				// 		this.myRef3.current.focus();
				// 	}, 300)
				// 	break;
				case 3:
					setTimeout(() => {
						this.myRef4.current.focus();
					}, 300)
					break;
				case 4:
					setTimeout(() => {
						this.myRef5.current.focus();
					}, 300)
					break;
				case 5:
					setTimeout(() => {
						this.myRef6.current.focus();
					}, 300)
					break;
				case 6:
					setTimeout(() => {
						this.myRef7.current.focus();
					}, 300)
					break;
				case 7:
					setTimeout(() => {
						this.myRef8.current.focus();
					}, 300)
					break;
				case 8:
					setTimeout(() => {
						this.myRef9.current.focus();
					}, 300)
					break;
				case 9:
					setTimeout(() => {
						this.myRef10.current.focus();
					}, 300)
					break;
				case 10:
					setTimeout(() => {
						this.myRef11.current.focus();
					}, 300)
					break;
				case 11:
					setTimeout(() => {
						this.myRef12.current.focus();
					}, 300)
					break;
				case 12:
					setTimeout(() => {
						this.myRef13.current.focus();
					}, 300)
					break;
				default:
					setTimeout(() => {
						this.myRef14.current.focus();
					}, 300)
			}

		}

		// 获取路由数据
		getRouterData = (type) => {
			let { user, groupID } = this.state;
			if (!groupID) {
				this.setState({ routerData: [] });
				return;
			}
			let data = {
				params: [{
					// 角色ID：groupDr
					GroupDr: groupID,
					// 菜单类型
					Type: type,
					// 科室id
					LocDr: user && user.locID ? +user.locID : ''
				}]
			}
			$http.post('urlS', this, {
				code: '3002',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ routerData: res.result });
					} else {
						this.setState({ routerData: [] });
					}
				},
				error: function (error) {
					this.setState({ routerData: [] });
				}
			})
		}

		handleMainInterfaceOnFocus = e => {
			let meunType = this.props.form.getFieldValue("DefaultMenuType");
			if (!meunType) {
				return;
			}
			setTimeout(() => {
				this.getRouterData(meunType)
			}, 300)

		}

		// 角色名称失焦操作
		handleQuerygroupID = e => {
			if (!e.target.value) {
				return;
			}
			let data = {
				params: [{
					desc: e.target.value
				}]
			}
			$http.post('urlS', this, {
				code: '3003',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ groupID: res.result && res.result.groupID ? res.result.groupID : '' });
					} else {
						this.setState({ groupID: "" });
					}
				}
			})
		}

		render() {
			const formItemInput = {
				labelCol: { span: 5 },
				wrapperCol: { span: 19 }
			};
			const formItemSwitch = {
				labelCol: { span: 16 },
				wrapperCol: { span: 8 }
			};
			const { visible, confirmLoading, routerData } = this.state;
			const { getFieldDecorator } = this.props.form;
			let userInfo = this.state.userInfo;

			let menuOption = routerData && routerData.map((item, index) => {
				return (<Option key={index} value={item.ID} title={item.title}>{item.title}</Option>)
			})
			return (
				<div style={{ position: 'relative', margin: '10px 0', height: store.getState().tableHeight.y - 60 + 'px', overflow: 'auto' }}>
					<div style={{ width: '600px' }} className='basiclnformation'>
						{/* hideRequiredMark--隐藏所有表单项的必选标记 initialValue--初始值 */}
						<Form layout="vertical">
							<Row gutter={16}>
								<Form.Item label="角色名称：" {...formItemInput}>
									{getFieldDecorator('Descripts', {
										initialValue: userInfo.Descripts ? userInfo.Descripts : undefined,
										rules: [{ required: true, message: '请输入名称' }],
									})(
										<Input onBlur={this.handleQuerygroupID} ref={this.myRef14} placeholder="请输入角色名称" className='input' />
									)}
								</Form.Item>
							</Row>
							<Row gutter={16}>
								<Form.Item label="默认菜单类型：" {...formItemInput}>
									{getFieldDecorator('DefaultMenuType', {
										initialValue: userInfo.DefaultMenuType ? "" + userInfo.DefaultMenuType : undefined,
										rules: [{ required: true, message: '请选择默认菜单类型' }]
									})(
										<Select ref={this.myRef1} className='input' allowClear onSelect={() => this.handleOnSelect(1)} placeholder="请选择默认菜单类型">
											{this.props.selectData.menu && this.props.selectData.menu.map(item => {
												return <Option key={item.id} value={"" + item.id} title={item.descripts}>{item.descripts}</Option>
											})}
										</Select>
									)}
								</Form.Item>
							</Row>
							{/* <Row gutter={16}>
											<Form.Item label="安全等级：" {...formItemInput}v>
												{getFieldDecorator('SafeClassificat', {
														initialValue: userInfo.SafeClassificat ? userInfo.SafeClassificat : undefined,
												})(
														<Select ref={this.myRef2} allowClear onSelect={() => this.handleOnSelect(2)} placeholder="请选择安全等级">
																{this.props.selectData.safetyGrade && this.props.selectData.safetyGrade.map(item => {
																	return <Option key={item.id} value={item.id}>{item.descripts}</Option>
																})}
														</Select>
												)}
											</Form.Item>
										</Row> */}
							<Row gutter={16}>
								<Form.Item label="主界面：" {...formItemInput}>
									{getFieldDecorator('MainInterface', {
										initialValue: userInfo.MainInterface ? userInfo.MainInterface : undefined,
									})(
										<Select onFocus={this.handleMainInterfaceOnFocus} ref={this.myRef3} showSearch optionFilterProp="title" allowClear onSelect={() => this.handleOnSelect(3)} placeholder="请选择主界面">
											{menuOption}
										</Select>
									)}
								</Form.Item>
							</Row>
							<Row gutter={16}>
								<Form.Item label="生效日期：" {...formItemInput}>
									{getFieldDecorator('StartDate', {
										initialValue: userInfo.StartDate ? Moment(userInfo.StartDate, 'YYYY-MM-DD') : Moment(),
										rules: [{ required: true, message: '请选择生效日期' }],
									})(
										<DatePicker style={{ width: '100%' }} ref={this.myRef4} format="YYYY-MM-DD" allowClear onChange={() => this.handleOnSelect(4)} />
									)}
								</Form.Item>
							</Row>
							<Row gutter={16}>
								<Form.Item label="失效日期：" {...formItemInput}>
									{getFieldDecorator('StopDate', {
										initialValue: userInfo.StopDate ? Moment(userInfo.StopDate, 'YYYY-MM-DD') : undefined,
									})(
										<DatePicker style={{ width: '100%' }} ref={this.myRef5} format="YYYY-MM-DD" allowClear onChange={() => this.handleOnSelect(5)} />
									)}
								</Form.Item>
							</Row>
							<Row gutter={16}>
								<Form.Item label="超时时间(分钟)：" {...formItemInput}>
									{getFieldDecorator('OverTime', {
										initialValue: userInfo.OverTime ? userInfo.OverTime : undefined,
										rules: [{ pattern: /^[1-9]\d*$/, message: '超时时间只能为正整数, 如1、2、3、4' }]
									})(
										<Input placeholder="请输入超时时间" type="number" className="input-number" ref={this.myRef6} onPressEnter={() => this.handleOnSelect(6)} />
									)}
								</Form.Item>
							</Row>
							<Row gutter={16}>
								<Form.Item label="岗位：" {...formItemInput}>
									{getFieldDecorator('PostDr', {
										initialValue: userInfo.PostDr ? userInfo.PostDr : undefined,
										rules: [{ required: true, message: '请选择岗位' }],
									})(
										<Select showSearch optionFilterProp="seatchprop" ref={this.myRef7} allowClear onSelect={() => this.handleOnSelect(7)} placeholder="请选择岗位">
											{this.props.selectData.post && this.props.selectData.post.map(item => {
												return <Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
											})}
										</Select>
									)}
								</Form.Item>
							</Row>
							<Row gutter={16}>
								<Form.Item label="角色类型：" {...formItemInput}>
									{getFieldDecorator('groupType', {
										initialValue: userInfo.groupType ? userInfo.groupType : undefined,
									})(
										<Input ref={this.myRef14} placeholder="登录选择当前角色时获取跳转第三方系统路径标识" className="input" />
									)}
								</Form.Item>
							</Row>
							<Row gutter={16}>
								<Col span={8}>
									<Form.Item label="全部医嘱：" {...formItemSwitch}>
										{getFieldDecorator('AllOrder', {
											valuePropName: 'checked',
											initialValue: userInfo.AllOrder === "Y" ? true : false,
										})(
											<Switch ref={this.myRef8} checkedChildren="是" unCheckedChildren="否" onChange={() => this.handleOnSelect(8)} />
										)}
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item label="操作代码表：" {...formItemSwitch}>
										{getFieldDecorator('OperCodeTable', {
											valuePropName: 'checked',
											initialValue: userInfo.OperCodeTable === "Y" ? true : false,
										})(
											<Switch ref={this.myRef9} checkedChildren="是" unCheckedChildren="否" onChange={() => this.handleOnSelect(9)} />
										)}
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item label="向所有用户发消息：" {...formItemSwitch}>
										{getFieldDecorator('SendMsgToAllUser', {
											valuePropName: 'checked',
											initialValue: userInfo.SendMsgToAllUser === "Y" ? true : false,
										})(
											<Switch ref={this.myRef10} checkedChildren="是" unCheckedChildren="否" onChange={() => this.handleOnSelect(10)} />
										)}
									</Form.Item>
								</Col>
							</Row>
							<Row gutter={16}>
								<Col span={8}>
									<Form.Item label="界面编辑权限：" {...formItemSwitch}>
										{getFieldDecorator('LayoutEdit', {
											valuePropName: 'checked',
											initialValue: userInfo.LayoutEdit === "Y" ? true : false,
										})(
											<Switch ref={this.myRef11} checkedChildren="是" unCheckedChildren="否" onChange={() => this.handleOnSelect(11)} />
										)}
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item label="撤销已执行医嘱：" {...formItemSwitch}>
										{getFieldDecorator('CancelExecStatus', {
											valuePropName: 'checked',
											initialValue: userInfo.CancelExecStatus === "Y" ? true : false,
										})(
											<Switch ref={this.myRef12} checkedChildren="是" unCheckedChildren="否" onChange={() => this.handleOnSelect(12)} />
										)}
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item label="列编辑权限：" {...formItemSwitch}>
										{getFieldDecorator('ColumnEdit', {
											valuePropName: 'checked',
											initialValue: userInfo.ColumnEdit === "Y" ? true : false,
										})(
											<Switch ref={this.myRef13} checkedChildren="是" unCheckedChildren="否" onChange={() => this.handleOnSelect(13)} />
										)}
									</Form.Item>
								</Col>
							</Row>
							<Row gutter={16} style={{ textAlign: 'center' }}>
								<Button onClick={this.handelAdd} type="primary" style={{ marginRight: '15px', display: this.props.flag === 'add' ? 'none' : '' }}>新角色</Button>
								<Button onClick={this.handelSave} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存</Button>
								{/* <Button onClick={this.goBack}>返回</Button> */}
							</Row>
						</Form>
					</div>
					<div
						style={{
							position: 'absolute',
							top: '4px',
							left: '620px',
							display: this.props.flag === 'compile' ? 'none' : ''
						}}
					>
						<span className="span" onClick={this.showModal}>复制角色信息</span>
					</div>
					{/* <div
							style={{
								position: 'absolute',
								bottom: '32px',
								left: '640px'
							}}
						>
							
						</div> */}
					<Modal
						width={600}
						title="复制角色"
						visible={visible}
						onOk={this.handleOk}
						confirmLoading={confirmLoading}
						onCancel={this.handleCancel}
					>
						<div className="table-operations">
							<Row>
								<Col span={18}>
									角色名称：<Input placeholder="请输入角色名称" value={this.state.name} style={{ width: '150px', marginRight: '20px' }} onChange={this.onChangeName} onPressEnter={this.handleQuery} />
									<Checkbox checked={this.state.checked} onChange={this.handleCheckbox}>仅显示生效</Checkbox>
								</Col>
								<Col span={6}>
									<Button style={{ marginRight: '15px', background: 'rgba(255,255,255,1)' }} onClick={this.handleQuery}>查询</Button>
								</Col>
							</Row>
							<div style={{ marginTop: '24px' }}>
								<Table
									rowClassName={this.setRowClassName}
									style={{ height: '400px', maxHeight: '400px', overflow: 'scroll' }}
									dataSource={this.state.tableData}
									columns={this.columns}
									pagination={false}
									onRow={this.onClickRow}
									// bordered
									loading={this.state.tableLoading}
									onExpand={this.handleOnExpand}
									onExpandedRowsChange={this.handelOnExpandedRowsChange}
									expandedRowRender={record => (
										<div style={{ textAlign: 'left' }}>
											<Row>
												<Col span={12}>
													<div>
														<h3>头菜单</h3>
														<ul>
															{this.state.headerMenu ? this.state.headerMenu.map(item => {
																return <li key={item.key}>{item.MenuDetailDrDesc}</li>
															}) : ''}
														</ul>
													</div>
												</Col>
												<Col span={12}>
													<div>
														<h3>侧菜单</h3>
														<ul>
															{this.state.sideMenu ? this.state.sideMenu.map(item => {
																return <li key={item.key}>{item.MenuDetailDrDesc}</li>
															}) : ''}
														</ul>
													</div>
												</Col>
											</Row>
										</div>
									)}
								/>
							</div>
						</div>
						<div style={{ position: 'absolute', bottom: '10px', left: '16px', height: '32px', lineHeight: '32px', opacity: '0.5' }}>提示：此处复制包含基本信息、菜单授权、其他配置信息</div>
					</Modal>
				</div>
			)
		}
	}
);
export default BasicInformation;