// 退药申请
import React from 'react';
import { Card, Row, Col, DatePicker, Button, Input, Table, Select, message, Icon } from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import './style/index.less';
import ApplicationForRefund from './component/ApplicationForRefund';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

let {Option} = Select;

export default class HPApplicationDrugWithdrawal extends React.Component {
    constructor(props) {
        super(props);
        // var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            pharmacy: undefined, // 药房
            startDate: Moment(), // 开始日期 
            endDate: Moment(), // 结束日期
            basicHeight: 0,
            patientListSelectedRowKeys: [], // 病人列表选中的key值
            patientListSelectedRows: [], // 病人列表选中的行数据
            patientListRowId: '', // 病人列表选中行ID
            patientListColumns: [], // 病人列表表头数据
            patientListTableData: [], // 病人列表数据
            drugSubsidiaryColumns: [], // 药品明细表头数据
            drugSubsidiaryTableData: [], // 药品明细列表数据
            drugSubsidiarySelectedRowKeys: [], // 药品明细选中key值
            drugSubsidiarySelectedRows: [], // 药品明细选中行数据
            detailColumns: [], //表头列表
            detailTableWidth: '', //表头长度
        }
    }

    componentDidMount() {
        this.getPatientListColumns();
        this.handleQuery();
        this.getSelectData();
        this.setState({basicHeight: document.getElementById("apply-for-refund-medicine").clientHeight})
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state,callback)=>{ return; }
    }

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

     // 取发药下拉框数据集
	getSelectData = () => {
		let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02040028",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    let pharmacy=""; // 获取默认科室
                    for(var i = 0; i < res.recLoc.length; i++) {
                        if (res.recLoc[i].defaultFlag==="Y") {
                            pharmacy=res.recLoc[i].id
                            break;
                        }
                    }
                    this.setState({
                        selectData: res, pharmacy, 
                        startDate: res && res.startDate ? Moment(res.startDate) : Moment(),
						endDate: res && res.endDate ? Moment(res.endDate) : Moment(),
                    }, () => {
                        // this.getDrugSubsidiaryColumns(); // 获取药品明细表头数据
                        this.getDetailColumns();
                    })
				}
			}
		})
    }

    // 药房查询条件
    handlePharmacyOnChange = e => {
        this.setState({pharmacy: e})
    }

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

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

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

    // 获取病人列表表头数据
    getPatientListColumns = () => {
        let data = [
            {
                title: '病人登记号',
                dataIndex: 'patNo',
                width: '100px',
                align: "center",
            },
            {
                title: '病人姓名',
                dataIndex: 'patName',
                width: '80px',
                align: "center"
            },
            {
                title: '床号',
                dataIndex: 'bedNo',
                width: '80px',
                align: "center"
            },
        ]
        this.setState({patientListColumns: data})
    }

    // 获取病人列表数据
    getPatientListTableData = () => {
        let {pharmacy, startDate, endDate, patNameOrNO} = this.state;
        let data = {
			params: [{
				startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
				endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
                recLocID: pharmacy, // 药房科室ID
                patNameOrNO, // 登记号
                bedNo: patNameOrNO, // 床号
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: "02040029",
			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({patientListTableData: res.rows})
                    // this.setState({patientListTableData: res.rows, patNameOrNO: res.search})
                    this.handleReset();
				}
			}
		})
    }

    handlePatientListOnRow = (record) => {
        return {
            onClick: () => {
                let { patientListSelectedRowKeys, patientListSelectedRows } = this.state;
                let findFlag = false;
                let start = 0;
                if (patientListSelectedRowKeys) {
                    patientListSelectedRowKeys.find(function (value, key) {
                        if (value === record.key) {
                            //遍历找到选中的数据，并记录下选中数据在数组中的key
                            findFlag = true;
                            start = key;
                        }
                    })
                }
                if (findFlag) {
                    //再次点击移除选中
                    patientListSelectedRowKeys.splice(start, 1);
                    patientListSelectedRows.splice(start, 1);
                } else {
                    //将点击的行添加到选中
                    patientListSelectedRowKeys.push(record.key);
                    patientListSelectedRows.push(record);
                }
                if (this.state.patientListRowId === "") {
                    this.setState({
                        patientListRowId: record.key,
                        patientListSelectedRowKeys,
                        patientListSelectedRows
                    }, () => {
                        this.getDrugSubsidiaryTableData()
                    });
                } else {
                    if (this.state.patientListRowId !== record.key) {
                        this.setState({
                            patientListRowId: record.key,
                            patientListSelectedRowKeys,
                            patientListSelectedRows
                        }, () => {
                            this.getDrugSubsidiaryTableData()
                        })
                    } else {
                        this.setState({
                            patientListRowId: "",
                            patientListSelectedRowKeys,
                            patientListSelectedRows
                        }, () => {
                            this.getDrugSubsidiaryTableData()
                        });
                    }
                }
            }
		}
    }

    handlePatientListRowClassName = (record) => {
        return (("^" + this.state.patientListSelectedRowKeys.join("^") + "^").indexOf("^" + record.key + "^") > -1) ? 'clickRowStyle' : '';
    }

    // 请求退药数量/退药原因  reqQty
    handleCompileInputBox = (record, e, flag) => {
        let drugSubsidiaryTableData = JSON.parse(JSON.stringify(this.state.drugSubsidiaryTableData));
        for(let i = 0; i < drugSubsidiaryTableData.length; i++) {
            if (drugSubsidiaryTableData[i].inDispBatID === record.inDispBatID) {
                if (flag === 'reqQty') {
                    if (e.target.value < 1) {
                        drugSubsidiaryTableData[i].reqQty = undefined
                        break
                    } else {
                        drugSubsidiaryTableData[i].reqQty = e.target.value;
                        break;
                    }
                } else if (flag === 'reqReasonID') {
                    drugSubsidiaryTableData[i].reqReasonID = e;
                    break;
                }
               
            }
        }
        this.setState({drugSubsidiaryTableData})
    }

    // 获取药品明细表头数据
    getDrugSubsidiaryColumns = () => {
        let {selectData} = this.state;
        let reasonOption = selectData && selectData.reason && selectData.reason.length > 0 ? selectData.reason.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        }) : '';
        let data = [
            {
                title: '病人登记号',
                dataIndex: 'patNo',
                width: '80px',
                align: "center",
            },
            {
                title: '病人姓名',
                dataIndex: 'patName',
                width: '80px',
                align: "center"
            },
            {
                title: '床号',
                dataIndex: 'bedNO',
                width: '80px',
                align: "center"
            },
            {
                title: '发药数量',
                dataIndex: 'dispQty',
                width: '80px',
                align: "center"
            },
            {
                title: '已退数量',
                dataIndex: 'hasRet',
                width: '80px',
                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, 'reqQty')} />
				)
            },
            {
                title: '退药原因',
                dataIndex: 'reqReasonID',
                width: '150px',
                align: "center",
                render: (text, record) => (
                    <Select placeholder="请选择" style={{width: '80%'}} value={record.reqReasonID} onChange={(e) => this.handleCompileInputBox(record, e, 'reqReasonID')}>
                        {reasonOption}
                    </Select>
				)
            },
            {
                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"
            },
        ]
        this.setState({drugSubsidiaryColumns: data})
    }
    // 获取明细列表表头
    getDetailColumns = () => {
        let {selectData} = this.state;
        let reasonOption = selectData && selectData.reason && selectData.reason.length > 0 ? selectData.reason.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        }) : '';
        let data = {
            params: [{
                compontName: "HPApplicationDrugWithdrawal",
                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.columnRef.onOpenModel()}>{item.descripts}</div>,
                            render: (text, record)=>(
                                <span>
                                    {item.code == 'reqQty' ?
                                        <Input type="number" className="input-number" placeholder="请输入" style={{width: '80%'}} value={record.reqQty} onChange={(e) => this.handleCompileInputBox(record, e, 'reqQty')} />
                                    :
                                        item.code == 'reqReasonID' ?
                                            <Select placeholder="请选择" style={{width: '80%'}} value={record.reqReasonID} onChange={(e) => this.handleCompileInputBox(record, e, 'reqReasonID')}>
                                                {reasonOption}
                                            </Select>
                                            : text
                                    }
                                </span>
                            )
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({detailColumns: filterArr, detailTableWidth: res.totalWidth})
                }
            }
        })
    }
    // 获取药品明细列表数据
    getDrugSubsidiaryTableData = () => {
        let {patientListSelectedRows, selectData} = this.state;
        let arr = [];
        for(var i = 0; i < patientListSelectedRows.length; i++) {
            arr = arr.concat(patientListSelectedRows[i].inDispBat)
        }
        let data = {
			params: [{
				inDispBat: arr
			}]
		}
		$http.post('urlS', this, {
			code: "02040030",
			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].reqQty = Number(res.rows[i].dispQty)-Number(res.rows[i].hasReq)-Number(res.rows[i].hasRet);
                        res.rows[i].reqReasonID = selectData.reason && selectData.reason.length > 0 ? selectData.reason[0].id : undefined
                    }
                    this.setState({drugSubsidiaryTableData: res.rows})
				} else {
                    this.setState({drugSubsidiaryTableData: []})
                }
			}
		})
    }

    // 历史单据 
    handleHistoricalDocuments = () => {
        this.child.handleShowModal();
    }

    // 重置
    handleReset = () => {
        this.setState({
            patientListSelectedRowKeys: [],
            patientListSelectedRows: [],
            patientListRowId: [],
            drugSubsidiarySelectedRowKeys: [],
            drugSubsidiarySelectedRows: [],
            drugSubsidiaryTableData: []
        })
    }

    //保存
    handleSave = () => {
        let {drugSubsidiaryTableData, drugSubsidiarySelectedRowKeys} = this.state;
        let arr = [];
        for(var i = 0; i < drugSubsidiarySelectedRowKeys.length; i++) {
            arr.push(drugSubsidiaryTableData[drugSubsidiarySelectedRowKeys[i]])
        }
        arr = arr.map((item) => {
            return {
                inDispBatID: item.inDispBatID,
                reqQty: item.reqQty,
                reqReasonID: item.reqReasonID
            }
        })
        for(var i = 0; i < arr.length; i++) {
            if (!(arr[i].reqQty)) {
                message.error("请输入需要保存药品明细的请求退药数量");
                return;
            } else if (!(arr[i].reqReasonID)) {
                message.error("请选择需要保存药品明细的退药原因");
                return;
            }
        }
        let data = {
			params: arr
		}
		$http.post('urlS', this, {
			code: "02040031",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    message.success("保存成功");
                    this.handleReset(); // 重置列表数据
				}
			}
		})
    }

    // 病人登记号/姓名
    handlePatNameOrNO = e => {
        this.setState({patNameOrNO: e.target.value})
    }

    onPressEnterPatNameOrNO = () => {
        this.getPatientListTableData();
    }

    render() {
        let {pharmacy, startDate, endDate, basicHeight, patientListSelectedRowKeys, patientListSelectedRows, patientListColumns, patientListTableData,
            drugSubsidiaryColumns, drugSubsidiaryTableData, drugSubsidiarySelectedRowKeys, drugSubsidiarySelectedRows, patNameOrNO, selectData , detailTableWidth , detailColumns
        } = this.state;
        const patientListRowSelection = { // 病人列表
            selectedRowKeys: patientListSelectedRowKeys,
            selectedRows: patientListSelectedRows,
            onChange: (selectedRowKeys, selectedRows) => {
                // console.log(selectedRowKeys, selectedRows)
                let rowId= "";
                if (selectedRowKeys.length !== 0) {
                    rowId=selectedRowKeys[selectedRowKeys.length-1];
                }
                this.setState({patientListSelectedRowKeys: selectedRowKeys, patientListSelectedRows: selectedRows, patientListRowId: rowId}, () => {
                    this.getDrugSubsidiaryTableData()
                })
            }
        };
        const drugSubsidiaryRowSelection = { // 药品明细
            selectedRowKeys: drugSubsidiarySelectedRowKeys,
            selectedRows: drugSubsidiarySelectedRows,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({drugSubsidiarySelectedRowKeys: selectedRowKeys, drugSubsidiarySelectedRows: selectedRows})
            }
        }

        // 药房
        let pharmacyOption = selectData && selectData.recLoc && selectData.recLoc.length > 0 ? selectData.recLoc.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        }) : ''
        return (
            <div className="hospital-pharmacies">
                <Row id="apply-for-refund-medicine" style={{padding: '0 24px'}}>
                    <Col span={16}>
                        <div style={{marginBottom: '8px'}}>
                            药房：<Select value={pharmacy} onChange={this.handlePharmacyOnChange} showSearch optionFilterProp="seatchprop" placeholder="请选择" style={{width: '150px', margin: '8px 15px 0 0'}}>
                                {pharmacyOption}
                            </Select>
                            <DatePicker
                                value={startDate}
                                onChange={this.handleStartDate}
                                style={{width: '150px', marginTop: '8px'}}
                                placeholder="开始日期"
                                allowClear={false}
                            />
                            <span style={{display: 'inline-block', margin: '0 5px'}}>到</span>
                            <DatePicker 
                                value={endDate}
                                onChange={this.handleEndDate}
                                style={{width: '150px', marginRight: '15px'}} 
                                placeholder="结束日期"
                                allowClear={false}
                            />
                            <Button style={{marginTop: '8px'}} onClick={this.handleQuery}>查询</Button>
                        </div>
                    </Col>
                    <Col span={8} style={{textAlign: 'right'}}>
                        <Button
                            type="primary"
                            style={{margin: '8px 15px 0 0', width: '100px'}}
                            onClick={this.handleSave}
                            disabled={drugSubsidiarySelectedRows&&drugSubsidiarySelectedRows.length > 0 ? false : true}
                        >
                            保存
                        </Button>
                        <Button
                            style={{margin: '8px 15px 0 0', width: '100px'}}
                            onClick={this.handleReset}
                        >
                            重置
                        </Button>
                        <Button
                            type="dashed"
                            style={{marginTop: '8px', width: '100px'}}
                            onClick={this.handleHistoricalDocuments}
                        >
                            历史单据
                        </Button>
                    </Col>
                </Row>
                <div style={{height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%'}}></div>
                <Row>
                    <Col span={6}>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>病人列表</div>}
                        >
                            <div style={{height: store.getState().tableHeight.y + 174 - basicHeight + 'px', overflow: 'auto'}}>
                                <div style={{marginBottom: '12px'}}>
                                    <Input
                                        style={{width: '100%'}}
                                        placeholder="床号/姓名（Enter）"
                                        value={patNameOrNO}
                                        onChange={this.handlePatNameOrNO}
                                        onPressEnter={this.onPressEnterPatNameOrNO}
                                    />
                                </div>
                                <Table
                                    className="remove-td-default-bg"
                                    rowSelection={patientListRowSelection}
                                    columns={patientListColumns}
                                    dataSource={patientListTableData}
                                    bordered
                                    pagination={false}
                                    // scroll={{x: 260, y: store.getState().tableHeight.y + 160 - 75 - basicHeight}}
                                    onRow={this.handlePatientListOnRow}
                                    rowClassName={this.handlePatientListRowClassName}
                                />
                            </div>
                        </Card>
                    </Col>
                    <Col span={18}>
                        <div style={{paddingLeft: '6px', position: 'relative'}}>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>药品明细</div>}
                                extra={<span style={{color: '#666'}} className='span' onClick={() => this.columnRef.onOpenModel()}><Icon type="setting" title="列权限设置" /></span>}
                            >
                                <div style={{height: store.getState().tableHeight.y + 174 - basicHeight + 'px', overflow: 'auto'}}>
                                    <Table
                                        className="remove-td-default-bg inpatient-area"
                                        rowSelection={drugSubsidiaryRowSelection}
                                        columns={detailColumns.length>0 ? detailColumns : drugSubsidiaryColumns}
                                        dataSource={drugSubsidiaryTableData}
                                        bordered
                                        pagination={false}
                                        scroll={{x: detailTableWidth ? detailTableWidth : 1500, y: store.getState().tableHeight.y + 118 - basicHeight}}
                                    />
                                </div>
                            </Card>
                            <div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%'}}></div>
                        </div>
                    </Col>
                </Row>
                <ApplicationForRefund onRef={this.onRef} selectData={selectData} pharmacy={pharmacy} />
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='HPApplicationDrugWithdrawal'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getDetailColumns}
                />
            </div>
        )
    }
}