// 查询退药申请单
import React from 'react';
import {Modal, Input, Select, DatePicker, Button, Table, message} from 'antd';
import Moment from 'moment';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from 'containers/config/https';
import 'assets/css/common.css';
import '../style/index.less';

let {Option} = Select;

export default class ApplicationForRefund extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: Moment(),
            endDate: Moment(),
            patNoOrName: undefined,
            stateID: undefined,
            visible: false,
            applicationRowId: '', // 退药申请单选中行ID
            applicationColumns: [], // 退药申请表头数据
            applicationTableData: [], // 退药申请列表数据
            selectedRows: [], // 退药明细选中行数据
            selectedRowKeys: [], // 退药明细选中行key值
            detailColumns: [], // 退药明细表头数据
            detailDataSource: [], //退药明细列表数据
        };
        this.detailColumns = [
            {
                title: '发药数量',
                dataIndex: 'dispQty',
                width: '100px',
                align: "center",
            },
            {
                title: '请求数量',
                dataIndex: 'reqQty',
                width: '100px',
                align: "center",
                render: (text, record) => (
                    <Input type="number" className="input-number" placeholder="请输入" style={{width: '80%'}} value={record.reqQty} onChange={(e) => this.handleCompileInputBox(record, e)} />
				)
            },
            {
                title: '退药数量',
                dataIndex: 'retQty',
                width: '100px',
                align: "center"
            },
            {
                title: '退药日期',
                dataIndex: 'retDate',
                width: '100px',
                align: "center",
            },
            {
                title: '退药原因',
                dataIndex: 'reqReasonDesc',
                width: '100px',
                align: "center"
            },
            {
                title: '药品名称',
                dataIndex: 'stockDesc',
                width: '200px',
                align: "center"
            },
            {
                title: '剂型',
                dataIndex: 'formDesc',
                width: '100px',
                align: "center",
            },
            {
                title: '规格',
                dataIndex: 'stockSpec',
                width: '100px',
                align: "center"
            },
            {
                title: '用药时间',
                dataIndex: 'reqExecTime',
                width: '100px',
                align: "center"
            },
        ]
    }

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

    // 打开弹窗
    handleShowModal = () => {
        this.setState({visible: true}, () => {
            if (!(this.state.applicationColumns&&this.state.applicationColumns.length > 0)) {
                this.getApplicationColumns();
            }
            if (!(this.state.detailColumns&&this.state.detailColumns.length > 0)) {
                this.getDetailColumns();
            }
            this.getApplicationTableData();
        });
    }

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

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    // 获取退药申请单表头数据
    getApplicationColumns = () => {
        let data = {
            params: [{
                compontName: 'HPDrugWithdrawalLeft',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return  {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => {this.setState({parameterCode: 'HPDrugWithdrawalLeft'},()=>{
                                this.columnRef.onOpenModel();
                            }) }}>{item.descripts}</div>
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({applicationColumns: filterArr, detailWidthTotal: res.totalWidth})
                }
            }
        })
    }

    // 重置列表数据
    handleReset = () => {
        this.setState({applicationRowId: '', detailDataSource: [], selectedRows: [], selectedRowKeys: []})
    }

    // 3.2.3.2.5.查询住院退药申请单
    getApplicationTableData = () => {
        let {patNoOrName, stateID, startDate, endDate} = this.state;
        let data = {
			params: [{
				startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
				endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
                patNoOrName, // 姓名或登记号
                stateID, // 状态ID
                recLocID: this.props.pharmacy
			}]
		}
		$http.post('urlS', this, {
			code: "02040032",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    for(var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i
                    }
                    this.setState({applicationTableData: res.rows})
                    this.handleReset();
				}
			}
		})
    }

    // 退药申请单行操作
    handleApplicationOnRow = (record) => {
        return {
			// 单击行选中
			onClick: () => {
				if (this.state.applicationRowId === '') {
					// 保存行数据以及ID
					this.setState({applicationRowId: record.inReqID}, () => {
                        this.getDetailDataSource();
                    });
				} else {
					if (this.state.applicationRowId !== record.inReqID) {
						this.setState({applicationRowId: record.inReqID}, () => {
                            this.getDetailDataSource();
                        });
					}
				}
			}
		}
    }

    handleApplicationRowClassName = (record) => {
        return record.inReqID === this.state.applicationRowId ? 'clickRowStyle' : '';
    }

    handleCompileInputBox = (record, e) => {
        let detailDataSource = JSON.parse(JSON.stringify(this.state.detailDataSource));
        for(let i = 0; i < detailDataSource.length; i++) {
            if (detailDataSource[i].inReqBatID === record.inReqBatID) {
                detailDataSource[i].reqQty = e.target.value;
                break;
            }
        }
        this.setState({detailDataSource})
    }

    // 获取申请单明细表头
    getDetailColumns = () => {
        let data = {
            params: [{
                compontName: "HPDrugWithdrawal",
                type: 'C'
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return  {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => {this.setState({parameterCode: 'HPDrugWithdrawal'},()=>{
                                this.columnRef.onOpenModel();
                            }) }}>{item.descripts}</div>,
                            render: (text, record) => {
                                return (
                                    <span>
                                        {item.dataIndex === "reqQty" ? <Input type="number" className="input-number" placeholder="请输入" style={{width: '80%'}} value={record.reqQty} onChange={(e) => this.handleCompileInputBox(record, e)} /> : text}
                                    </span>
                                )
                            }
                        }
                    }) : '';
                    console.log(arr)
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({detailColumns: filterArr, wardAndPatientTableWidth: res.totalWidth})
                }
            }
        })
        // this.setState({detailColumns: data})
    }

    // 患者
    handlePatNoOrName = e => {
        this.setState({patNoOrName: e.target.value})
    }

    // 开始日期
    handleStartDate = e => {
        this.setState({startDate: e})
    }

    // 结束日期
    handleEndDate = e => {
        this.setState({endDate: e})
    }

    // 状态
    handleStateID = e => {
        this.setState({stateID: e})
    }

    // 3.2.3.2.6.查询住院退药申请单明细
    getDetailDataSource = () => {
        let {applicationRowId} = this.state;
        let data = {
			params: [{
                inReqID: applicationRowId
			}]
		}
		$http.post('urlS', this, {
			code: "02040033",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    for(var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i;
                        res.rows[i].hasRet = res.rows[i].hasRet ? res.rows[i].hasRet : 0
                    }
                    this.setState({detailDataSource: res.rows, selectedRows: [], selectedRowKeys: []})
				}
			}
		})
    }

    // 删除
    handleDelete = () => {
        let {selectedRows} = this.state;
        let data = {
			params: selectedRows
		}
		$http.post('urlS', this, {
			code: "02040035",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    message.success("删除成功");
                    this.getDetailDataSource(); // 重新查询退药申请列表
				}
			}
		})
    }

    // 查询
    handleQuery = () => {
        this.getApplicationTableData();
    }

    // 保存
    handleSave = () => {
        let {detailDataSource, selectedRowKeys} = this.state;
        let arr = [];
        for(var i = 0; i < selectedRowKeys.length; i++) {
            arr.push(detailDataSource[selectedRowKeys[i]])
        }
        arr = arr.map((item) => {
            return {
                inReqBatID: item.inReqBatID,
                reqQty: item.reqQty,
            }
        })
        let data = {
			params: arr
		}
		$http.post('urlS', this, {
			code: "02040034",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    message.success("保存成功");
                    this.handleReset(); // 重置列表数据
				}
			}
		})
    }

    render() {
        let {visible, applicationColumns, applicationTableData, selectedRows, selectedRowKeys, detailColumns, detailDataSource, patNoOrName, startDate,
            endDate, stateID
        } = this.state;
        const rowSelection = {
            selectedRowKeys,
            selectedRows,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({selectedRows, selectedRowKeys})
            }
        }
        // 药房
        let statusOption = this.props.selectData && this.props.selectData.status && this.props.selectData.status.length > 0 ? this.props.selectData.status.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        }) : ''
        return(
            <Modal
                visible={visible}
                title="查询退药申请单"
                footer={null}
                onCancel={this.handleCancel}
                width={1200}
                className="application-for-refund"
            >
                <div style={{height: '600px', overflow: 'auto'}}>
                    <div style={{marginBottom: '24px'}}>
                        患者：<Input placeholder="请输入" style={{width: '130px', marginRight: '8px'}} value={patNoOrName} onChange={this.handlePatNoOrName} />
                        单据生成日期：<DatePicker
                            style={{width: '130px'}}
                            placeholder="开始日期"
                            allowClear={false}
                            value={startDate}
                            onChange={this.handleStartDate}
                        />
                        <span style={{display: 'inline-block', margin: '0 5px'}}>到</span>
                        <DatePicker 
                            style={{width: '130px', marginRight: '8px'}} 
                            placeholder="结束日期"
                            allowClear={false}
                            value={endDate}
                            onChange={this.handleEndDate}
                        />
                        单据状态：<Select value={stateID} allowClear onChange={this.handleStateID} showSearch optionFilterProp="seatchprop" placeholder="请选择" style={{width: '130px', marginRight: '8px'}}>
                                {statusOption}
                            </Select>
                        <Button onClick={this.handleQuery}>查询</Button>
                        <div style={{float: 'right'}}>
                            <Button style={{marginRight: '8px'}} type="primary" onClick={this.handleSave} disabled={selectedRows&&selectedRows.length > 0 ? false : true}>保存</Button>
                            <Button type="danger" onClick={this.handleDelete} disabled={selectedRows&&selectedRows.length > 0 ? false : true}>删除</Button>
                        </div>
                    </div>
                    <div style={{height: '532px'}}>
                        {/* 退药申请单 */}
                        <div style={{height: '100%', overflow: 'hidden', width: '400px', display: 'inline-block', marginRight: '24px'}}>
                            <Table
                                columns={applicationColumns}
                                dataSource={applicationTableData}
                                bordered
                                pagination={false}
                                onRow={this.handleApplicationOnRow}
                                rowClassName={this.handleApplicationRowClassName}
                                scroll={{x: 640, y: 480}}
                                className="table-body-height"
                            />
                        </div>
                        {/* 退药申请单明细 */}
                        <div style={{height: '100%', overflow: 'hidden', width: '728px', display: 'inline-block'}}>
                            <Table
                                rowSelection={rowSelection}
                                columns={detailColumns&&detailColumns.length > 0 ? detailColumns : this.detailColumns}
                                dataSource={detailDataSource}
                                bordered
                                pagination={false}
                                scroll={{x: 1100, y: 480}}
                                className="table-body-height"
                            />
                        </div>
                    </div>
                </div>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName={this.state.parameterCode}
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={() => {
                        if (this.state.parameterCode == 'HPDrugWithdrawal') {
                            this.getDetailColumns()
                        }else if(this.state.parameterCode == 'HPDrugWithdrawalLeft'){
                            this.getApplicationColumns()
                        }
                    }
                    }
                />
            </Modal>
        )
    }
}