import React, { Component } from 'react';
import { Table, Collapse, Input, Button, Alert, Icon, Layout, message, Row, Col, DatePicker, TimePicker, Divider, Popconfirm, InputNumber, Checkbox } from 'antd';
import moment from 'moment';
import { $http } from '../../containers/config/https';

import ConditionDetailPanel from './ConditionDetailPanel';
import SelectTable from './SelectTable';
import './style/nurseConfig.less';//引入样式

const {
    Header, Footer, Sider, Content,
} = Layout;
let userData;
let columnKeys = [], buttonKeys = [], priorityKeys = [], ordCatKeys = [], specKeys = [], recLocKeys = [], ordLocKeys = [], stageKeys = [], disposeKeys = [], ordStatusKeys = [], usageKeys = []
class ConfigCondition extends Component {
    constructor(props) {
        super(props);
        userData= sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
        this.state = {
            multipleFlag: false,
            startIndex: '',
            title: [
                {
                    title: '描述',
                    dataIndex: 'descripts',
                    width: '150px',
                    key: 'descripts',
                }
            ],
            // column: [],
            sheet: [],
            // button: [],
            ordStatus: [],
            priority: [],
            ordCat: [],
            usage: [],
            spec: [],
            recLoc: [],
            ordLoc: [],
            stage: [],
            dispose: [],
            priorityKeys: [],
            ordCatKeys: [],
            specKeys: [],
            recLocKeys: [],
            ordLocKeys: [],
            stageKeys: [],
            disposeKeys: [],
            ordStatusKeys: [],
            usageKeys: [],
            columnDisplay: [],
            buttonDisplay: [],
            selectIndex: '',
            showHeader: false,
            rightloading: true,
            selectSheet: '',
            setClassName: 'clickRowStylee',
            hospID: '1',
            startDate: '0',
            startTime: '00:00',
            endDate: '0',
            endTime: '23:59:59',
            tabsActiveKey: '',
            top: 0,
            left: 0,
            skintestFlag: ''
        }        
    }
    componentDidMount() {
        this.props.onRef(this);
    }
    componentWillUmount() {
    }
    shouldComponentUpdate(nextProps, nextState) {
        if (!nextProps.update) {
            return false
        }
        return true;
    }

