//对折扣申请进行审批 
import React from 'react'
import { Table, Button, Form, Row, Col, message, InputNumber } from 'antd'
import { $http } from '../../../containers/config/https';
import TipHeader from '../charges/component/TipHeader';
import '../charges/style/style.less';
import { Util } from 'tools/index';

class PatientAdmOrderChargesApply extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			userInfo: {},
			admID: '',
			dataPatChar: [], // 挂号table数据
			dataCharges: [],      //医嘱收费项table数据
			dataChargesBkp: [],      //医嘱收费项table数据备份
			total: 0,
			page: 1,
			pageSize: 50,
			selectedRowKeys: [],
			limitedAmt: '',
			limitedPercent: '',
			coupon: 0,
			totalAmt: 0,    // 总价
		}

		this.columns = [
			{
				title: '挂号时间',
				dataIndex: 'admDateTime',
				width: 200,
				align: 'center',
			},
			{
				title: '科室',
				dataIndex: 'admLocDesc',
				width: 100,
				align: 'center',
			},
			{
				title: '医生',
				dataIndex: 'admDocDesc',
				width: 100,
				align: 'center',
			},
			{
				title: '接待人',
				dataIndex: '',
				width: 100,
				align: 'center',
			},
			{
				title: '诊断名称',
				dataIndex: 'diagnose',
				width: 150,
				align: 'center',
			}
		]
		this.selectFocus = React.createRef();
		this.orderColumns = [
			// {
			//     title: '医嘱ID',
			//     dataIndex: 'detailID',
			//     width: 100,
			//     align: 'center',
			// },
			{
				title: '医嘱名称',
				dataIndex: 'medItemDesc',
				width: 150,
				align: 'center',
			},
			{
				title: '收费项代码',
				dataIndex: 'itemCode',
				width: 100,
				align: 'center',
			},
			{
				title: '收费项名称',
				dataIndex: 'itemDesc',
				width: 200,
				align: 'center',
			},
			{
				title: '医保代码',
				dataIndex: '',
				width: 100,
				align: 'center',
			},
			{
				title: '价格',
				dataIndex: 'price',
				width: 100,
				align: 'center',
			},
			{
				title: '数量',
				dataIndex: 'qty',
				width: 100,
				align: 'center',
			},
			{
				title: '金额',
				dataIndex: 'totalPrice',
				width: 100,
				align: 'center',
			},
			{
				title: '优惠金额',
				dataIndex: 'discountAmt',
				width: 100,
				align: 'center',
				render: (text, data, index) => {
					let displayDiscountAmt = data.discountAmt ? parseFloat(data.discountAmt).toFixed(2) : 0
					let disabledflag = false;
					if (this.state.selectedRowKeys.includes(index)) {
						if (this.state.coupon == 0 || this.state.coupon == '') {
							disabledflag = false
						}
						else {
							disabledflag = true
						}
					}
					return <InputNumber min={-999999999.0000} max={parseFloat(data.totalPrice)} style={{ width: '95%' }} id={"discountAmt-input" + index} ref={this.selectFocus}
						value={displayDiscountAmt}
						onChange={(val) => this.calcDiscount(index, val)}
						disabled={
							data.ordSelect === 'Y' ? true : disabledflag}
					/>
				}
			},
			// {
			//     title: '限定价格',
			//     dataIndex: 'limitedPrice',
			//     width: 100,
			//     align: 'center',
			//     render: (text, data, index) => {
			//         return <InputNumber min={0} max={data.price} style={{ width: '95%' }} id={"limitedPrice-input" + index} ref={this.selectFocus}
			//             value={data.limitedPrice}
			//             onChange={(val) => this.handLimitedPrice(index, val)}
			//             disabled={data.ordSelect==='Y' ? true : false}
			//         />
			//     } 
			// },
			{
				title: '限定折扣',
				dataIndex: 'limitedPercent',
				width: 100,
				align: 'center',
				render: (text, data, index) => {
					let displayLimitedPercent = data.limitedPercent ? parseFloat(data.limitedPercent).toFixed(2) : 0
					let disabledflag = false;
					if (this.state.selectedRowKeys.includes(index)) {
						if (this.state.coupon == 0 || this.state.coupon == '') {
							disabledflag = false
						}
						else {
							disabledflag = true
						}
					}
					return <InputNumber max={50.0000} min={0} style={{ width: '95%' }} id={"limitedPercent-input" + index} ref={this.selectFocus}
						value={displayLimitedPercent}
						onChange={(val) => this.handLimitedPercent(index, val)}
						disabled={data.ordSelect === 'Y' ? true : disabledflag}
					/>
				}
			}
			,
			{
				title: '备注',
				dataIndex: 'remarks',
				width: 450,
				align: 'center',
			},
			{
				title: '详情描述',
				dataIndex: 'applyflagDesc',
				width: 300,
				align: 'center',
			}
			,
			{
				title: '不可审批原因',
				dataIndex: 'reason',
				width: 450,
				align: 'center',
			}

		]
	}

	static getDerivedStateFromProps(nextProps, prevState) {
		// 该方法内禁止访问this
		if (('userInfo' in nextProps && (JSON.stringify(nextProps.userInfo) !== JSON.stringify(prevState.userInfo)))) {
			// 通过对比nextProps和prevState，返回一个用于更新状态的对象
			return {
				userInfo: nextProps.userInfo,
				admID: nextProps.userInfo.admID
			}
		}
		// 不需要更新状态，返回null
		return null
	}

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

	componentDidUpdate(prevProps, prevState) {
		if ('userInfo' in prevProps && (JSON.stringify(prevProps.userInfo) !== JSON.stringify(this.state.userInfo))) {
			this.medicalInformation();
		}
	}

	// 填写优惠价时自动勾选
	autoCheck = (index) => {
		let { selectedRowKeys } = this.state
		if (!selectedRowKeys.includes(index)) {
			selectedRowKeys.push(index)
			this.setState({ selectedRowKeys })
		}
	}

	// 计算折扣平均值
	calcDiscountAvg = () => {
		//此处只做粗略的计算，审核处还会重新计算
		let { coupon, selectedRowKeys, dataCharges, dataChargesBkp } = this.state;
		if (!coupon) coupon = 0
		let totalAmt = 0
		let len = selectedRowKeys.length;
		for (let i = 0; i < len; i++) {
			totalAmt = totalAmt + dataCharges[selectedRowKeys[i]].totalPrice
		}
		if (coupon > totalAmt) {
			coupon = totalAmt
		}

		let avgPercent = parseFloat(1 - (coupon / totalAmt)).toFixed(8)
		let discountedAmt = 0   // 已优惠金额
		let totlamterr = parseFloat(coupon)
		let lastkey = 0
		// let avg = (coupon / len).toFixed(2)
		for (let i = 0; i < len; i++) {
			let paytotalamt = parseFloat(dataCharges[selectedRowKeys[i]].modelTotalAmt)
			dataCharges[selectedRowKeys[i]].limitedPercent = avgPercent
			let price = dataCharges[selectedRowKeys[i]].price       //总价格
			let discountedprice = (1 - avgPercent) * price                //优惠价格
			let qty = parseFloat(dataCharges[selectedRowKeys[i]].qty)
			let discountedAmt = parseFloat(discountedprice * qty).toFixed(2)
			totlamterr = totlamterr - discountedAmt
			dataCharges[selectedRowKeys[i]].discountAmt = discountedAmt;
			if (paytotalamt != 0) {
				lastkey = i
			}
		}
		if (totlamterr != 0) {
			let discountAmt = dataCharges[selectedRowKeys[lastkey]].discountAmt
			discountAmt = parseFloat(discountAmt) + parseFloat(totlamterr)
			let price = dataCharges[selectedRowKeys[lastkey]].price       //总价格
			let qty = parseFloat(dataCharges[selectedRowKeys[lastkey]].qty)
			let paytotalamt = price * qty
			let limitedPercent = parseFloat(1 - (discountAmt / paytotalamt)).toFixed(8)
			dataCharges[selectedRowKeys[lastkey]].limitedPercent = limitedPercent;
			dataCharges[selectedRowKeys[lastkey]].discountAmt = discountAmt
		}
		// 恢复未勾选
		for (let i = 0; i < dataChargesBkp.length; i++) {
			if (!selectedRowKeys.includes(i)) {
				dataCharges[i].discountAmt = ""
				dataCharges[i].limitedPercent = ""
			}
		}
		this.setState({ dataCharges, coupon })
	}

	calcDiscount = (index, val) => {
		let { dataCharges } = this.state;
		if (val) {
			dataCharges[index].discountAmt = val;
			dataCharges[index].limitedAmt = '';
			dataCharges[index].limitedPercent = parseFloat(1 - (val / dataCharges[index].totalPrice)).toFixed(8);
			dataCharges[index].limitedPrice = '';
			// 处理分母为0
			if (!dataCharges[index].totalPrice) {
				dataCharges[index].limitedPercent = 1
			}
			this.setState({ dataCharges }, () => this.autoCheck(index))
		}
	}

	// handLimitedAmt = (index, val) => {
	//     let { dataCharges } = this.state;
	//     if (val) {
	//         dataCharges[index].limitedAmt = val;
	//         dataCharges[index].limitedPercent = '';
	//         dataCharges[index].limitedPrice = '';
	//         this.setState({ dataCharges }, () => this.autoCheck(index))
	//     }
	// }

	handLimitedPercent = (index, val) => {
		let { dataCharges } = this.state;
		if (val) {
			dataCharges[index].discountAmt = (dataCharges[index].totalPrice * (1 - val)).toFixed(8);
			dataCharges[index].limitedAmt = '';
			dataCharges[index].limitedPercent = val;
			dataCharges[index].limitedPrice = '';
			this.setState({ dataCharges }, () => this.autoCheck(index))
		}
	}

	// handLimitedPrice = (index, val) => {
	//     let { dataCharges } = this.state;
	//     if (val) {
	//         dataCharges[index].limitedAmt = '';
	//         dataCharges[index].limitedPercent = '';
	//         dataCharges[index].limitedPrice = val;
	//         this.setState({ dataCharges }, () => this.autoCheck(index))
	//     }
	// }

	// 就诊信息
	medicalInformation = () => {
		let { userInfo, admID } = this.state
		let data = {
			params: [{
				hospID: JSON.parse(window.sessionStorage.userData).hospID || '', //医院id 
				admID: admID, //就诊id
				patID: userInfo?.patID
			}],
		}

		$http.post('urlS', this, {
			code: "05210003",
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					this.setState({
						dataPatChar: res.admInfo || [], // // 挂号table数据
					}, () => this.orderCharges());
				}
			}
		});
	}

	// 医嘱收费项
	orderCharges = () => {
		let selectedRowKeys = []
		let { page, pageSize, admID } = this.state;
		var data = {
			params: [{
				hospID: JSON.parse(window.sessionStorage.userData).hospID || '',
				admID: admID || '',
				locID: JSON.parse(window.sessionStorage.userData).locID || '',
				groupID: JSON.parse(window.sessionStorage.userData).groupID || ''
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page,
				sortColumn: 'code',
				sortOrder: 'asc'
			}]
		}

		$http.post('urlS', this, {
			code: "05210089",
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					let discountAmt = res.discountAmt
					let paytotalAmt = res.paytotalAmt
					let totalAmt = 0, dataChargesBkp = []
					for (let i = 0; i < res.total; i++) {
						if (res.result[i].ordSelect != 'Y') {
							selectedRowKeys.push(i)
						}
						totalAmt = totalAmt + res.result[i].totalPrice
						let bkpObj = {
							discountAmt: res.result[i].discountAmt,
							limitedPercent: res.result[i].limitedPercent
						}
						dataChargesBkp.push(bkpObj)
					}
					this.setState({
						dataCharges: res.result || [], // // 挂号table数据
						dataChargesBkp,
						total: res.total,
						selectedRowKeys,
						totalAmt,
						coupon: 0,
						discountAmt: discountAmt,
						paytotalAmt: paytotalAmt,
					});
				}
			}
		});
	}

	//审批
	priceApprove = () => {
		let { selectedRowKeys, dataCharges, admID } = this.state
		let arr = []
		for (let i = 0; i < selectedRowKeys.length; i++) {
			arr.push(dataCharges[selectedRowKeys[i]])
		}
		var data = {
			params: [{
				hospID: JSON.parse(window.sessionStorage.userData).hospID || '',
				userID: JSON.parse(window.sessionStorage.userData).userID || '',
				admID: admID || '',
				coupon: this.state.coupon,
				applyflag: this.props.applyflag ? this.props.applyflag : '',
				selectedRowKeys: arr
			}],
		}
		$http.post('urlS', this, {
			code: "05210070",
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					message.success("操作成功！")
					this.orderCharges()
					this.props.closeModal && this.props.closeModal()
				}
			}
		});
	}

	//取消审批
	cancelPriceApprove = () => {
		let { selectedRowKeys, dataCharges,admID } = this.state
		var data = {
			params: [{
				hospID: JSON.parse(window.sessionStorage.userData).hospID || '',
				userID: JSON.parse(window.sessionStorage.userData).userID || '',
				admID: admID || '',
				applyflag: this.props.applyflag ? this.props.applyflag : '',
				approvalflag: 'Y',
				selectedRowKeys: dataCharges
			}],
		}
		$http.post('urlS', this, {
			code: "05210071",
			data: data,
			success: function (res) {
				let errorCode = res.errorCode;
				if (errorCode === '0') {
					message.success("操作成功！")
					this.orderCharges()
					//this.props.closeModal()                    
				}
			}
		});
	}

	//单击类型事件
	onClickRow = (record) => {
		return {
			onClick: () => {
				this.setState({
					record: record,
					admID: record.admID
				}, () => {
					this.orderCharges()
				})
			}
		}
	}

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

	setDiscountRowClassName = (record) => {
		return record.discountAmt != '' ? 'clickRowStyle' : '';
	}

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

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

	render() {
		const { selectedRowKeys, userInfo } = this.state;
		const rowSelection = {
			selectedRowKeys,
			onChange: (selectedRowKeys) => {
				this.setState({ selectedRowKeys }, () => this.calcDiscountAvg())
			},
			getCheckboxProps: record => ({
				disabled: (record.ordSelect == 'Y' ? true : false),
			}),
		};

		return (
			<div>
				<div >
					<Row >
						<Col span={10} style={{ textAlign: 'center' }}>
							<Row >
								<Col span={23} style={{ height: '230px' }} >
									{!Util.isEmpty(userInfo) ? <TipHeader userInfo={userInfo} /> : null}
									<Row style={{ marginBottom: '10px' }}>
										金&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;额：{this.state.paytotalAmt}
									</Row>
									<Row style={{ marginBottom: '10px' }}>
										优惠抵扣金：{this.state.discountAmt}
									</Row>
									<Row>
										<Button type='primary' onClick={this.priceApprove} >审批</Button>
										<Button type='primary' onClick={this.cancelPriceApprove} style={{ marginLeft: '30px' }}>取消审批</Button>
									</Row>
								</Col>
							</Row>
							<Col span={1}
								style={{
									height: '100%',
									background: 'rgb(240, 242, 245)',
									float: 'right',
									position: 'absolute',
									right: '0px',
									top: '0px'
								}} >
							</Col>
						</Col>
						<Col span={14}>
							<div className="table-operations">
								<Row style={{ minHeight: '50px', paddingBottom: '10px', paddingLeft: '10px' }}>
									<Col span={23} >
										<Table
											className="outpatient-body"
											style={{ height: '200px' }}
											columns={this.columns}
											dataSource={this.state.dataPatChar}
											pagination={false}
											bordered={true}
											scroll={{ y: 160 }}
											onRow={this.onClickRow}
											rowClassName={this.setRowClassName}
										/>
									</Col>
								</Row>
							</div>
						</Col>
					</Row>
				</div>
				<div style={{ background: '#f0f2f5', height: '10px', widht: '100%' }}></div>
				<Row >
					<Table
						className="outpatient-body"
						style={{ height: '370px', padding: 10 }}
						columns={this.orderColumns}
						pagination={false}
						bordered={true}
						dataSource={this.state.dataCharges}
						scroll={{ x: 1800, y: 300 }}
						rowSelection={rowSelection}
						rowClassName={this.setDiscountRowClassName}
					/>
				</Row>
			</div>
		)
	}
}


export default Form.create()(PatientAdmOrderChargesApply)