//药品的组件
import React from 'react';
import { Select, Row, Col, DatePicker, TimePicker, Icon, Tag, Switch, Checkbox, Button, message } from 'antd';
import { $http } from '../../../containers/config/https';
import moment from 'moment';
import PubSub from 'pubsub-js';
let timeout;
const Option = Select.Option;
let user;

export default class DrugReviewSearch extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],//发药的数据
            dispensing: '',//发药
            examined: '',//已审
            longOrd: '',//长期
            temporary: '',//临时
            arrears: '',//欠费
            toxinHemp: '',//毒麻
            spirit: '',//精神
            dischargeMed: '',//出院带药
            startDate: "", //开始日期
            startTime: "",//开始时间
            endDate: "",//结束日期
            endTime: "",//结束时间
            medData: [],//药品下拉框
            pharmacyAry: [],// 药房下拉数据
            pharmacyAryId: "",
            medItemId: "",
            medColumnAry: [], //药品数据列
            orderColumnAry: [], //医嘱明细列
            orderButtonAry: [],//医嘱明细按钮
            drugButtonAry: [],//药品审核按钮
            auditFlag: 'N',//是否点击审核按钮
            process: "",//进程号
            ENObj: {},
            CNObj: {},

        }
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    }

    componentDidMount() {
        this.getCondition();
        this.props.onRef(this);
        this.getDetailColumns();
    }

    // 获取列表头数据
    getDetailColumns = () => {
        let { userInfo } = this.state;
        let data = {
            params: [{
                reactCode: ['NuserDrugOrderDraw'],
                compontName: 'NuserDrugOrderDraw',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        ENObj: res.result.language.EN,
                        CNObj: res.result.language.CN
                    })
                }
            }
        })
    };
    
    //查询领药审核药品信息列表
    handleQuery = () => {
        let queryFlagObj = {};
        this.state.dataSource.map((item) => {
            queryFlagObj[item.code] = item.defaultValue;
        })
        let data = {
            params: [{
                userID: user.userID,
                hospID: user.hospID,
                queryFlagObj: queryFlagObj,
                patientAry: this.props.patient,
                locID: user.locID,
                ordRecLocID: "",
                CBMedID: this.state.CBMedID,
                startDate: this.state.startDate,
                startTime: this.state.startTime,
                stopDate: this.state.endDate,
                stopTime: this.state.endTime,
                pharmacyAryId: this.state.pharmacyAryId
            }],
        };
        $http.post('urlS', this, {
            code: "04060011",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    res.result.forEach((element, index) => {
                        element['index'] = index
                    });
                    // console.log('result',res.result)
                    this.setState({
                        data: res.result,
                    })
                    let { loadData } = this.props;
                    loadData && loadData({ "dataSource": res.result, process: res.process, update: true })
                    PubSub.publish('handleDrugReviewSearch', res.result)
                } else {
                    this.setState({
                        data: [],
                    })
                }
                this.props.clearDetail()
            }
        });
    }

    onCheckChange = (dataSource, key, e) => {
        //console.log(dataSource, key)
        dataSource[key].defaultValue = e.target.checked ? 'Y' : 'N';
        this.setState({ dataSource: dataSource })
    }

    // 查询条件查询
    getCondition = () => {
        let data = {
            params: [{
                userID: user.userID,
                groupID: user.groupID,
                hospID: user.hospID,
                locID: user.locID,
            }]
        };
        $http.post('urlS', this, {
            code: "04060010",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode == '0') {
                    this.setState({
                        dataSource: res.result,
                        pharmacyAry: res.pharmacyAry,
                        drugColumnAry: res.drugColumnAry,
                        orderColumnAry: res.orderColumnAry,
                        drugButtonAry: res.drugButtonAry,
                        orderButtonAry: res.orderButtonAry,
                        startDate: res.defaultValue.startDate,
                        startTime: res.defaultValue.startTime,
                        endDate: res.defaultValue.endDate,
                        endTime: res.defaultValue.endTime,
                    }, () => {
                        let { loadData } = this.props;
                        loadData && loadData({ "pharmacyAry": res.pharmacyAry, "drugColumnAry": res.drugColumnAry, "orderColumnAry": res.orderColumnAry, "drugButtonAry": res.drugButtonAry, "orderButtonAry": res.orderButtonAry })
                        this.handleQuery();
                    })
                } else {
                    this.setState({
                        dataSource: [],
                    })
                }
            }
        });
    }

    onChange = (id) => {
        this.setState({
            pharmacyAryId: id,
        })
    }

    onSelctChange = (id) => {
        this.setState({
            CBMedID: id,
        })
    }

    GetMedItem = (value, callback) => {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        function getMedItemData() {
            if (value === "") {
                this.setState({ medData: [] })
                return
            }
            let data = {
                params: [{
                    findCode: value,
                    detailFlag: "",
                }]
            }
            $http.post('urlS', this, {
                code: "01010002",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        callback(res.result.Data)

                    }
                }
            })
        }
        timeout = setTimeout(getMedItemData, 1000);
    }

    handleSerach = (value) => {
        let reg = /\s/g;
        if (reg.test(value)) {
            message.error('不能输入空字符')
            return
        }
        this.GetMedItem(value, data => this.setState({ medData: data }))

    }

    updateState = (state) => {
        this.setState(state);
    }

    handleDateTimeChange = (flag, time, datetimeString) => {
        this.setState({ [flag]: datetimeString });
    }
    
    render() {
        let date = new Date();
        let language = user.language
        let languageObj = {}
        if (language == "EN") {
            languageObj = this.state.ENObj
        } else {
            languageObj = this.state.CNObj
        }
        return (
            <div style={{ width: "100%", height: "100%", overflowY: 'hidden' }}>
                <Row style={{ boxSizing: 'border-box', padding: '0 24px', height: '38px', lineHeight: '38px', maxHeight: '38px' }} >
                    <Col xxl={{ span: 8 }} xl={{ span: 8 }} lg={{ span: 14 }} md={{ span: 24 }} className="xxl-8">
                        {languageObj.NuserDrugOrderDrawSDate != null ? languageObj.NuserDrugOrderDrawSDate.descripts : ""}
                        <DatePicker
                            onChange={this.handleDateTimeChange.bind(this, "startDate")}
                            value={(this.state.startDate === "") ? null : moment(this.state.startDate, 'YYYY-MM-DD')}
                            style={{ margin: '0 10px', width: '45%' }}

                        >
                        </DatePicker>

                        <TimePicker
                            style={{ width: '30%' }}
                            onChange={this.handleDateTimeChange.bind(this, "startTime")}
                            value={(this.state.startTime === "") ? null : moment(this.state.startTime, 'HH:mm:ss')}
                        >
                        </TimePicker>
                    </Col>

                    <Col xxl={{ span: 7 }} xl={{ span: 7 }} lg={{ span: 14 }} md={{ span: 24 }} className="xxl-7">
                        {languageObj.NuserDrugOrderDrawEnd != null ? languageObj.NuserDrugOrderDrawEnd.descripts : ""}
                        <DatePicker
                            onChange={this.handleDateTimeChange.bind(this, "endDate")}
                            value={(this.state.endDate === "") ? null : moment(this.state.endDate, 'YYYY-MM-DD')}
                            style={{ margin: '0 10px', width: '45%' }}>
                        </DatePicker>
                        <TimePicker
                            style={{ width: '30%' }}
                            onChange={this.handleDateTimeChange.bind(this, "endTime")}
                            value={(this.state.endTime === "") ? null : moment(this.state.endTime, 'HH:mm:ss')}
                        >
                        </TimePicker>
                    </Col>

                    <Col xxl={{ span: 4 }} xl={{ span: 4 }} lg={{ span: 14 }} md={{ span: 24 }}>
                        {languageObj.NuserDrugOrderDrawpharmacy != null ? languageObj.NuserDrugOrderDrawpharmacy.descripts : ""}
                        <Select
                            allowClear
                            showSearch
                            style={{ width: '75%', margin: ' 3px 0' }}
                            placeholder="请输入药房"
                            optionFilterProp="children"
                            onChange={this.onChange}
                            onSearch={this.onSearch}
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        >
                            {
                                this.state.pharmacyAry.map(
                                    (item) => {
                                        return <Option key={item.id} value={item.id} title={item.descripts + "^" + item.descriptsSPCode.toLowerCase()}>{item.descripts}</Option>
                                    }
                                )

                            }
                        </Select>
                    </Col>
                    <Col xxl={{ span: 4 }} xl={{ span: 4 }} lg={{ span: 14 }} md={{ span: 24 }}>
                        {languageObj.NuserDrugOrderDrawDrug != null ? languageObj.NuserDrugOrderDrawDrug.descripts : ""}
                        <Select
                            allowClear
                            showSearch
                            optionFilterProp="title"
                            style={{ width: '75%', margin: ' 3px 0' }}
                            placeholder="请输入药品"
                            // optionFilterProp="children"
                            onChange={this.onSelctChange}
                            onSearch={this.handleSerach}
                            filterOption={false}
                        >
                            {
                                this.state.medData && this.state.medData.map(
                                    (item) => {
                                        return <Option key={item.id} value={item.id} title={item.descripts + "^" + item.descriptsSPCode.toLowerCase()}>{item.descripts}</Option>
                                    }
                                )

                            }
                        </Select>
                    </Col>
                </Row>
                <Row style={{ padding: "0 24px", height: '38px', lineHeight: '38px', maxHeight: '38px', borderBottom: '1px solid #cccccc' }}>
                    <Col span={17} style={{ textAlign: 'left' }}>
                        {
                            this.state.dataSource && this.state.dataSource.map((item, key) => {
                                if (item.displayFlag !== "Y") return '';
                                return (
                                    <Col span={3} key={key}>
                                        <Checkbox
                                            onChange={this.onCheckChange.bind(this, this.state.dataSource, key)}
                                            checked={item.defaultValue === 'Y' ? true : false}
                                        // defaultChecked={item.defaultValue === "Y" ? true : false}
                                        //  style={{ margin: '0 15px' }}
                                        >{item.description}</Checkbox>
                                    </Col>
                                )
                            })
                        }
                    </Col>

                    <Col span={2} offset={5}>
                        <Button
                            onClick={this.handleQuery}
                            type="primary">
                            {languageObj.NuserDrugOrderDrawSearch != null ? languageObj.NuserDrugOrderDrawSearch.descripts : ""}
                        </Button>
                    </Col>

                </Row>
            </div >
        )
    }
}
