// 库存项---发药单位维护 
import React from 'react';
import { Form, Button, Input, Switch, 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 {
    /**
     * @shizi: 新增是否默认操作 - defaultFlag
     * Create 2021-06-07
     */
    getInput = () => {
        if (this.props.dataIndex === 'dispLocDesc' || this.props.dataIndex === 'dispUnitDesc') {
            return (
                <Select style={{ width: '80%' }} showSearch optionFilterProp="seatchprop" allowClear>
                    {this.props.option}
                </Select>
            );
        } else if (this.props.dataIndex === 'defaultFlag') {
            return <Switch checkedChildren="是" unCheckedChildren="否" />;
        } else {
            return <Input style={{ width: '80%' }} type="number" className="input-number" />;
        }
    };

    renderCell = ({ getFieldDecorator }) => {
        const {
            editing,
            dataIndex,
            title,
            option,
            record,
            index,
            children,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editing ? (dataIndex === 'defaultFlag' ? (
                    <Form.Item >
                        {getFieldDecorator(dataIndex, {
                            valuePropName: 'checked',
                            initialValue: record[dataIndex] && record[dataIndex] === 'Y' ? true : false
                        })(
                            this.getInput()
                        )}
                    </Form.Item>
                ) : (
                    <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 AIIUnitMaintenance extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            columns: [],
            editingKey: '',
            language: JSON.parse(window.sessionStorage.userData),
        }
    }

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

    // 根据下拉框描述找出对应的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
            }
        }
    }

    // 保存时返回数组的值
    handleValidateFields = () => {
        let data = this.state.dataSource;
        for (var i = 0; i < data.length; i++) {
            data[i].dispUnitID = this.fildID(data[i].dispUnitDesc, this.props.selectData && this.props.selectData.unit); // 发药单位ID
            data[i].dispLocID = this.fildID(data[i].dispLocDesc, this.props.selectData && this.props.selectData.loc); // 发药科室ID
            data[i].defaultFlag = data[i] && data[i].defaultFlag ? 'Y' : 'N'
        }
        this.props.receiveSubcomponentsValue(data.filter(item => item.dispUnitID), 'unitMaintenance')
    }

    // 获取表头数据
    getColumnsData = () => {
        let columns = [
            {
                title: this.state.language.language == 'EN' ? 'Medicine department' : '发药科室',
                dataIndex: 'dispLocDesc',
                editable: true,
                width: '150px',
                align: 'center'
            },
            {
                title: this.state.language.language == 'EN' ? 'Drug delivery unit' : '发药单位',
                dataIndex: 'dispUnitDesc',
                editable: true,
                width: '150px',
                align: 'center'
            },
            {
                title: this.state.language.language == 'EN' ? 'Conversion factor' : '转换系数',
                dataIndex: 'factor',
                editable: true,
                width: '150px',
                align: 'center'
            }, {
                title: '是否默认',
                dataIndex: 'defaultFlag',
                editable: true,
                width: '100px',
                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.key, record)}>
                                {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 })
    }

    // 获取表格数据
    getTableData = (tableData) => {
        let dataSource = JSON.parse(JSON.stringify(tableData));
        for (var i = 0; i < dataSource.length; i++) {
            dataSource[i].key = 'dispUomID' in dataSource[i] && dataSource[i].dispUomID ? dataSource[i].dispUomID : ('ID' in dataSource[i] && dataSource[i].ID ? dataSource[i].ID : i + 1);
        }
        this.setState({ dataSource, editingKey: '' });
    }

    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;
            }
            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 = (key, record) => {
        this.setState({ editingKey: key }, () => {
            this.props.form.setFieldsValue({
                ...record,
                defaultFlag: record && 'defaultFlag' in record && record.defaultFlag === 'Y' ? true : false
            });
        });
    }

    // 本地删除数据
    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;
        let rowID = 'dispUomID' in record && record.dispUomID ? record.dispUomID : record?.ID; // 表ID
        if (rowID && isSaveAnother !== "saveAnother") {
            let data = {
                params: [
                    {
                        dispUomID: rowID
                    }
                ]
            }
            $http.post('urlS', this, {
                code: "02020239",
                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;
        const newData = {
            key: leg,
            dispLocDesc: undefined,
            dispUnitDesc: undefined,
            factor: undefined,
            defaultFlag: 'N'
        };
        this.setState({
            dataSource: [...dataSource, newData]
        }, () => {
            if (!this.state.editingKey) {
                this.setState({ editingKey: leg })
            }
        });
    }

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

    resetFieldsEditingKey = () => {
        this.setState({ editingKey: '' })
    }

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

    render() {
        let { dataSource, columns } = this.state;
        const components = {
            body: {
                cell: EditableCell,
            },
        };
        let selectData = this.props.selectData;

        // 发药科室
        let locOption = selectData && selectData.loc && selectData.loc.map((item, index) => {
            return (<Option key={index} value={item.descripts} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 发药单位
        let unitOption = selectData && selectData.unit && selectData.unit.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 === 'dispLocDesc' ? locOption : unitOption,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                }),
            };
        });
        let ChineseEnglishSize = this.props.ChineseEnglishSize;
        return (
            <Card
                type="inner"
                title={<div style={{ position: 'relative' }}>
                    {ChineseEnglishSize.DrugMaintenancedrugDeliveryUnitMaintenance ? ChineseEnglishSize.DrugMaintenancedrugDeliveryUnitMaintenance.descripts : '发药单位维护'}
                    <span style={{ position: 'absolute', top: '-6px', right: '4px' }}>
                        <Button onClick={this.handleAddTableData}>{ChineseEnglishSize.DrugMaintenanceadd ? ChineseEnglishSize.DrugMaintenanceadd.descripts : '新增'}</Button>
                        {this.props.handleHttpSave ? <Button type='primary' style={{ marginLeft: '12px' }} onClick={this.props.handleHttpSave}>保存</Button> : ''}
                    </span>
                </div>}
                size="small"
            >
                <div style={{ padding: '8px 15px' }}>
                    {/* <div style={{textAlign: 'right', margin: '8px 0'}}>
                        <Button onClick={this.handleAddTableData}>新增</Button>
                    </div> */}
                    <EditableContext.Provider value={this.props.form}>
                        <Table
                            style={{ minHeight: '220px' }}
                            components={components}
                            bordered
                            dataSource={dataSource}
                            columns={filterColumns}
                            rowClassName="editable-row"
                            pagination={false}
                            onRow={this.handleOnRow}
                        />
                    </EditableContext.Provider>
                </div>
            </Card>
        )
    }
};
let AIIUnitMaintenanceForm = Form.create()(AIIUnitMaintenance);
export default AIIUnitMaintenanceForm;