// 中草药发药
import React from 'react';
import {Card, Row, Col, DatePicker, Button, Select, Checkbox, Table, Input, message} from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import './style/index.less';
import RejectDispensingCause from './component/RejectDispensingCause';

let {Option} = Select;
let timeout;

export default class HPHerbalDispensing extends React.Component {
    constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            user: userData ? userData : {},
            pharmacy: userData.locID, // 药房
            startDate: Moment(), // 开始日期
            endDate: Moment(), // 结束日期
            selectData: {}, // 下拉框数据
            basicHeight: 0, // 查询框宽度
            wardID: undefined, // 病区
            wardSelectData: [], // 病区下拉框数据
            wardSelectedRows: [], // 选中的行数据
            wardSelectedRowKeys: [], // 病区选中行数key值
            wardColumns: [], // 病区table表头数据
            wardTableData: [], // 病区列表数据
            wardRowId: "", // 选中行id
            patNo: undefined, // 登记号
            mainInfo: [], // 处方饭预览数据
            patientColumns: [], // 患者表头数据
            patientTableData: [], // 患者列表数据
            dispCatData: [], // 发药类别
            patientRowId: '', // 患者列表选中行ID
            patientRowData: {}, // 患者列表选中行数据
        }
    }

    componentDidMount() {
        this.getPatientColumns();
        this.getSelectData();
        this.getWardTableData();
        this.getWardColumns();
        this.setState({basicHeight: document.getElementById("chinese-herbs-make-medicine").clientHeight})
    }

    // 取发药下拉框数据集
	getSelectData = () => {
		let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02040021",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    let dispCatData = res.dispCat&&res.dispCat.length > 0 ? res.dispCat.map((item) => {
                        return {
                            ...item,
                            checked: false,
                            disabled: true
                        }
                    }) : [];
					this.setState({selectData: res, dispCatData})
				}
			}
		})
    }

    // 拒绝发药窗口
    onRef = ref => {
        this.child = ref;
    }
    
    // 药房查询条件
    handlePharmacyOnChange = e => {
        this.setState({pharmacy: e})
    }

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

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

    // 请求病区下拉框数据(病区)
    handleWardSelectData = (value) => {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        timeout = setTimeout(() => {
            if (value) {
                let data = {
                    params: [{
                        alias: value
                    }]
                }
                $http.post('urlS', this, {
                    code: "02040003",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({wardSelectData: res.result})
                        }
                    }
                })
            }
        }, 300)
    }

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

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

    getWardColumns = () => {
        let columns = [
            {
                title: '病区',
                dataIndex: 'wardDesc',
                width: '150px',
                align: "center",
            },
        ];
        this.setState({wardColumns: columns})
    }

    // 病区
    handleWardOnChange = e => {
        this.setState({wardID: e}, () => {
            this.getWardTableData()
        })
    }

    // 获取病区列表数据
    getWardTableData = () => {
        let {pharmacy, startDate, endDate} = this.state;
        let data = {
			params: [{
				startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
				endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
                recLocID: pharmacy, // 药房科室
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: "02040022",
			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({wardTableData: res.rows})
                    this.resetTableData();
				}
			}
		})
    }

    // 重置表格数据
    resetTableData = () => {
        let dispCatData = JSON.parse(JSON.stringify(this.state.dispCatData));
        for(var i = 0; i < dispCatData.length; i++) {
            dispCatData[i].checked = false;
            dispCatData[i].disabled = true;
        }
        this.setState({
            dispCatData,
            wardSelectedRows: [],
            wardSelectedRowKeys: [],
            wardRowId: "",
            patientTableData: []
        })
    }

    // 登记号
    handlePatNoOnChange = e => {
        this.setState({patNo: e.target.value})
    }

    // 获取患者列表表头信息
    getPatientColumns = () => {
        let data = [
            {
                align: "center",
                code: "patNo",
                dataIndex: "patNo",
                descripts: "病人登记号",
                display: "Y",
                enDescripts: "",
                fixed: "",
                id: "26||2",
                seqNo: 1,
                title: "患者",
                width: "100px",
            },
            {
                align: "center",
                code: "patNo",
                dataIndex: "patNoss",
                display: "Y",
                enDescripts: "",
                fixed: "",
                id: "26||3",
                key: 2,
                title: "处方号",
                width: "100px",
            }
        ];
        this.setState({patientColumns: data})
    }

    // 获取患者列表
    getPatientTableData = () => {
        let {pharmacy, startDate, endDate, wardSelectedRows} = this.state;
        let wardData = JSON.parse(JSON.stringify(wardSelectedRows));
        let dispCatData = JSON.parse(JSON.stringify(this.state.dispCatData));
        let arr = [];
        for(var i = 0; i < dispCatData.length; i++) {
            if(dispCatData[i].checked) {
                arr.push(dispCatData[i].dispCatID)
            }
        }
        for(var i = 0; i <wardData.length; i++) {
            wardData[i].dispCat = arr
        }
        let data = {
            params: [{
                startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
				endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
				recLocID: pharmacy, // 药房科室ID
                ward: wardData, // 病区 
                priority: [], // 医嘱优先级
            }]
        }
        $http.post('urlS', this, {
            code: "02040041",
            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({patientTableData: res.rows})
                } else {
                    this.setState({patientTableData: []})
                }
            }
        })
    }

    // 修改checkbox
    changeCheckbox = (e, item) => {
        let dispCatData = JSON.parse(JSON.stringify(this.state.dispCatData));
        for(var i = 0; i < dispCatData.length; i++) {
            if (dispCatData[i].dispCatID === item.dispCatID) {
                dispCatData[i].checked = e.target.checked;
                break;
            }
        }
        this.setState({dispCatData}, () => {
            this.getPatientTableData();
        })
    }

    // 患者列表行操作
    handlePatientOnRow = record => {
        return {
            onClick: () => {
                if (this.state.patientRowId === "") {
                    this.setState({
                        patientRowId: record.key,
                        patientRowData: record
                    });
                } else {
                    if (this.state.patientRowId !== record.key) {
                        this.setState({
                            patientRowId: record.key,
                            patientRowData: record
                        });
                    }
                }
            }
		}
    }

    handlePatientRowClassName = (record) => {
        return record.key === this.state.patientRowId ? 'clickRowStyle' : '';
    }

    // 查询患者列表
    handleQueryDispensingDetail = () => {
        let {dispCatData, wardSelectedRows} = this.state;
        let arr = JSON.parse(JSON.stringify(dispCatData));
        let wardData = JSON.parse(JSON.stringify(wardSelectedRows));
        let dispCat = [];
        for(var i = 0; i < wardData.length; i++) {
            dispCat = dispCat.concat(wardData[i].dispCat)
        }
        let filterArr = [];
        for(var i = 0; i < arr.length; i++) {
            let dispCatID = arr[i].dispCatID;
            let isExist = false;
            let obj = arr[i];
            arr[i].checked = false;
            arr[i].disabled = false;
            for(var j = 0; j < dispCat.length; j++) {
                if (dispCatID === dispCat[j]) {
                    isExist = true
                    break;
                }
            }
            if (isExist) {
                obj.checked = true
            } else {
                obj.disabled = true
            }
            filterArr.push(obj)
        }
        this.setState({dispCatData: filterArr}, () => {
            this.getPatientTableData()
        })
    }

    // 住院发药
    handleHPDispensing = () => {
        let {pharmacy, patientRowData} = this.state;
        let arr = [];
        arr.push(patientRowData);
        let data = {
            params: [{
				recLocID: pharmacy, // 药房科室ID
                ward: arr, // 病区 
            }]
        }
        $http.post('urlS', this, {
            code: "02040027",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success("发药成功");
                }
            }
        })
    }


    render() {
        let {pharmacy, startDate, endDate, selectData, wardSelectData, basicHeight, wardSelectedRowKeys, wardSelectedRows, wardColumns, wardTableData, 
            wardID, patNo, mainInfo, user, patientColumns, patientTableData, dispCatData, patientRowId
        } = this.state;
        let mainInfoObj = mainInfo&&mainInfo.length > 0 ? mainInfo[0] : {};
        const wardRowSelection = {
            selectedRowKeys: wardSelectedRowKeys,
            selectedRows: wardSelectedRows,
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(selectedRowKeys, selectedRows)
                let rowId= "";
                if (selectedRowKeys.length !== 0) {
                    rowId=selectedRowKeys[selectedRowKeys.length-1];
                }
                this.setState({wardSelectedRowKeys: selectedRowKeys, wardSelectedRows: selectedRows, wardRowId: rowId})
            }
        };
        let colTop = {
            xs: {span: 12},
            sm: {span: 12},
            md: {span: 10},
            lg: {span: 10},
            xl: {span: 10},
            xxl: {span: 10}
        }
        let colBottom = {
            xs: {span: 12},
            sm: {span: 12},
            md: {span: 14},
            lg: {span: 14},
            xl: {span: 14},
            xxl: {span: 14}
        }

        // 药房
        let pharmacyOption = selectData.loc && selectData.loc.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 病区
        let wardAreaOption = wardSelectData&&wardSelectData.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 发药类别
        let dispTypeCheckbox = dispCatData && dispCatData.map((item, index) => {
			return (<Checkbox checked={item.checked} disabled={item.disabled} key={index} onChange={(e) => this.changeCheckbox(e, item)}>{item.dispCatDesc}</Checkbox>)
        })

        let medicalAdviceDom = (
            <div>
                <div style={{borderBottom: '1px solid #ccc'}}>
                    <h1 style={{textAlign: 'center', position: 'relative', fontSize: '26px', marginBottom: '30px'}}>
                        {mainInfoObj.hospName ? mainInfoObj.hospName : user.hospDesc}处方笺
                        <span style={{position: 'absolute', right: '10px', top: '10px', fontSize: '14px', fontWeight: 100, textAlign: 'right'}}>
                            <Row>{mainInfoObj.prescType}</Row>
                            <Row>处方号：{mainInfoObj.ordPrescNo}</Row>
                        </span>
                    </h1>
                    <div style={{padding: '0 24px 15px', fontSize: '16px'}}>
                        <Row>
                            <Col span={6}>
                                科室：{mainInfoObj.ordLocDesc}
                            </Col>
                            <Col span={6}>
                                卡号：{mainInfoObj.patCardNo}
                            </Col>
                            <Col span={6}>
                                日期：{mainInfoObj.ordDate}
                            </Col>
                            <Col span={6}>
                                费别：{mainInfoObj.admReasonDesc}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={6}>
                                患者：{mainInfoObj.patName}
                            </Col>
                            <Col span={6}>
                                性别：{mainInfoObj.patSexDesc}
                            </Col>
                            <Col span={6}>
                                年龄：{mainInfoObj.patAge}
                            </Col>
                            <Col span={6}>
                                体重：{mainInfoObj.patWeight}
                            </Col>
                        </Row>
                        <Row>
                            诊断：{mainInfoObj.admDiag}
                        </Row>
                    </div>
                </div>
                <div style={{borderBottom: '1px solid #ccc', padding: '24px'}} className="pr-style">
                    <h1 style={{fontSize: '26px'}}>Rp:</h1>
                    <div className="diagonal"></div>
                </div>
                <div style={{padding: '24px'}}>
                    <Row>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">医生签名：{mainInfoObj.ordDocDesc}</Col>
                                <Col {...colBottom}></Col>
                            </Row>
                        </Col>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">审核：{mainInfoObj.auditUserName}</Col>
                                <Col {...colBottom}></Col>
                            </Row>
                        </Col>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">金额：{mainInfoObj.prescAmt}</Col>
                                <Col {...colBottom}></Col>
                            </Row>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">调配：{mainInfoObj.prepUserName}</Col>
                                <Col {...colBottom}></Col>
                            </Row>
                        </Col>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">核对：{mainInfoObj.printUserName}</Col>
                                <Col {...colBottom}></Col>
                            </Row>
                        </Col>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">发药：{mainInfoObj.dispUserName}</Col>
                                <Col {...colBottom}></Col>
                            </Row>
                        </Col>
                    </Row>
                    <p style={{textAlign: 'center', marginTop: '50px', marginBottom: 0}}>本处方当前有效</p>
                </div>
            </div>
        )
        return (
            <div className="hospital-pharmacies">
                <Row id="chinese-herbs-make-medicine" style={{padding: '0 24px'}}>
                    <Col span={20}>
                        <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.getWardTableData}>查询</Button>
                        </div>
                    </Col>
                    <Col span={4} style={{textAlign: 'right'}}>
                        <Button
                            type="danger"
                            ghost
                            style={{margin: '8px 15px 0 0', width: '100px'}}
                            onClick={() => this.child.handleShowModal()}
                            disabled={patientRowId ? false : true}
                        >
                            拒绝发药
                        </Button>
                        <Button
                            type="primary"
                            style={{marginTop: '8px', width: '100px'}}
                            disabled={patientRowId ? false : true}
                            onClick={this.handleHPDispensing}
                        >
                            发药
                        </Button>
                    </Col>
                </Row>
                <div style={{height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%'}}></div>
                <Row>
                    <Col span={5}>
                        <div style={{paddingRight: '6px', position: 'relative'}}>
                            <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'}}>
                                        <Row>
                                            <Col span={13}>
                                                <Select
                                                    showSearch
                                                    defaultActiveFirstOption={false}
                                                    showArrow={false}
                                                    filterOption={false}
                                                    onSearch={this.handleWardSelectData}
                                                    notFoundContent={null}
                                                    placeholder="搜索病区"
                                                    allowClear
                                                    style={{width: '100%'}}
                                                    value={wardID}
                                                    onChange={this.handleWardOnChange}
                                                >
                                                    {wardAreaOption}
                                                </Select>
                                            </Col>
                                            <Col span={11} style={{textAlign: 'center'}}>
                                                <Button
                                                    style={{width: '116px'}}
                                                    onClick={this.handleQueryDispensingDetail}
                                                    // disabled={wardSelectedRows&&wardSelectedRows.length > 0 ? false : true}
                                                >
                                                    查询患者列表
                                                </Button>
                                            </Col>
                                        </Row>
                                    </div>
                                    <Table
                                        className="remove-td-default-bg inpatient-area"
                                        rowSelection={wardRowSelection}
                                        columns={wardColumns}
                                        dataSource={wardTableData}
                                        bordered
                                        pagination={false}
                                        scroll={{x: 200,y: store.getState().tableHeight.y + 160 - 80 - basicHeight}}
                                        onRow={this.handleWardOnRow}
                                        rowClassName={this.handleWardRowClassName}
                                    />
                                </div>
                            </Card>
                            <div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%'}}></div>
                        </div>
                    </Col>
                    <Col span={7}>
                        <div style={{paddingRight: '6px', position: 'relative'}}>
                            <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'}}>
                                        <div style={{marginBottom: '6px'}}>
                                            {dispTypeCheckbox}
                                        </div>
                                        <Input
                                            style={{width: '100%'}}
                                            value={patNo}
                                            onChange={this.handlePatNoOnChange}
                                            onPressEnter={this.getPatientTableData}
                                            placeholder="根据登记号、床位或姓名查询(Enter)"
                                        />
                                    </div>
                                    <Table
                                        className="inpatient-area"
                                        columns={patientColumns}
                                        dataSource={patientTableData}
                                        bordered
                                        pagination={false}
                                        scroll={{y: store.getState().tableHeight.y + 160 - 105 - basicHeight}}
                                        onRow={this.handlePatientOnRow}
                                        rowClassName={this.handlePatientRowClassName}
                                    />
                                </div>
                            </Card>
                            <div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%'}}></div>
                        </div>
                    </Col>
                    <Col span={12}>
                        <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'}}>
                                <p style={{textAlign: 'center', textDecoration: 'underline'}}>选择左侧处方来查看处方单</p>
                                <div style={{
                                    width: '100%',
                                    height: '100%',
                                    display: mainInfo&&mainInfo.length > 0 ? 'block' : 'none',
                                   }}>
                                    {medicalAdviceDom}
                                </div>
                            </div>
                        </Card>
                    </Col>
                </Row>
                <RejectDispensingCause onRef={this.onRef} />
            </div>
        )
    }
}