// 医嘱项---限制用药 
import React from 'react';
import {Form, Button, Table, Card, Popconfirm, Select, Divider, message} from 'antd';
import { $http } from 'containers/config/https';
import { Util } from 'tools/index';

let {Option} = Select;

const EditableContext = React.createContext();

class EditableCell extends React.Component {
    getInput = () => {
        return <Select style={{width: '80%'}} 
                onSelect={this.props.dataIndex === 'operTypeDesc' ? this.props.pointerDescOnChange : ''}
                >
            {this.props.option}
        </Select>;
        
    };

    renderCell = ({ getFieldDecorator }) => {
        const {
            editing,
            dataIndex,
            title,
            option,
            inputType,
            record,
            index,
            children,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item style={{ margin: 0 }}>
                        {getFieldDecorator(dataIndex, {
                        rules: [
                            {
                            required: true,
                            message: `${title + (JSON.parse(window.sessionStorage.userData).language == 'EN' ? ' Can not be empty!' : '不能为空!')}`,
                            },
                        ],
                        initialValue: record[dataIndex],
                        })(this.getInput())}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };

    render() {
        return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
    }
}

class ADADrugRestriction extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            columns: [],
            editingKey: '',
            pointerDescSelectData: [],
            language: JSON.parse(window.sessionStorage.userData),
        }
    }

    componentDidMount() {
        this.props.onRef(this);
        this.getColumnsData();
    }

    handleValidateFields = () => {
        let data = this.state.dataSource;
        for(var i = 0; i < data.length; i++) {
            data[i].operTypeID = this.fildID(data[i].operTypeDesc, this.props.selectData&&this.props.selectData.operType); // 类型ID
            data[i].pointerID = data[i].pointerID ? data[i].pointerID : this.fildID(data[i].pointerDesc, data[i].pointerDescSelectData); // 类型值ID
            data[i].operateID = this.fildID(data[i].operateDesc, this.props.selectData&&this.props.selectData.operate); // 操作ID
            data[i].levelID = this.fildID(data[i].levelDesc, this.props.selectData&&this.props.selectData.level); // 管控级别ID
        }
        this.props.receiveSubcomponentsValue(data.filter(item => item.pointerID), 'drugRestriction')
    }

    // 获取表格数据
    getTableData = (tableData) => {
        let dataSource = JSON.parse(JSON.stringify(tableData));
        for(var i = 0; i < dataSource.length; i++) {
            dataSource[i].key = i + 1;
        }
        this.setState({dataSource});
    }

    // 获取表头数据
    getColumnsData = () => {
        let columns = [
            {
                title: this.state.language.language == 'EN'?'range':'范围',
                dataIndex: 'operateDesc',
                editable: true,
                width: '150px',
                align: 'center'
            },
            {
                title: this.state.language.language == 'EN'?'Types of':'类型',
                dataIndex: 'operTypeDesc',
                editable: true,
                width: '150px',
                align: 'center'
            },
            {
                title: this.state.language.language == 'EN'?'Type value':'类型值',
                dataIndex: 'pointerDesc',
                editable: true,
                width: '150px',
                align: 'center'
            },
            {
                title: this.state.language.language == 'EN'?'Management level':'管控级别',
                dataIndex: 'levelDesc',
                editable: true,
                width: '150px',
                align: 'center'
            },
            {
                title: this.state.language.language == 'EN'?'operating':'操作',
                dataIndex: 'operation',
                width: '130px',
                align: 'center',
                render: (text, record) => {
                    const { editingKey } = this.state;
                    const editable = this.isEditing(record);
                    return editable ? (
                        <span>
                            <EditableContext.Consumer>
                                {form => (
                                    <span
                                        className="span"
                                        onClick={() => this.handleSave(form, record.key)}
                                    >
                                        {this.state.language.language == 'EN'?'save':'保存'}
                                    </span>
                                )}
                            </EditableContext.Consumer>
                            <Divider type="vertical" />
                            <Popconfirm title={this.state.language.language == 'EN'?'Do you cancel editing?':"是否取消编辑?"} okText={this.state.language.language == 'EN' ? "Yes" : '是'} cancelText={this.state.language.language == 'EN' ? "No" : '否'} onConfirm={() => this.handleCancel(record)}>
                                <span className="span" style={{color: 'rgba(240,65,52,1)'}}>{this.state.language.language == 'EN'?'cancel':'取消'}</span>
                            </Popconfirm>
                        </span>
                    ) : (
                        <span>
                            <a className="span" disabled={editingKey !== ''} onClick={() => this.handleEdit(record, record.key)}>
                               {this.state.language.language == 'EN'?'edit':'编辑'}
                            </a>
                            <Divider type="vertical" />
                            <Popconfirm title={this.state.language.language == 'EN'?'Delete is not recoverable, are you sure you want to delete it?':"删除不可恢复，你确定要删除吗?"} okText={this.state.language.language == 'EN' ? "Yes" : '是'} cancelText={this.state.language.language == 'EN' ? "No" : '否'} onConfirm={() => this.handleDelete(record)}>
                                <span className="span" style={{color: 'rgba(240,65,52,1)'}}>{this.state.language.language == 'EN'?'delete':'删除'}</span>
                            </Popconfirm>
                        </span>
                    );
                },
            },
        ];
        this.setState({columns})
    }

    isEditing = record => record.key === this.state.editingKey;

    // 取消
    handleCancel = (record) => {
        let status =  Util.checkAttributeIsEmpty(this.props.form.getFieldsValue());
        if (status) {
            // 都为空则删除该条记录
            this.setState({editingKey: ''}, () => {
                this.handleDelete(record);
            })
        } else {
            this.setState({editingKey: ''})
        }
    };
  
    // 保存
    handleSave = (form, key) => {
        form.validateFields((error, row) => {
            if (error) {
                return;
            }
            row.pointerDescSelectData = JSON.parse(JSON.stringify(this.state.pointerDescSelectData))
            const newData = [...this.state.dataSource];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row,
                });
                this.setState({ dataSource: newData, editingKey: '' }, () => {
                    this.props && this.props.handleSave && this.props.handleSave();
                });
            } else {
                newData.push(row);
                this.setState({ dataSource: newData, editingKey: '' }, () => {
                    this.props && this.props.handleSave && this.props.handleSave();
                });
            }
        });
    }
  
    // 编辑
    handleEdit = (record, key) => {
        this.pointerDescOnChange(record.operTypeDesc);
        this.setState({ editingKey: key });
    }

    // 本地删除数据
    deleteRow(key){
        const dataSource = JSON.parse(JSON.stringify(this.state.dataSource));
        this.setState({ dataSource: dataSource.filter(item => item.key !== key)});
    }
  
    // 删除
    handleDelete = (record) => {
        let isSaveAnother = this.props.isSaveAnother;
        if (record.medAutID && isSaveAnother !== "saveAnother") {
            let data ={
                params: [
                    {
                        medAutID: record.medAutID,
                    }
                ]
            }
            $http.post('urlS', this, {
                code: "02020229",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.deleteRow(record.key);
                    }
                }
            })
        } else {
            this.deleteRow(record.key)
        }
    }

    // 新增表格数据
    handleAddTableData = () => {
        const { dataSource } = this.state;
        let leg = dataSource&&dataSource.length ? dataSource.length + 1 : 1;
        let arr = [];
        const newData = {
          key: leg,
          operateDesc: undefined,
          operTypeDesc: undefined,
          pointerDesc: undefined,
          levelDesc: undefined
        };
        arr.push(newData)
        this.setState({
          dataSource: dataSource&&dataSource.length> 0 ? [...dataSource, newData] : arr,
          pointerDescSelectData: []
        }, () => {
            if (!this.state.editingKey) {
                this.setState({editingKey: leg})
            }
        });
    }

    // 重置数据
    resetFields = () => {
        this.setState({dataSource: [], editingKey: ''})
    }

    resetFieldsEditingKey = () => {
        // this.props.form.resetFields();
        this.setState({editingKey: ''})
    }

    handleOnRow = (record) => {
        return {
            onDoubleClick: () => {
                this.props.form.resetFields();
                this.setState({ editingKey: record.key });
            }
        }
    }

    // 根据下拉框描述找出对应的id
    fildID = (desc, data) => {
        if (!(data&&data.length > 0)) {
            return;
        }
        for(var i = 0; i < data.length; i++) {
            if(data[i].descripts === desc) {
                return data[i].id
            }
        }
    }

    // 选择类型查询类型值下拉框数据
    pointerDescOnChange = (key) => {
        let operTypeID = this.fildID(key, this.props.selectData&&this.props.selectData.operType);
        let data = {
            params: [{
                operTypeID
            }],
        }
        $http.post('urlS', this, {
            code: "02020232",
            data: data,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({pointerDescSelectData: res.result})
                }
            }
        });
    }
    
    render() {
        let {dataSource, columns, pointerDescSelectData} = this.state;
        const components = {
            body: {
                cell: EditableCell,
            },
        };
        let selectData = this.props.selectData;

        // 范围
        let operateDescOption = selectData&&selectData.operate&&selectData.operate.map((item, index) => {
            return (<Option key={index} value={item.descripts} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 类型
        let operTypeDescOption = selectData&&selectData.operType&&selectData.operType.map((item, index) => {
            return (<Option key={index} value={item.descripts} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 类型值
        let pointerDescOption = pointerDescSelectData&&pointerDescSelectData.map((item, index) => {
            return (<Option key={index} value={item.descripts} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 管控级别
        let levelDescOption = selectData&&selectData.level&&selectData.level.map((item, index) => {
            return (<Option key={index} value={item.descripts} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        const filterColumns = columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    option: col.dataIndex === 'operateDesc' ? operateDescOption : (col.dataIndex === 'operTypeDesc' ? operTypeDescOption : (col.dataIndex === 'pointerDesc' ? pointerDescOption : levelDescOption)),
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                    pointerDescOnChange: this.pointerDescOnChange
                }),
            };
        });
        let  ChineseEnglishSize=this.props.ChineseEnglishSize;
        return (
            <Card
                type="inner"
                size="small"
                title={<div style={{position: 'relative'}}>
                    {ChineseEnglishSize.DrugMaintenancedrugRestriction ? ChineseEnglishSize.DrugMaintenancedrugRestriction.descripts:'限制用药'}
                    <span style={{marginLeft: '6px', color: "#999", fontSize: "12px"}}> {ChineseEnglishSize.DrugMaintenancedrugRestrictionTips ? ChineseEnglishSize.DrugMaintenancedrugRestrictionTips.descripts:'提示：在选择类型值前请先选择类型值'}</span>
                    <span style={{position: 'absolute', top: '-6px', right: '4px'}}><Button onClick={this.handleAddTableData}>  {ChineseEnglishSize.DrugMaintenanceadd ? ChineseEnglishSize.DrugMaintenanceadd.descripts:'新增'}</Button></span>
                </div>}
            >
                <div style={{padding: '8px 15px'}}>
                    <EditableContext.Provider value={this.props.form}>
                        <Table
                            style={{minHeight: '220px'}}
                            components={components}
                            bordered
                            dataSource={dataSource}
                            columns={filterColumns}
                            rowClassName="editable-row"
                            pagination={{
                                onChange: this.handleCancel,
                            }}
                            onRow={this.handleOnRow}
                        />
                    </EditableContext.Provider>
                </div>
            </Card>
        )
    }
};
let ADADrugRestrictionForm = Form.create()(ADADrugRestriction);
export default ADADrugRestrictionForm;
