import React, { Component } from 'react';
import { Table, Collapse, Input, Button, Alert, Icon, Layout, message, Row, Col, DatePicker, TimePicker, Divider, Popconfirm, InputNumber } from 'antd';
import moment from 'moment';
import { $http } from '../../containers/config/https';
import ConfigCondition from './ConfigCondition'
import './style/nurseConfig.less';//引入样式
const {
    Header, Footer, Sider, Content,
} = Layout;
let userData;
class NurseExcuteConfig extends Component {
    constructor(props) {
        super(props);
        this.state = {
            multipleFlag: false,
            startIndex: '',
            title: [
                {
                    title: '描述',
                    dataIndex: 'descripts',
                    width: '150px',
                    key: 'descripts',
                }
            ],
            sheetColumns: [{
                title: '代码',
                dataIndex: 'code',
                key: 'code',
                width: '80px',
                render: (text, record, index) => {
                    if ((record.editable) && (!record.id)) {
                        return (
                            <Input
                                style={{ width: '100px' }}
                                value={text}
                                autoFocus
                                onChange={e => this.handleFieldChange(e, 'code', record, index)}
                                placeholder="代码"
                            />
                        )
                    }
                    return text;
                }
            }, {
                title: '名称',
                dataIndex: 'descripts',
                key: 'descripts',
                width: '120px',
                render: (text, record, index) => {
                    if (record.editable) {
                        return (
                            <Input
                                style={{ width: '135px' }}
                                value={text}
                                placeholder="名称"
                                onChange={e => this.handleFieldChange(e, 'descripts', record, index)}
                            />
                        )
                    }
                    return text;
                }
            }, {
                title: '操作',
                key: 'action',
                width: '',
                render: (text, record, index) => {
                    if (record.editable) {
                        return (
                            <span>
                                <a onClick={e => this.handleSaveRow(e, record)}>保存</a>
                                <Divider type="vertical" />

                                <a onClick={e => this.handleCancelRow(e, record, index)}>取消</a>
                            </span>
                        );
                    }
                    return (
                        <span>
                            <Popconfirm title="确定删除该单据？" onConfirm={(e) => this.handleDelRow(e,record.id)}>
                                <a>删除</a>
                            </Popconfirm>

                            <Divider type="vertical" />

                            <a onClick={e => this.handleEditRow(e, record, index)}>编辑</a>
                        </span>
                    );
                }

            }
            ],
            column: [],
            sheet: [],
            selectIndex: '',
            showHeader: false,
            leftloading: true,
            selectSheet: '',
            setClassName: 'clickRowStylee',
            hospID: '1',
            updateChild: true,

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


    /** 去重*/
    unique5(arr) {
        var x = new Set(arr);
        return [...x];
    }

    delData = (id) => {
        this.setState(
            {
                leftloading: true,
                rightloading: true
            });
        let data = {
            "params": [{
                userID: userData.userID,
                id: id,
            }]
        }
        $http.post('urlDeault', this, {
            code: "04010003",
            data: data,
            success: function (res) {
                this.setState(
                    {
                        leftloading: false,
                        rightloading: false,
                    }
                );
                if (+res.errorCode === 0) {
                    message.success('删除成功！');
                    this.getData("");
                }
            },
            error: function (error) {
                this.setState(
                    {
                        leftloading: false,
                        rightloading: false,
                    }
                );
                message.error('删除失败：' + error);
            }
        });
    }

    componentDidMount() {
        //绑定键盘事件
        this.ConfigCondition.getData("");
    }
    newMember = () => {

        const newData = this.state.sheet
        if (newData.length > 1) {
            if (newData[newData.length - 1].editable) {
                message.error('请先保存或取消当前编辑的数据！');
                return;
            }
        }
        newData.push({
            code: '',
            descripts: '',
            editable: true,
        });
        this.handleCleanSelect();
        this.setState({ sheet: newData });
    };
    handleSaveRow = (e, record) => {
        record.editable = false;
        if ((record.code === "") || (record.descripts === "")) {
            message.error('单据代码和描述不能为空');
            return;
        }
        this.saveRow(record);
    }
    saveRow = (record) => {
        let data = {
            "params": [{
                sheetCode: record.code,
                hospID: userData.hospID,
                sheetDesc: record.descripts,
                userID: userData.userID,
            }]
        };
        $http.post('urlDeault', this, {
            code: "04010005",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                    this.getData();
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        });
    }
    getData = () => {
        this.setState(
            {
                leftloading: true,
                updateChild: false,
            }, () => {
                let data = {
                    "params": [{
                        sheetCode: "",
                        hospID: userData.hospID,
                    }]
                };
                $http.post('urlDeault', this, {
                    code: "04010004",
                    data: data,
                    success: function (res) {
                        this.setState(
                            {
                                sheet: res.result.sheet,
                                leftloading: false,
                                updateChild: false,
                            }
                        );
                    },
                    error: function (error) {
                        message.error('失败：' + error);
                    }
                });

            });
    }
    handleSave = () => {
        let selectSheet = this.state.selectSheet;
        if (selectSheet === "") {
            message.error('编辑状态请点击行内保存或双击要保存的单据!');
            return;
        }
        this.ConfigCondition.saveData(selectSheet);
    }
    handleDelRow = (e,id) => {
        e.stopPropagation();
        this.delData(id);
    }

    handleCancelRow = (e, record, index) => {
        let data = this.state.sheet;
        if (record.id) {
            data[index].editable = false;
        }
        else {
            data.splice(index, 1);
        }
        this.setState({ sheet: data })

    }
    handleEditRow = (e, record, index) => {
        let data = this.state.sheet;
        data[index].editable = true
        this.setState({ sheet: data })
    }

    handleFieldChange(e, field, record, index) {
        record[field] = e.target.value;
        var sheet = this.state.sheet
        sheet[index] = record
        this.setState({ sheet: sheet, updateChild: false })
    }
    handleCleanSelect = () => {
        this.ConfigCondition.setState(
            {
                buttonKeys: [],
                columnKeys: [],
                priorityKeys: [],
                ordCatKeys: [],
                specKeys: [],
                recLocKeys: [],
                stageKeys: [],
                ordStatusKeys: [],
                usageKeys: [],
                disposeKeys: [],
                columnDisplay: [],
                buttonDisplay: []
            })
    }
    //更新State
    updateState = (leftloading, sheet) => {
        this.setState({ leftloading: leftloading, sheet: sheet });
    }
    //单据行点击事件
    tableRow = (tableName, record, index) => {
        return {
            /* 单击行 */
            onClick: (event) => {
                if (tableName === "sheet") {
                    if (record.editable === true) {
                        return;
                    }
                    if (record.code === "") {
                        return;
                    }
                    else {
                        this.setState({ selectSheet: record, updateChild: true }, () => {
                            this.ConfigCondition.getData(record);
                        });
                    }
                    return;
                }
                return;
            },
        };
    }
    //绑定子组件
    onRef = (ref) => {
        this.ConfigCondition = ref;
    }
    render() {
        let marginTop = 16;
        if (this.state.sheet.length === 0) marginTop = 200;
        return (
            <Row className="nurseConfig" style={{ height: '100%', overflow: 'hidden' }}>
                <Col span={5}>
                    <Row style={{ backgroundColor: '#E6F7FF', height: '40px' }}>
                        <Col span={15}>
                            <span style={{ fontsize: '14px' }}>添加单据</span>
                        </Col>
                        <Col>
                            <Button
                                type="primary"
                                icon="save"
                                onClick={this.handleSave}
                            >保存配置</Button>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <Table
                                columns={this.state.sheetColumns}
                                dataSource={this.state.sheet}
                                pagination={false}
                                onRow={this.tableRow.bind(this, "sheet")}
                                rowClassName={(record, index) => {
                                    if (record.code === this.state.selectSheet.code) {
                                        return "clickRowStyle";
                                    }
                                    return;

                                }}
                                rowKey={(row) => {
                                    return row.id + "";
                                }}
                                loading={this.state.leftloading}
                            />
                        </Col>
                    </Row>

                    <Button
                        style={{ width: '100%', marginTop: marginTop, marginBottom: 8 }}
                        type="dashed"
                        onClick={this.newMember}
                        icon="plus"
                    >
                        新增单据
                     </Button>
                </Col>
                <Col span={19} style={{ height: '100%' }}>
                    <ConfigCondition update={this.state.updateChild} onRef={this.onRef} updateState={this.updateState} />
                </Col>
            </Row >
        );
    }

}
export default NurseExcuteConfig;  