import React from 'react';
import { Table, Tabs, Button, message, Modal } from 'antd';
import { $http } from '../../../containers/config/https';
import PubSub from 'pubsub-js';
import './index.less';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';
import ShowRecordMedicineModal from './ShowRecordMedicineModal';
import './index.less'
import { element } from 'prop-types';
import { Util } from 'tools/index';

const { TabPane } = Tabs
let user;
export default class DrugReviewTabel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            newData: [],
            selectedRowKeys: [],
            selectedRowKeys_right: [],
            isDoubelClickTab: false,
            clickRowMedID: '',               //点击药品列表某行
            auditDetailFlag: false,          //点击过审核或撤销审核按钮
            ENObj: {},
            CNObj: {},
            detailColor: ""

        }
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    }
    componentDidMount() {
        this.props.onRef(this);
        this.getColumns();
        PubSub.subscribe('handleDrugReviewSearch', (data) => {
            // console.dir(data)
            this.setState({
                dataSource: data,
            })
        })
    }

    componentWillReceiveProps(nextProps, nextState) {
        if (nextProps.update) {
            if (!this.state.auditDetailFlag) {
                this.setState({ newData: [], isDoubelClickTab: nextProps.isDoubelClickTab }, () => {
                    this.getSelectedRowKeys()
                })
            } else {
                this.setState({
                    auditDetailFlag: false
                })
            }
        }

    }
    updateState = (state) => {
        this.setState(state);
    }
    onSelectChange(selectedRowKeys) {
        this.setState({ selectedRowKeys })
    }
    // 获取列表头数据  
    getColumns = () => {
        let { userInfo } = this.state;
        let data = {
            params: [{
                reactCode: ['NuserDrugOrderDraw'],
                compontName: 'NuserDrugOrderDraw',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                //console.log(res)
                if (+res.errorCode === 0) {
                    this.setState({
                        ENObj: res.result.language.EN,
                        CNObj: res.result.language.CN
                    })
                }
            }
        })
    };
    //审核药品列表
    getDrugreview = (flag, e) => {
        // 
        const { dataSource } = this.props;
        const { selectedRowKeys } = this.state;
        let medIDAry = []
        // console.log('dataSource',dataSource)
        dataSource.forEach((element) => {
            selectedRowKeys.forEach((item) => {
                if (element.index === item) {
                    medIDAry.push(element.medID)
                }
            })
        })
        // console.log('medIDAry',medIDAry)
        // return
        let data = {
            params: [{
                userID: user.userID,//用户主键
                medIDAry: medIDAry,//医嘱项数组
                process: this.props.process,
                auditFlag: flag,//是否点击审核按钮
            }]
        };
        $http.post('urlS', this, {
            code: "04060013",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    this.props.handleThis.handleQueryTop();
                    //this.setState({ isDoubelClickTab: false });
                    this.setState({
                        data: res.result,
                        selectedRowKeys: [],
                    })

                } else {
                    this.setState({
                        data: [],
                    })
                }
            }
        });

    }

    //医嘱项审核
    getauditor = (fag, e) => {
        // console.log(this.state.medItemId)
        let data = {
            params: [{
                userID: user.userID,//用户主键
                disIDAry: this.state.selectedRowKeys_right,//数组中值为发药主表主键
                auditFlag: fag,//是否点击审核按钮
            }]
        };
        $http.post('urlS', this, {
            code: "04060014",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    this.props.handleThis.handleQueryTop();
                } else {

                }
            }
        });

    }


    // 查询医嘱明细
    getdetail = (id) => {
        if (!id) {
            id = this.state.clickRowMedID
        }
        var flag = false
        var forSize = this.props.dataSource ? this.props.dataSource.length - 1 : 0
        for (var i = 0; i <= forSize; i++) {
            if (id == (this.props.dataSource ? this.props.dataSource[i].medID : "")) {
                flag = true
            }
        }
        if (flag) {
            let data = {
                params: [{
                    userID: user.userID,//用户主键
                    process: this.props.process,
                    medID: id,//医嘱项
                }]
            };
            $http.post('urlS', this, {
                code: "04060012",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setState({
                            newData: res.result,
                            selectedRowKeys_right: [],
                            auditDetailFlag: true,
                        })

                    } else {
                        this.setState({
                            newData: [],
                            selectedRowKeys_right: [],
                            auditDetailFlag: true,
                        })
                    }
                }
            });
        }
    }


    onRow = (record) => {
        var that = this
        return {
            //   onClick: event => {
            //       console.log("onClick")
            //   }, 
            onClick: () => {
                if (!that.state.isDoubelClickTab) {
                    that.setState({
                        isDoubelClickTab: true,
                        clickRowMedID: record.medID,
                        newData: [],
                        detailColor: record.color
                    }
                        , () => {
                            if (this.state.isDoubelClickTab) {
                                that.getdetail(record.medID);
                            }
                        });
                } else {
                    if (that.state.clickRowMedID == record.medID) {
                        that.setState({ isDoubelClickTab: false })
                    } else {
                        that.setState({
                            isDoubelClickTab: true,
                            clickRowMedID: record.medID,
                            newData: [],
                            detailColor: record.color
                        }
                            , () => {
                                if (this.state.isDoubelClickTab) {
                                    that.getdetail(record.medID);
                                }
                            });
                    }
                }
            },
            onChange: () => {
                this.setState({ isDoubelClickTab: false })
            }
        };
    }

    //   onDoubleClickShow = () => {
    //       return
    //   }


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

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

    setRowClassName = (record) => {
        if (record.color == "red") {
            return 'drugred'
        }
        if (record.color == "blue") {
            return 'drugblue'
        }
        if (record.color == "green") {
            return 'druggreen'
        }
        if (record.color == "yellow") {
            return 'drugyellow'
        }
    }

    RowClassName = () => {
        if (this.state.detailColor == "red") {
            return 'drugred'
        }
        if (this.state.detailColor == "blue") {
            return 'drugblue'
        }
        if (this.state.detailColor == "green") {
            return 'druggreen'
        }
        if (this.state.detailColor == "yellow") {
            return 'drugyellow'
        }
    }

    //取药执行记录
    handleRecordMedicineModal() {
        this.setState({
            isShowRecordMedicineModal: true
        })
    }

    hideModal(name) {
        this.setState({
            [name]: false
        })
    }

    countDown = () => {
        let secondsToGo = 3;
        const modal = Modal.success({
            title: '执行成功！',
            content: `将于 ${secondsToGo} 秒后关闭窗口.`,
        });
        const timer = setInterval(() => {
            secondsToGo -= 1;
            modal.update({
                content: `将于 ${secondsToGo} 秒后关闭窗口.`,
            });
        }, 1000);
        setTimeout(() => {
            clearInterval(timer);
            modal.destroy();
        }, secondsToGo * 1000);
    }

    //药品执行记录
    onSubmit(id) {
        var params = {
            params: [{
                ordID: id,
                userID: user.userID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050271",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    // message.success('执行成功！')
                    this.countDown();
                    // this.hideModal('isShowRecordMedicineModal')
                }
            }
        });
    }

    getSelectedRowKeys = () => {
        let dataSource = this.props && this.props.dataSource && this.props.dataSource.length > 0 ? this.props.dataSource : [];
        let arr = []
        dataSource.forEach((element, index) => {
            arr.push(index)
        });
        this.setState({
            selectedRowKeys: arr
        })

    }

    render() {
        var language = user.language
        var languageObj = {}
        if (language == "EN") {
            languageObj = this.state.ENObj
        } else {
            languageObj = this.state.CNObj
        }
        const { selectedRowKeys } = this.state;
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log('selectedRowKeys', selectedRowKeys);
                this.setState({ selectedRowKeys: selectedRowKeys })
            },
            onSelect: (record, selected, selectedRows) => {
                //console.log(record, selected, selectedRows);
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                //console.log(selected, selectedRows, changeRows);
            },
            selectedRowKeys: selectedRowKeys,
        };
        const { selectedRowKeys_right } = this.state;
        const rowSelection_right = {
            onChange: (selectedRowKeys_right, selectedRows) => {
                // console.log('逻辑',selectedRowKeys_right)
                // console.log('11111',selectedRows)
                this.setState({ selectedRowKeys_right: selectedRowKeys_right })
            },
            onSelect: (record, selected, selectedRows) => {
                // console.log(record, selected, selectedRows);
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                //console.log(selected, selectedRows, changeRows);
            },
            selectedRowKeys_right: this.state.selectedRowKeys_right,
        };
        return (
            <div style={{ height: "100%", padding: '0 24px' }} className="TableCrad">
                {this.state.isShowRecordMedicineModal ?
                    <ShowRecordMedicineModal isShow={this.state.isShowRecordMedicineModal}
                        patient={this.props.patient}
                        onSubmit={this.onSubmit.bind(this)}
                        onHide={this.hideModal.bind(this, 'isShowRecordMedicineModal')}>
                    </ShowRecordMedicineModal> : null}
                <div className="ReviewTable">{languageObj.NuserDrugOrderDrawDrugSearch != null ? languageObj.NuserDrugOrderDrawDrugSearch.descripts : ""}</div>
                <div style={{ width: '100%', height: '40px', background: 'rgb(245,244,244)' }}>
                    <div style={{ paddingLeft: '24px', margin: '8px', float: 'Right' }}>
                        <Button type="primary" size="small" style={{ verticalAlign: 'middle' }} onClick={this.getDrugreview.bind(this, "Y")}>{languageObj.NuserDrugOrderDrawDrugReview != null ? languageObj.NuserDrugOrderDrawDrugReview.descripts : ""}</Button>&nbsp;&nbsp;&nbsp;
                        <Button type="primary" size="small" style={{ verticalAlign: 'middle' }} onClick={this.getDrugreview.bind(this, "N")}>{languageObj.NuserDrugOrderDrawCancelAudit != null ? languageObj.NuserDrugOrderDrawCancelAudit.descripts : ""}</Button>
                        <Button type='primary' size='small' style={{ verticalAlign: 'middle', marginLeft: 10 }} onClick={this.handleRecordMedicineModal.bind(this)}
                            disabled={Util.isEmpty(this.props.patient)}>取药执行记录</Button>
                    </div>
                </div>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName="NuserDrugOrderDraw"
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getColumns}
                />
                <div style={{ height: 0, clear: 'both' }}></div>
                <Table
                    scroll={{ y: this.state.newData && this.state.newData.length > 0 ? 200 : 560 }}
                    dataSource={this.props.dataSource}
                    columns={this.props.orderColumnAry}
                    rowClassName={this.setRowClassName}
                    pagination={false}
                    rowKey={(row) => {
                        return row.index
                    }}

                    onRow={this.onRow}
                    bordered
                    rowSelection={rowSelection}
                    auditFlag={this.state.auditFlag}
                />
                {this.state.isDoubelClickTab ? (
                    <div style={{ paddingTop: '28px' }}>
                        <div className="Drug">{languageObj.NuserDrugOrderDrawDeatil != null ? languageObj.NuserDrugOrderDrawDeatil.descripts : ""}</div>
                        <div style={{ width: '100%', height: '40px', background: 'rgb(245,244,244)' }}>
                            <div style={{ paddingLeft: '24px', margin: '8px', float: 'Right' }}>
                                <Button type="primary" size="small" style={{ verticalAlign: 'middle' }} onClick={this.getauditor.bind(this, "Y")}>{languageObj.NuserDrugOrderDrawDetaiReview != null ? languageObj.NuserDrugOrderDrawDetaiReview.descripts : ""}</Button>&nbsp;&nbsp;&nbsp;
                            <Button type="primary" size="small" style={{ verticalAlign: 'middle' }} onClick={this.getauditor.bind(this, "N")}>{languageObj.NuserDrugOrderDrawCancelDetaiReview != null ? languageObj.NuserDrugOrderDrawCancelDetaiReview.descripts : ""}</Button>
                            </div>
                        </div>

                        <div style={{ height: 0, clear: 'both' }}></div>
                        <Table
                            dataSource={this.state.newData}
                            scroll={{ y: 337 }}
                            columns={this.props.drugColumnAry}
                            rowClassName={this.RowClassName}
                            pagination={false}
                            bordered
                            rowKey={(row) => {
                                return row.dspID
                            }}
                            onHeaderRow={column => {
                                return {
                                    onDoubleClick: () => {
                                        this.columnRef.onOpenModel();
                                    },
                                };
                            }}
                            rowSelection={rowSelection_right}
                        />
                    </div>

                ) : null
                }

            </div>
        )
    }
}