    getData = (record) => {
        let sheetCode = "";
        if (record != "") {
            sheetCode = record.code
        }
        this.setState(
            {
                rightloading: true
            }, () => {
                let data = {
                    "params": [{
                        sheetCode: sheetCode,
                        hospID: userData.hospID,
                    }]
                };

                $http.post('urlDeault', this, {
                    code: "04010004",
                    data: data,
                    success: function (res) {
                        let sheet = [], priority = [], ordCat = [], spec = [], recLoc = [], ordLoc = [], stage = [], ordStatus = [], usage = [], dispose = [], buttonDisplay = [], columnDisplay = []
                        buttonKeys = [], columnKeys = []// let , priorityKeys = [], ordCatKeys = [], specKeys = [], recLocKeys = [], stageKeys = [], ordStatusKeys = [], usageKeys = [], disposeKeys = []button = [], column = [], 
                        let startDate = res.startDate, startTime = res.startTime, endDate = res.endDate, endTime = res.endTime, skintestFlag = res.skintestFlag                        
                        sheet = res.result.sheet;
                        // button = res.result.button;
                        // column = res.result.column;
                        priority = res.result.priority;
                        ordCat = res.result.ordCat;
                        spec = res.result.spec;
                        recLoc = res.result.recLoc;
                        ordLoc = res.result.ordLoc;
                        stage = res.result.stage;
                        ordStatus = res.result.ordStatus;
                        usage = res.result.usage;
                        dispose = res.result.dispose;
                        disposeKeys = res.result.disposeKeys;
                        priorityKeys = res.result.priorityKeys;
                        ordCatKeys = res.result.ordCatKeys;
                        specKeys = res.result.specKeys;
                        recLocKeys = res.result.recLocKeys;
                        ordLocKeys = res.result.ordLocKeys;
                        stageKeys = res.result.stageKeys;
                        ordStatusKeys = res.result.ordStatusKeys;
                        usageKeys = res.result.usageKeys;
                        buttonDisplay = res.result.buttonDisplay
                        columnDisplay = res.result.columnDisplay;

                        if (sheetCode != "") {
                            this.setState(
                                {
                                    selectSheet: record,
                                    sheet: sheet,
                                    priorityKeys: priorityKeys,
                                    ordCatKeys: ordCatKeys,
                                    specKeys: specKeys,
                                    recLocKeys: recLocKeys,
                                    ordLocKeys: ordLocKeys,
                                    stageKeys: stageKeys,
                                    ordStatusKeys: ordStatusKeys,
                                    usageKeys: usageKeys,
                                    disposeKeys: disposeKeys,
                                    buttonDisplay: buttonDisplay,
                                    columnDisplay: columnDisplay,
                                    startDate: startDate,
                                    startTime: startTime,
                                    endDate: endDate,
                                    endTime: endTime,
                                    tabsActiveKey: "1",
                                    rightloading: false,
                                    skintestFlag: skintestFlag
                                }
                            );
                        } else {
                            this.setState(
                                {
                                    selectSheet: record,
                                    sheet: sheet,
                                    priority: priority,
                                    ordCat: ordCat,
                                    spec: spec,
                                    recLoc: recLoc,
                                    ordLoc: ordLoc,
                                    stage: stage,
                                    ordStatus: ordStatus,
                                    usage: usage,
                                    dispose: dispose,
                                    startDate: startDate,
                                    startTime: startTime,
                                    endDate: endDate,
                                    endTime: endTime,
                                    tabsActiveKey: "1",
                                    rightloading: false,
                                    skintestFlag: skintestFlag
                                }
                            );
                        }

                        if (record === "") {
                            this.props.updateState(false, sheet);
                        }
                    },
                    error: function (error) {
                        message.error('失败：' + error);
                    }
                });
            });
    }
    getdataRowId = (keys) => {

        let idStr = "";
        for (var i = 0; i < keys.length; i++) {

            if (idStr === "") {

                idStr = keys[i];
            }
            else {
                idStr = idStr + "^" + keys[i];
            }
        }
        return idStr;
    }
    /** 去重*/
    unique(arr) {
        var x = new Set(arr);
        return [...x];
    }
    saveData = (record) => {
        let rightloading = true, leftloading = false;
        if (record.editable) {
            record.editable = false;
            leftloading = true;
        }
        let tempArr1 = this.state.columnDisplay
        let columnIds = [], buttonIds = []
        for (let i = 0; i < tempArr1.length; i++) {
            columnIds.push(tempArr1[i].id);
        }
        let tempArr2 = this.state.buttonDisplay
        for (let j = 0; j < tempArr2.length; j++) {
            buttonIds.push(tempArr2[j].id);
        }
        this.setState(
            {
                leftloading: leftloading,
                rightloading: rightloading
            });
        let data = {
            "params": [{
                sheetCode: record.code,
                hospID: userData.hospID,
                sheetDesc: record.descripts,
                startDate: this.state.startDate,
                startTime: this.state.startTime,
                endDate: this.state.endDate,
                endTime: this.state.endTime,
                userID: userData.userID,
                button: this.getdataRowId(buttonIds),
                column: this.getdataRowId(columnIds),
                priority: this.getdataRowId(priorityKeys),
                ordCat: this.getdataRowId(ordCatKeys),
                spec: this.getdataRowId(specKeys),
                recLoc: this.getdataRowId(recLocKeys),
                ordLoc: this.getdataRowId(ordLocKeys),
                stage: this.getdataRowId(stageKeys),
                ordStatus: this.getdataRowId(ordStatusKeys),
                usage: this.getdataRowId(usageKeys),
                dispose: this.getdataRowId(disposeKeys),
                skintestFlag: this.state.skintestFlag
            }]
        };

        $http.post('urlDeault', this, {
            code: "04010005",
            data: data,
            success: function (res) {
                this.setState(
                    {
                        leftloading: false,
                        rightloading: false,
                    }
                );
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                }
            },
            error: function (error) {
                this.setState(
                    {
                        leftloading: false,
                        rightloading: false,
                    }
                );
                message.error('失败：' + error);
            }
        });
        columnKeys = [], buttonKeys = []
    }

    handleDateChange = (flag, value) => {
        this.setState({ [flag]: value })
    }
    handleTimeChange = (flag, time, timeString) => {
        this.setState({ [flag]: timeString });
    }
    handleCleanSelect = () => {
        this.setState(
            {
                // buttonKeys: [],
                // columnKeys: [],
                priorityKeys: [],
                ordCatKeys: [],
                specKeys: [],
                recLocKeys: [],
                ordLocKeys: [],
                stageKeys: [],
                ordStatusKeys: [],
                usageKeys: [],
                disposeKeys: [],
                columnDisplay: [],
                buttonDisplay: []
            })
    }
    onTabsChange = (tabsActiveKey) => {
        this.setState({ tabsActiveKey: tabsActiveKey });

    }

    handleEnterKey = (e) => {
        //shift 按键按下时触发
        if (e.keyCode === 16) {
            this.setState({ multipleFlag: !this.state.multipleFlag });
        }
    }
    //临时存储每个table里的数据
    storageData = (tableName, keys) => {
        if (tableName === "ordStatusKeys") { ordStatusKeys = keys }
        if (tableName === "priorityKeys") { priorityKeys = keys }
        if (tableName === "disposeKeys") { disposeKeys = keys }
        if (tableName === "ordCatKeys") { ordCatKeys = keys }
        if (tableName === "specKeys") { specKeys = keys }
        if (tableName === "recLocKeys") { recLocKeys = keys }
        if (tableName === "ordLocKeys") { ordLocKeys = keys }
        if (tableName === "stageKeys") { stageKeys = keys }
        if (tableName === "usageKeys") { usageKeys = keys }
        if (tableName === "buttonKeys") { buttonKeys = keys }
        if (tableName === "columnKeys") { columnKeys = keys }
    }
    // 当显示列焦点后
    onBlurColumn = (e) => {
    }
    getColumnData = (flag, e) => {
        let id = "col-Panel";
        if (flag === "B") {
            id = "btn-Panel";
        }

        let top = document.getElementById(id).getBoundingClientRect().top + document.getElementById(id).getBoundingClientRect().height + 2 + 'px';
        let left = document.getElementById(id).getBoundingClientRect().left + 3 + 'px';
        this.setState({
            top: top,
            left: left
        });
        this.child.showModal(flag);
    }
    onRef = (ref) => {
        this.child = ref;
    }
    onRefPanel = (ref) => {
        this.childPanel = ref;
    }
    // 选中获取id
    handleOk = (arr, flag) => {
        let tempArr = (flag === 'C') ? this.state.columnDisplay : this.state.buttonDisplay;
        let variable = ''
        if (flag === 'C') { variable = 'columnDisplay' }
        else { variable = 'buttonDisplay' }
        let idArr = [];
        for (let i = 0; i < tempArr.length; i++) {
            idArr.push(tempArr[i].id);
        }
        for (let j = 0; j < arr.length; j++) {
            if (!idArr.includes(arr[j].id)) {
                tempArr.push(arr[j]);
                idArr.push(arr[j].id);
            }
        }
        this.setState({
            [variable]: tempArr
        })
    }
    // 移除选中项
    remove = (tableName) => {
        let tempArr = (tableName === 'columnKeys') ? this.state.columnDisplay : this.state.buttonDisplay;
        let tempKeys = (tableName === 'columnKeys') ? columnKeys : buttonKeys;
        for (let i = 0; i < tempKeys.length; i++) {
            tempArr.splice(tempArr.findIndex(item => item.id === tempKeys[i]), 1)
        }
        if (tableName === 'columnKeys') {
            this.setState({
                columnDisplay: tempArr
            })
            columnKeys = []
        }
        if (tableName === 'buttonKeys') {
            this.setState({
                buttonDisplay: tempArr
            })
            buttonKeys = []
        }
        this.childPanel.clearSelectedData()
    }
    // 上移
    handleUp = (tableName) => {
        let keys = (tableName === 'columnKeys') ? columnKeys : buttonKeys;
        let data = (tableName === 'columnKeys') ? this.state.columnDisplay : this.state.buttonDisplay;
        let variable = (tableName === 'columnKeys') ? 'columnDisplay' : 'buttonDisplay';
        let index = [];
        for (let i = 0; i < data.length; i++) {
            if (("^" + keys.join("^") + "^").includes("^" + data[i].id + "^")) {
                index.push(i);
            }
        }
        index = this.unique(index);
        let newKeys = []
        keys = index.sort(function (m, n) {
            if (m < n) return -1
            else if (m > n) return 1
            else return 0
        });
        for (let i = 0; i < keys.length; i++) {
            if (keys[i] === 0) {
                newKeys.push(keys[i])
                continue
            }
            let curRowData = data[keys[i]]
            let curRowKey = curRowData.key
            let upRowData = data[keys[i] - 1]
            let upRowKey = upRowData.key
            upRowData.key = curRowKey
            curRowData.key = upRowKey
            data[keys[i]] = upRowData
            data[keys[i] - 1] = curRowData
            newKeys.push(keys[i] - 1)
        }
        this.setState({
            [variable]: data
        })
    }
    // 下移
    handleDown = (tableName) => {
        let keys = (tableName === 'columnKeys') ? columnKeys : buttonKeys;
        let data = (tableName === 'columnKeys') ? this.state.columnDisplay : this.state.buttonDisplay;
        let variable = (tableName === 'columnKeys') ? 'columnDisplay' : 'buttonDisplay';
        let index = [];
        for (let i = 0; i < data.length; i++) {
            if (("^" + keys.join("^") + "^").includes("^" + data[i].id + "^")) {
                index.push(i);
            }
        }
        index = this.unique(index);
        let newKeys = [];
        keys = index.sort(function (m, n) {
            if (m < n) return -1
            else if (m > n) return 1
            else return 0
        });
        for (let i = keys.length - 1; i >= 0; i--) {
            if (keys[i] === data.length - 1) {
                newKeys.push(keys[i])
                continue
            }
            let curRowData = data[keys[i]]
            let upRowData = data[keys[i] + 1]
            let curRowKey = curRowData.key
            let upRowKey = upRowData.key
            upRowData.key = curRowKey
            curRowData.key = upRowKey
            data[keys[i]] = upRowData
            data[keys[i] + 1] = curRowData
            newKeys.push(keys[i] + 1)
        }
        this.setState({
            [variable]: data
        })
    }
    render() {
        let marginTop = 16;
        if (this.state.sheet.length === 0) marginTop = 200;
        let param = {
            width: 240,
            top: this.state.top,
            left: this.state.left,
            height: 400,
            columns: this.state.title,
            ModalClassName: "selectTable",
            // data:this.state.column,
            isFooter: true
        }

        return (
            <Col span={24} className="nurseConfig">
                <Row style={{ height: '50%' }}>
                    <Col className="tablBorder" span={5} >
                        <Button type="primary" size='small' id='btn-Panel' style={{ margin: '2px' }} onClick={this.getColumnData.bind(this, "B")}>添加按钮</Button>
                        <Button type="primary" size='small' onClick={this.handleUp.bind(this, 'buttonKeys')}>上移</Button>
                        <Button type="primary" size='small' style={{ margin: '2px' }} onClick={this.handleDown.bind(this, 'buttonKeys')} >下移</Button>
                        <Button type="primary" size='small' onClick={this.remove.bind(this, 'buttonKeys')}>移除</Button>
                        <Row style={{ height: "70%" }}>
                            <ConditionDetailPanel
                                title={this.state.title}
                                dataArr={this.state.buttonDisplay}
                                selectedData={buttonKeys}
                                tableName='buttonKeys'
                                storageData={this.storageData}
                                onRef={this.onRefPanel}
                                id={(row) => {
                                    return row.id;
                                }}
                                scroll={{ y: 290 }}
                            />
                        </Row>
                        <Row >
                            <Col span={12} style={{ paddingLeft: 15 }}>
                                <Checkbox onChange={() =>
                                    this.setState({
                                        skintestFlag: this.state.skintestFlag === 'Y' ? 'N' : 'Y'
                                    })
                                }
                                    checked={this.state.skintestFlag === 'Y' ? true : false}
                                >显示皮试医嘱</Checkbox>
                            </Col>
                        </Row>
                        <Row >
                            <Col span={10} style={{ paddingLeft: 10 }}>
                                <InputNumber
                                    style={{ width: "60%" }}
                                    key="startDate"
                                    defaultValue={0}
                                    min={-3}
                                    max={3}
                                    value={+this.state.startDate}
                                    onChange={this.handleDateChange.bind(this, "startDate")}
                                />
                            </Col>
                            <Col span={10}>
                                <TimePicker
                                    key="startTime"
                                    defaultValue={moment(this.state.startTime, 'HH:mm:ss')}
                                    onChange={this.handleTimeChange.bind(this, "startTime")} />
                            </Col>
                        </Row>
                        <Row>
                            <Col span={10} style={{ paddingTop: 5, paddingBottom: 5, paddingLeft: 10 }}>
                                <InputNumber
                                    style={{ width: "60%" }}
                                    key="endDate"
                                    defaultValue={0}
                                    min={-3}
                                    max={3}
                                    value={+this.state.endDate}
                                    onChange={this.handleDateChange.bind(this, "endDate")} />
                            </Col>
                            <Col span={10}>
                                <TimePicker
                                    key="endTime"
                                    style={{ paddingTop: 5, paddingBottom: 5 }}
                                    defaultValue={moment(this.state.endTime, 'HH:mm:ss')}
                                    onChange={this.handleTimeChange.bind(this, "endTime")} />
                            </Col>
                        </Row>
                    </Col>
                    <Col span={5} className="tablBorder">
                        <Button type="primary" size='small' id='col-Panel' style={{ margin: '2px' }} onClick={this.getColumnData.bind(this, "C")}>添加列</Button>
                        <Button type="primary" size='small' onClick={this.handleUp.bind(this, 'columnKeys')}>上移</Button>
                        <Button type="primary" size='small' style={{ margin: '2px' }} onClick={this.handleDown.bind(this, 'columnKeys')} >下移</Button>
                        <Button type="primary" size='small' onClick={this.remove.bind(this, 'columnKeys')}>移除</Button>
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.columnDisplay}
                            selectedData={columnKeys}
                            tableName='columnKeys'
                            storageData={this.storageData}
                            onRef={this.onRefPanel}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 380 }}
                        />
                    </Col>
                    <Col span={5} className="tablBorder">
                        <Alert
                            message="医嘱状态"
                            type="info"
                        />
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.ordStatus}
                            tableName='ordStatusKeys'
                            selectedData={this.state.ordStatusKeys}
                            storageData={this.storageData}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 375 }}
                        />
                    </Col>
                    <Col span={5} className="tablBorder">
                        <Alert
                            message="优先级"
                            type="info"
                        />
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.priority}
                            tableName='priorityKeys'
                            selectedData={this.state.priorityKeys}
                            storageData={this.storageData}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 375 }}
                        />
                    </Col>
                    <Col span={4} className="tablBorder">
                        <Alert
                            message="接收科室"
                            type="info"
                        />
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.recLoc}
                            tableName='recLocKeys'
                            selectedData={this.state.recLocKeys}
                            storageData={this.storageData}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 375 }}
                        />
                    </Col>


                </Row>
                <Row style={{ height: '50%' }}>
                    <Col span={5} className="tablBorder">
                        <Alert
                            message="医嘱阶段"
                            type="info"
                        />
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.stage}
                            tableName='stageKeys'
                            selectedData={this.state.stageKeys}
                            storageData={this.storageData}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 375 }}
                        />
                    </Col>
                    <Col span={5} className="tablBorder">
                        <Alert
                            message="医嘱子类"
                            type="info"
                        />
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.ordCat}
                            tableName='ordCatKeys'
                            selectedData={this.state.ordCatKeys}
                            storageData={this.storageData}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 375 }}
                        />
                    </Col>

                    <Col span={5} className="tablBorder">
                        <Alert
                            message="用法"
                            type="info"
                        />
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.usage}
                            tableName='usageKeys'
                            selectedData={this.state.usageKeys}
                            storageData={this.storageData}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 375 }}
                        />
                    </Col>
                    <Col span={5} className="tablBorder">
                        <Alert
                            message="标本"
                            type="info"
                        />
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.spec}
                            tableName='specKeys'
                            selectedData={this.state.specKeys}
                            storageData={this.storageData}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 375 }}
                        />
                    </Col>
                    <Col span={4} className="tablBorder">
                        <Alert
                            message="开单科室"
                            type="info"
                        />
                        <ConditionDetailPanel
                            title={this.state.title}
                            dataArr={this.state.ordLoc}
                            tableName='ordLocKeys'
                            selectedData={this.state.ordLocKeys}
                            storageData={this.storageData}
                            id={(row) => {
                                return row.id;
                            }}
                            scroll={{ y: 375 }}
                        />
                    </Col>
                </Row>
                <SelectTable
                    param={param}
                    onRef={this.onRef}
                    id={(row) => {
                        return row.id;
                    }}
                    handleOk={this.handleOk}
                />
            </Col>
        );
    }

}
export default ConfigCondition;  