import React from 'react';
import '../../assets/css/system.css';
import PropTypes from 'prop-types';
import { $http } from '../../containers/config/https';
import { Form, message, Select } from 'antd';
import moment from 'moment';
import InsuLinkCharge from '../InvManagement/InsuLinkCharge';
import 'assets/css/common.css';

const Option = Select.Option;
const FormHandel = Form.create()(

	class extends React.Component {
		constructor(props) {
			super(props);
			this.state = {
				sessionData: {},
				GGItemData: {},
				ItemHospData: [],
				PriceHospData: [],
				priceHospID: "",
				Pricerowid: "",
				itemID: "",
				hospSubData: {},
				hospTCSUBData: [],
				hospMCSUBData: [],
				hospICSUBData: [],
				hospOCSUBData: [],
				hospECSUBData: [],
				hospACSUBData: [],
				Authoritydata: {},
				ChargeInfo: {},
				//费别
				admReasonID: '',
				AdmReasonData: [],
				admReasonDesc: '',
				//等级
				gradeID: '',
				GradeData: [],
				gradeDesc: '',
				// 抽屉显示
				visible: false,
				chargeCode: '',
				remarks: '',
				Buttondisplay: 'none',
				UpData: [],
				uplistkey: 0,
			}
			this.columns = [
				{
					title: '费别',
					dataIndex: 'priceAdmReasonDesc',
					align: "center"
				},
				{
					title: '价格',
					dataIndex: 'price',
					align: "center"
				},
				{
					title: '开始日期',
					dataIndex: 'priceStDate',
					align: "center"
				},
				{
					title: '结束日期',
					dataIndex: 'priceEndDate',
					align: "center"
				},
				{
					title: '级别',
					dataIndex: 'priceGradeDesc',
					align: "center"
				},
				{
					title: '医院',
					dataIndex: 'pricehospDesc',
					align: "center"
				},
				{
					title: '物价依据',
					dataIndex: 'priceChargeCode',
					align: "center"
				},
				{
					title: '备注',
					dataIndex: 'priceRemarks',
					align: "center"
				},
				{
					title: '创建日期',
					dataIndex: 'createDate',
					align: "center"
				},
				{
					title: '创建时间',
					dataIndex: 'createTime',
					align: "center"
				},
				{
					title: '创建人员',
					dataIndex: 'createUserDesc',
					align: "center"
				},

			];
		}

		componentDidMount() {
			this.props.onRef(this);
			this.selectloadData()
		}

		// 查询单个收费项数据
		handleItmQuery = (itemID) => {
			let data = {
				params: [{
					itemID: itemID,
				}],
				pagination: [{
					pageSize: 1,
					currentPage: 1,
					sortColumn: "Code",
					sortOrder: "asc"
				}]
			}
			$http.post('urlS', this, {
				code: '05100010',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0 && res.result) {
						this.setState({
							GGItemData: res.result.Data[0]
						});
					}
				}
			})
		}

		// 查询
		FindChangePriceData = () => {
			this.setState({ UpData: [] })
			let ID = this.props.ItemData.ID
			let hospDr = this.state.priceHospID
			let data = {}
			data = {
				params: [{
					itemID: ID,
					hospID: hospDr,
					effectiveflag: this.state.effectiveflag,
					logonGroupID: this.state.sessionData.groupID,
					logonHospID: this.state.sessionData.hospID,
				}],
				pagination: [{
					pageSize: 10,
					currentPage: 1,
					sortColumn: "Code",
					sortOrder: "asc"
				}]
			}
			$http.post('urlS', this, {
				code: '05100022',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0 && res.result.Data) {
						for (var i = 0; i < res.result.Data.length; i++) {
							res.result.Data[i].key = i
						}
						this.setState({ uplistkey: res.result.Data.length + 1 })
						this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false })
					} else {
						this.setState({ data: [], total: 0, loading: false, uplistkey: 1 })
					}
				}
			})
		}

		selectloadData = () => {
			let data = {}
			data = {
				params: [{
					code: '',
					className: ''
				}]
			}
			$http.post('urlS', this, {
				code: '05100082',
				data: data,
				success: function (res) {
					// if (+res.errorCode === 0 && res.AdmReasonData) {
					//   for(var i = 0; i < res.AdmReasonData.length; i++) {
					//     this.state.AdmReasonData.push(<Option value={res.AdmReasonData[i].ID} title='admReasonID' key={i}>{res.AdmReasonData[i].Descripts}</Option>)
					//   }
					// }
					if (+res.errorCode === 0 && res.GradeData) {
						for (var i = 0; i < res.GradeData.length; i++) {
							this.state.GradeData.push(<Option value={res.GradeData[i].ID} title='gradeID' key={i}>{res.GradeData[i].Descripts}</Option>)
						}
					}
					this.setState({
						// AdmReasonData:this.state.AdmReasonData,
						GradeData: this.state.GradeData
					});
					this.payOffData()  //.费别
				}
			})
		}

		//.费别
		payOffData = () => {
			let data = {
				params: [{
					"hospID": this.state.priceHospID,
				}]
			}
			$http.post('urlS', this, {
				code: "05100129",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ AdmReasonData: res.data })
					}
				}
			})
		}

		GetHospData = () => {
			let data = {
				params: [{
					hospitalId: this.state.sessionData.hospID,
					logonGroupID: this.state.sessionData.groupID,
					logonHospID: this.state.sessionData.hospID,
					dataType: "combo",
				}]
			}
			$http.post('urlS', this, {
				code: '05100046',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0 && res.Hosp) {
						for (var i = 0; i < res.Hosp.length; i++) {
							if (res.Hosp[i].descripts !== "") {
								this.state.ItemHospData.push(<Option value={String(res.Hosp[i].id)} key={i}>{res.Hosp[i].descripts}</Option>)
								this.state.PriceHospData.push(<Option value={String(res.Hosp[i].id)} key={i}>{res.Hosp[i].descripts}</Option>)
							}
						}
						this.setState({ ItemHospData: this.state.ItemHospData, PriceHospData: this.state.PriceHospData })
					}
				}
			})
		}

		ItemHospChange = (value) => {
			if (this.state.Authoritydata.gridData.add ? (this.state.Authoritydata.gridData.add.indexOf(value) === -1 & this.state.Authoritydata.gridData.add.indexOf("ALL") === -1) ? true : false : true) {
				message.error('你没有该医院的权限！！！', 0.8);
				value = ''
			}
			setTimeout(() => {
				this.selectItemHosploadData(value)
				this.setState(preState => ({
					hospSubData: { ...preState.hospSubData, hospID: value }
				}))
			}, 0)

		}

		//医院下拉框值
		handlehospChange = (field, value) => {
			value = typeof value === 'undefined' ? '' : value
			this.setState(preState => ({
				hospSubData: { ...preState.hospSubData, [field]: value }
			}))
		}

		///医院类型
		selectItemHosploadData = (value) => {
			this.GetItemHospOnlyone(value)
			this.setState({
				hospSubData: {},
				hospTCSUBData: [],
				hospMCSUBData: [],
				hospICSUBData: [],
				hospOCSUBData: [],
				hospECSUBData: [],
				hospACSUBData: [],
			})
			if (typeof value === 'undefined') {
				return
			}
			if (value === "") {
				return
			}
			let data = {}
			data = {
				params: [{
					code: '',
					className: '',
					hospID: value,
					tartype: "SUB",
				}]
			}
			$http.post('urlS', this, {
				code: '05100011',
				data: data,
				success: function (res) {

					if (+res.errorCode === 0 && res.TCSUBData) {
						for (var i = 0; i < res.TCSUBData.length; i++) {
							this.state.hospTCSUBData.push(<Option value={String(res.TCSUBData[i].ID)} title='tcsubID' key={i}>{res.TCSUBData[i].Descripts}</Option>)
						}
						this.setState({ hospTCSUBData: this.state.hospTCSUBData })
					}

					if (+res.errorCode === 0 && res.ICSUBData) {
						for (var i = 0; i < res.ICSUBData.length; i++) {
							this.state.hospICSUBData.push(<Option value={String(res.ICSUBData[i].ID)} title='icsubID' key={i}>{res.ICSUBData[i].Descripts}</Option>)

						}
						this.setState({ hospICSUBData: this.state.hospICSUBData })
					}
					if (+res.errorCode === 0 && res.OCSUBData) {
						for (var i = 0; i < res.OCSUBData.length; i++) {
							this.state.hospOCSUBData.push(<Option value={String(res.OCSUBData[i].ID)} title='ocsubID' key={i}>{res.OCSUBData[i].Descripts}</Option>)

						}
						this.setState({ hospOCSUBData: this.state.hospOCSUBData })
					}
					if (+res.errorCode === 0 && res.ECSUBData) {
						for (var i = 0; i < res.ECSUBData.length; i++) {
							this.state.hospECSUBData.push(<Option value={String(res.ECSUBData[i].ID)} title='ecsubID' key={i}>{res.ECSUBData[i].Descripts}</Option>)

						}
						this.setState({ hospECSUBData: this.state.hospECSUBData })
					}
					if (+res.errorCode === 0 && res.ACSUBData) {
						for (var i = 0; i < res.ACSUBData.length; i++) {
							this.state.hospACSUBData.push(<Option value={String(res.ACSUBData[i].ID)} title='acsubID' key={i}>{res.ACSUBData[i].Descripts}</Option>)

						}
						this.setState({ hospACSUBData: this.state.hospACSUBData })
					}
					if (+res.errorCode === 0 && res.MCSUBData) {
						for (var i = 0; i < res.MCSUBData.length; i++) {
							this.state.hospMCSUBData.push(<Option value={String(res.MCSUBData[i].ID)} title='mcsubID' key={i}>{res.MCSUBData[i].Descripts}</Option>)
						}
						this.setState({ hospMCSUBData: this.state.hospMCSUBData })
					}
				}
			})
		}

		//单个收费项医院表数据查询
		GetItemHospOnlyone = (value) => {
			if (typeof value === 'undefined') {
				return
			}
			if (value === "") {
				return
			}
			let data = {}
			data = {
				params: [{
					code: '',
					className: '',
					hospID: value,
					itemID: this.props.ItemData.ID
				}]
			}
			$http.post('urlS', this, {
				code: '05100075',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0 && res.result) {
						let ICSubID = res.result.Data[0].hospItemICsubID
						let TCSubID = res.result.Data[0].hospItemTCsubID
						let MCSubID = res.result.Data[0].hospItemMCsubID
						let OCSubID = res.result.Data[0].hospItemOCsubID
						let ECSubID = res.result.Data[0].hospItemECsubID
						let ACSubID = res.result.Data[0].hospItemACsubID
						this.setState(preState => ({
							hospSubData: {
								...preState.hospSubData,
								icsubID: ICSubID,
								tcsubID: TCSubID,
								ocsubID: OCSubID,
								mcsubID: MCSubID,
								ecsubID: ECSubID,
								acsubID: ACSubID,
							}
						}))
					}
				}
			})
		}

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

		// 显示弹出层
		showModal = () => {
			this.setState({
				visible: true,
				ItemHospData: [],
				PriceHospData: [],
				admReasonID: '',
				gradeID: '',
				admReasonDesc: '',
				gradeDesc: '',
				Buttondisplay: 'none',
				price: '',
				UpData: [],
				uplistkey: 0,
				stDate: moment(new Date(new Date().setDate(new Date().getDate() + 1))).format('YYYY-MM-DD'),

			});
			this.clearsubdata()
			setTimeout(() => {
				let ItemID = this.props.ItemData.ID
				this.handleItmQuery(ItemID)   ///子表数据去查询主表数据
				this.setState({
					itemID: ItemID,
					Authoritydata: this.props.Authoritydata,
					priceHospID: this.props.ItemData.itemHospID,
					priceHospDesc: typeof this.props.ItemData.itemHospDesc !== 'undefined' ? this.props.ItemData.itemHospDesc : '',
				}, () => {
					this.payOffData()
				});
				this.GetHospData()
				let value = this.props.ItemData.itemHospID
				this.selectItemHosploadData(value)
				this.setState(preState => ({
					hospSubData: { ...preState.hospSubData, hospID: value }
				}))
				this.FindChangePriceData()
			}, 0)
		}

		// 取消
		handleCancel = () => {
			this.setState({
				visible: false,
			});
		}

		handleUpdate = () => {
			message.config({
				top: '30%'
			});
			let itemID = typeof this.props.ItemData.ID !== 'undefined' ? this.props.ItemData.ID : ""
			if (itemID === "") {
				message.error('请选择收费项目再进行操作！！！', 0.8);
				return
			}
			let hospID = typeof this.state.hospSubData.hospID !== 'undefined' ? this.state.hospSubData.hospID !== '' ? this.state.hospSubData.hospID : "" : ""
			if (hospID === "") {
				message.error('请选择医院！！！', 0.8);
				return
			}
			if ((itemID !== "") && (this.state.Authoritydata.gridData.add ? (this.state.Authoritydata.gridData.add.indexOf(this.state.hospSubData.hospID) === -1 & this.state.Authoritydata.gridData.add.indexOf("ALL") === -1) ? true : false : true)) {
				message.error('你没有该医院的修改权限！！！', 0.8);
				return
			}

			let tcnum = typeof this.state.hospSubData.tcsubID !== 'undefined' ? this.state.hospSubData.tcsubID !== '' ? 1 : 0 : 0
			let mcnum = typeof this.state.hospSubData.mcsubID !== 'undefined' ? this.state.hospSubData.mcsubID !== '' ? 1 : 0 : 0
			let icnum = typeof this.state.hospSubData.icsubID !== 'undefined' ? this.state.hospSubData.icsubID !== '' ? 1 : 0 : 0
			let ocnum = typeof this.state.hospSubData.ocsubID !== 'undefined' ? this.state.hospSubData.ocsubID !== '' ? 1 : 0 : 0
			let ecnum = typeof this.state.hospSubData.ecsubID !== 'undefined' ? this.state.hospSubData.ecsubID !== '' ? 1 : 0 : 0
			let acnum = typeof this.state.hospSubData.acsubID !== 'undefined' ? this.state.hospSubData.acsubID !== '' ? 1 : 0 : 0
			let hosnum = typeof this.state.hospSubData.hospID !== 'undefined' ? this.state.hospSubData.hospID !== '' ? 1 : 0 : 0
			let num = tcnum + mcnum + icnum + ocnum + ecnum + acnum
			if ((num > 0) && (num < 6)) {
				message.error('医院信息不完整,不能保存！！！', 0.8);
				return
			}
			if ((num === 6) && (hosnum < 1)) {
				message.error('请选择医院！！！', 0.8);
				return
			}
			const { form: { validateFields } } = this.props;
			validateFields((errors, values) => {
				// 验证成功
				if (errors === null) {
					let data = {
						params: [{
							logonGroupID: this.state.sessionData.groupID,
							logonHospID: this.state.sessionData.hospID,
							updateUserID: this.state.sessionData.userID,
							itemID: this.props.ItemData.ID,
							hospSubData: this.state.hospSubData
						}]
					}
					$http.post('urlADS', this, {
						code: '05100074',
						data: data,
						success: function (res) {
							if (+res.errorCode === 0) {
								// 提示
								message.success('保存医院信息成功');
							}
						},
						error: function (error) {
							message.error('保存医院信息保存失败：' + error);
						}
					})
				}

			});

		}

		disabledStartDate = (stDate) => {
			return stDate < moment();
		}

		disabledEndDate = (endDate) => {
			if (!this.state.stDate) {
				return true;
			}
			let data = this.state.stDate < moment().format('YYYY-MM-DD') ? moment().format('YYYY-MM-DD') : this.state.stDate
			return moment(endDate).format('YYYY-MM-DD') < data;
		}

		onChangeDate = (field, value) => {
			this.setState({
				[field]: moment(value).format('YYYY-MM-DD'),
			});
		}

		chkPrice = (value) => { //方法1
			this.setState({
				price: value,
			});
		}

		// 售价
		chkPrice = (e) => {
			this.setState({
				price: e.target.value,
			});
		}

		// 设置行属性
		ChangeonRow = (record) => {
			return {
				// 单击行选中
				onClick: () => {
					if (this.state.Pricerowid === "") {
						this.setState({
							Pricerowid: record.ID,
						});
					} else {
						if (this.state.Pricerowid !== record.ID) {
							this.setState({
								Pricerowid: record.ID,
							});
						} else {

						}
					}
					this.clearsubdata()
				},
				// 双击行编辑
				onDoubleClick: () => {
					if (record.ID !== '') {
						//存在表的记录是修改，添加到上面去保存
						this.setState({
							ChargeInfo: record,
							Pricerowid: record.ID,
							stDate: record.priceStDate,
							endDate: record.priceEndDate,
							admReasonID: record.priceAdmReasonID,
							price: record.price,
							chargeCode: record.priceChargeCode,
							remarks: record.priceRemarks,
							gradeID: record.priceGradeID,
							priceHospID: record.hospID,
							Buttondisplay: ""
						});
					}
					else {
						//不是表的记录，直接删除
						const DelDataSource = this.state.data;      //列表数组
						DelDataSource.splice(event.target.getAttribute('data-index'), 1);//data-index为获取索引，后面的1为一次去除几行
						const DelDataUpData = this.state.UpData;    //列表数组
						DelDataUpData.splice(event.target.getAttribute('data-index'), 1);//data-index为获取索引，后面的1为一次去除几行
						this.setState({
							data: DelDataSource,
							UpData: DelDataUpData,
						});
					}
					this.setState({
						Chargerowid: record.ID,
					});
				},
			}
		}

		clearsubdata = () => {
			this.setState({
				Buttondisplay: 'none',
				Pricerowid: "",
				ChargeInfo: {},
				stDate: moment(new Date(new Date().setDate(new Date().getDate() + 1))).format('YYYY-MM-DD'),
				endDate: null,
				admReasonID: '',
				price: '',
				chargeCode: '',
				remarks: '',
				gradeID: '',
				admReasonDesc: "",
				gradeDesc: "",
				priceHospDesc: typeof this.props.ItemData.itemHospDesc !== 'undefined' ? this.props.ItemData.itemHospDesc : '',
				priceHospID: typeof this.props.ItemData.itemHospID !== 'undefined' ? this.props.ItemData.itemHospID : '',
			})
		}

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

		PriceHospChange = (value, option) => {
			this.setState({
				priceHospID: value,
				priceHospDesc: option.props.children,
				admReasonID: '',
			}, () => {
				this.FindChangePriceData()
				this.payOffData()  //.费别
			})
		}

		AdmReasonChange = (value, option) => {
			this.setState({
				admReasonID: value,
				admReasonDesc: option.props.children
			})
		}

		GradeChange = (value, option) => {
			this.setState({
				gradeID: value,
				gradeDesc: option.props.children
			})
		}

		onChangeTxT = (field, e) => {
			this.setState({ [field]: e.target.value });
		}

		///d条件查询
		Changetiveflag = (value, option) => {
			this.setState({
				[option.props.title]: value
			})
			this.clearsubdata()
			setTimeout(() => {
				this.FindChangePriceData()
			}, 0)
		}

		addTable = () => {
			console.log(this.state.price)
			if (parseFloat(this.state.price) < 0) {
				message.error('价格不能小于0')
				return false
			}

			if (this.state.Authoritydata.gridData.add ? (this.state.Authoritydata.gridData.add.indexOf(this.state.priceHospID) > -1 || this.state.Authoritydata.gridData.add.indexOf("ALL") > -1) ? true : false : true) { }
			else {
				message.error('你没有该医院的添加权限！！！', 0.8);
				return
			}
			if (this.state.admReasonID === '') {
				message.config({
					top: '50%'
				});
				message.error('请选择费别', 0.8);
				return
			}
			if (this.state.stDate === '') {
				message.config({
					top: '50%'
				});
				message.error("开始日期不能为空", 0.8);
				return
			}
			if (this.state.price === '') {
				message.config({
					top: '50%'
				});
				message.error('请输入价格', 0.8);
				return
			}
			let obj = {};
			obj.priceAdmReasonID = this.state.admReasonID
			obj.priceAdmReasonDesc = this.state.admReasonDesc
			obj.price = this.state.price
			obj.priceChargeCode = this.state.chargeCode
			obj.priceRemarks = this.state.remarks
			obj.priceStDate = moment(this.state.stDate).format('YYYY-MM-DD')
			obj.priceEndDate = this.state.endDate
			obj.ID = ''
			obj.priceGradeID = this.state.gradeID
			obj.priceGradeDesc = this.state.gradeDesc
			obj.pricehospID = this.state.priceHospID
			obj.pricehospDesc = this.state.priceHospDesc
			var olddata = this.state.data;
			var key = Number(this.state.uplistkey) + 1
			obj.key = key
			var oldUpData = this.state.UpData
			var objata = []
			objata.push(obj)
			var Newdata = objata.concat(olddata)
			var NewUpData = objata.concat(oldUpData)
			this.setState({
				data: Newdata,
				UpData: NewUpData,
				uplistkey: key,
			});
			this.clearsubdata()
		}

		///插入价格
		handleinsetPrice = () => {
			if (JSON.stringify(this.state.UpData) === "[]") {
				message.error('没有可插入的价格信息！！！', 0.8);
				return
			}
			const { form: { validateFields } } = this.props;
			validateFields((errors, values) => {
				// 验证成功
				if (errors === null) {
					let data = {
						params: [{
							updateUserID: this.state.sessionData.userID,
							itemID: this.props.ItemData.ID,
							UpData: this.state.UpData
						}]
					}
					$http.post('urlADS', this, {
						code: '05100023',
						data: data,
						success: function (res) {
							if (+res.errorCode === 0) {
								// 提示
								message.success('收费项价格保存成功');
								this.FindChangePriceData()
							}
						},
						error: function (error) {
							message.error('收费项价格保存失败：' + error);
							this.FindChangePriceData()
						}
					})
				}
			});
		}

		///修改收费项价格信息
		handleUpdatePrice = () => {
			if ((this.state.Authoritydata.gridData.update ? this.state.Authoritydata.gridData.update.indexOf(this.state.priceHospID) > -1 ? true : false : true) || (this.state.Authoritydata.gridData.update ? this.state.Authoritydata.gridData.update.indexOf("ALL") > -1 ? true : false : true)) {

			}
			else {
				if (this.props.ItemData.ID !== "") {
					message.error('你没有该医院的修改权限！！！', 0.8);
					return
				}
			}
			const { form: { validateFields } } = this.props;
			validateFields((errors, values) => {
				// 验证成功
				if (errors === null) {
					let data = {
						params: [{
							updateUserID: this.state.sessionData.userID,
							itemID: this.props.ItemData.ID,
							endDate: this.state.endDate,
							chargeCode: this.state.chargeCode,
							remarks: this.state.chargeCode,
							chargeCode: this.state.chargeCode,
							priceID: this.state.ChargeInfo.ID,
						}]
					}
					$http.post('urlADS', this, {
						code: '05100047',
						data: data,
						success: function (res) {
							if (+res.errorCode === 0) {
								// 提示
								message.success('收费项价格保存成功');
								this.FindChangePriceData()
							}
						},
						error: function (error) {
							message.error('收费项价格保存失败：' + error);
							this.FindChangePriceData()
						}
					})
				}

			});

		}

		render() {
			this.state.sessionData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {}
			return (
				<div className='greeTab'>
					<InsuLinkCharge itmID={this.props.ItemData.ID} key={this.props.ItemData.ID} />
				</div>
				// </Modal>
			);
		}
	});
export default FormHandel;
FormHandel.propTypes = {
	// 验证userInfo的属性
	userInfo: PropTypes.object
}
