// 病程标题配置
import React from 'react';
import './style/index.less';
import { Table, Input, InputNumber, Popconfirm, Form, Divider, Select, Button, Modal, message, Checkbox, Row, Col } from 'antd';
import { $http } from 'containers/config/https';
const { Option } = Select;

const EditableContext = React.createContext();

function requestHttp(code, data) {
    return new Promise((resolve, reject) => {
        $http.post('urlS', this, {
            code: code,
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    resolve(res);
                } else {
                    reject(res);
                }
            },
            error: function (error) {
                reject(error);
            }
        });
    })
}

class EditableCell extends React.Component {

    componentDidMount() {
        console.log("this.props.templateList===", this.props.templateList);
    }
    getInput = () => {
        function handleChange(value) {
            console.log(`selected ${value}`);
        }

        if (this.props.inputType === 'number') {
            return <InputNumber />;
        } else if (this.props.inputType === 'select') {
            return (
                <Select style={{ width: '100%' }} placeholder="请选择" onChange={handleChange} allowClear >
                    {
                        this.props.hospitalList.map(item => {
                            return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                        })
                    }
                </Select>
            )
        } else if (this.props.inputType === 'multiple') {
            return (
                <Select mode="multiple" style={{ width: '100%' }} placeholder="请选择" onChange={handleChange} >
                    {
                        this.props.templateList.map(item => {
                            return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                        })
                    }
                </Select>
            )
        }
        return <Input />;
    };

    renderCell = ({ getFieldDecorator }) => {
        const {
            editing,
            dataIndex,
            title,
            inputType,
            record,
            index,
            children,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item style={{ margin: 0 }}>
                        {getFieldDecorator(dataIndex, {
                            rules: [
                                {
                                    required: true,
                                    message: `请输入 ${title}!`,
                                },
                            ],
                            initialValue: record[dataIndex],
                        })(this.getInput())}
                    </Form.Item>
                ) : (
                        children
                    )}
            </td>
        );
    };

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

@Form.create()

export default class DiseaseProgressTitle extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            editingKey: '',
            templateList: [],
            hospitalList: [],
            visible: false,
            EMRProgTitleID: "",
            searchValue: "",
            checked: false,
            searchObj: {}
        };
        this.columns = [
            { title: '病程标题描述', dataIndex: 'EMRProgTitleDesc', editable: true, align: "center" },
            // { title: '病程标题代码', dataIndex: 'EMRProgTitleCode', editable: true, align: "center" },
            { title: '医院', dataIndex: 'hospDesc', editable: true, align: "center" },
            {
                title: '模板', dataIndex: 'EMRTemplateIDs', editable: true, width: "20%", align: "center", render: (text, record) => {
                    return <span>
                        {
                            record.EMRTemplateData && record.EMRTemplateData.map(data => {
                                return data.descripts;
                            }).join("  ")
                        }
                    </span>
                }
            },
            {
                title: '是否与父病历同级目录',
                dataIndex: 'progIsSuperCatalog',
                editable: true,
                align: "center",
                render: (text, record) => {
                    return text == "Y" ? "是" : "否"
                }
            },
            {
                title: '显示顺序',
                dataIndex: 'EMRProgTitleSeqNo',
                editable: true,
                align: "center"
            },
            {
                title: '是否有效',
                dataIndex: 'EMRProgTitleAvailable',
                editable: true,
                align: "center",
                render: (text, record) => {
                    return text == "Y" ? "是" : "否"
                }
            },
            {
                title: '操作',
                dataIndex: 'operation',
                align: "center",
                render: (text, record) => {
                    const { editingKey } = this.state;
                    const editable = this.isEditing(record);
                    return editable ? (
                        <span>
                            <EditableContext.Consumer>
                                {form => (
                                    <a onClick={() => this.save(form, record.key)} style={{ marginRight: 8 }} > 保存 </a>
                                )}
                            </EditableContext.Consumer>
                            <a onClick={() => this.cancel(record.key)}>取消</a>
                        </span>
                    ) : (
                            <>
                                <a disabled={editingKey !== ''} onClick={() => this.onEdit(record)}> 编辑 </a>
                                <Divider type="vertical" />
                                <Popconfirm title="确定要删除吗?" onConfirm={() => this.onDelete(record)}>
                                    <a> 删除</a>
                                </Popconfirm>
                            </>
                        );
                },
            },
        ];
    }

    getDiseaseList = async (queryParams) => {
        let queryObj = {};
        if (queryParams) {
            queryObj = queryParams;
        }
        let res = await requestHttp("06060108", { params: [queryObj] });
        let newData = res.result.data && res.result.data.map(item => {
            return { key: item.EMRProgTitleID, ...item }
        })
        this.setState({ data: newData });
    }

    getHospital = async () => {
        let { hospID, groupID } = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let res = await requestHttp("01040001", { params: [{ hospID: hospID, logonGroupID: groupID, logonHospID: hospID }] });
        this.setState({ hospitalList: res.result });
    }

    getTemplateList = async () => {
        let res = await requestHttp("06020003", { params: [{ 
            typePower: "textTemplate", 
            isReleaseVer:"Y", // 查询有发布版本的模板
        }] });
        let newData = res.result && res.result.map(item => {
            return { id: item.ID, code: item.code, descripts: item.descripts }
        });
        this.setState({ templateList: newData }, () => {
            this.getDiseaseList();
        });
    }

    componentDidMount() {
        this.getHospital();
        this.getTemplateList();
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

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

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

    save(form, key) {
        form.validateFields((error, row) => {
            if (error) {
                return;
            }
            console.log("editingKey=", this.state.editingKey, "row=", row);
            // let newData = this.state.data.map(data=>{
            //     if(this.state.editingKey == data.EMRProgTitleID){
            //         data.hospDesc = "666";
            //     }
            //     return data;
            // });
            // this.setState({data:newData});

            // let hosData =  this.state.hospitalList.find(item=>{
            //     if(row.hospDesc = item.id){
            //         return item
            //     }else{
            //        return row; 
            //     }
            // });
            // console.log("hosData==",hosData);
            // newData.descripts = hosData.descripts;

            let newData = [...this.state.data];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row
                });
                this.setState({ data: newData, editingKey: '' });
            } else {
                newData.push(row);
                this.setState({ data: newData, editingKey: '' });
            }

        });
    }

    onEdit(values) {
        // this.setState({ editingKey: key });
        console.log("values===", values);
        this.props.form.setFieldsValue({
            EMRProgTitleDesc: values.EMRProgTitleDesc,
            hospDesc: values.hospDesc,
            EMRTemplateIDs: values.EMRTemplateIDs,
            EMRProgTitleAvailable: values.EMRProgTitleAvailable
        });
        this.setState({ visible: true, EMRProgTitleID: values.EMRProgTitleID });
    }

    onDelete = async (values) => {
        let res = await requestHttp("06060107", { params: [{ EMRProgTitleID: values.EMRProgTitleID, power: "delete" }] });
        console.log("res", res)
        if (res) {
            message.success(res.errorMessage);
            this.getDiseaseList();
        }
    }

    returnType = (dataIndex) => {
        let obj = {
            hospDesc: "select",
            EMRTemplateIDs: "multiple"
        };
        return obj[dataIndex];
    }

    onAdd = () => {
        this.props.form.resetFields();
        this.setState({ visible: true, EMRProgTitleID: "" });
    }

    handleOk = () => {
        this.props.form.validateFields(async (error, values) => {
            if (error) return;
            console.log("values===", values);
            let { hospID } = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
            let obj = { 
                hospID: hospID, 
                EMRProgTitleDesc: values.EMRProgTitleDesc, 
                EMRTemplateIDs: values.EMRTemplateIDs, 
                EMRProgTitleAvailable: values.EMRProgTitleAvailable,
                progIsSuperCatalog: values.progIsSuperCatalog,
                EMRProgTitleSeqNo: values.EMRProgTitleSeqNo
            };
            if (this.state.EMRProgTitleID !== "") {
                obj.EMRProgTitleID = this.state.EMRProgTitleID;
            }
            let params = { params: [obj] };
            let res = await requestHttp("06060107", params);
            if (res) {
                message.info(this.state.EMRProgTitleID !== "" ? "编辑成功" : "添加成功");
                this.setState({ visible: false }, () => {
                    this.getDiseaseList();
                });
            } else {
                message.info(res.errorMessage);
            }
        })
    }

    handleCancel = () => {
        this.setState({ visible: false });
    }

    // 修改搜索值
    onChangeValue = (key, value) => {
        this.state.searchObj[key] = value;
        this.setState({ searchObj: this.state.searchObj });
    }

    onQuery = () => {
        this.getDiseaseList({
            EMRProgTitleDesc: this.state.searchObj["EMRProgTitleDesc"],
            hospID: this.state.searchObj["hospID"],
            EMRTemplateID: this.state.searchObj["EMRTemplateIDs"],
            EMRProgTitleAvailable: this.state.searchObj["EMRProgTitleAvailable"] ? "Y" : ""
        });
    }
    render() {
        const components = {
            body: {
                cell: EditableCell,
            },
        };
        const columns = this.columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    inputType: this.returnType(col.dataIndex),
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                    templateList: this.state.templateList,
                    hospitalList: this.state.hospitalList
                }),
            };
        });

        const { getFieldDecorator } = this.props.form;

        return (
            <EditableContext.Provider value={this.props.form} >
                <div className="searchFlex">
                    <Row gutter={[24, 8]}>
                        <Col span={6}>
                            <Input value={this.state.searchObj["EMRProgTitleDesc"]} onChange={({ target: { value } }) => this.onChangeValue("EMRProgTitleDesc", value)} style={{ marginLeft: 10 }} placeholder="请输入病程标题描述" allowClear />
                        </Col>
                        <Col span={4}>
                            <Select style={{width: "100%"}} onChange={(key) => this.onChangeValue("hospID", key)} placeholder="请选择医院" allowClear>
                                {
                                    this.state.hospitalList.map(item => {
                                        return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                                    })
                                }
                            </Select>
                        </Col>
                        <Col span={4}>
                            <Select style={{width: "100%"}} onChange={(key) => this.onChangeValue("EMRTemplateIDs", key)} placeholder="请选择模板" allowClear>
                                {
                                    this.state.templateList.map(item => {
                                        return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                                    })
                                }
                            </Select>
                        </Col>
                        <Col span={4}>
                            <Checkbox checked={this.state.searchObj["EMRProgTitleAvailable"]} onChange={({ target: { checked } }) => this.onChangeValue("EMRProgTitleAvailable", checked)}>是否有效</Checkbox>
                            <Button type="primary" onClick={this.onQuery}>查询</Button>
                        </Col>
                        <Col span={4}>
                            <Button type="primary" onClick={this.onAdd}>添加</Button>
                        </Col>
                    </Row>

                </div>
                <Table
                    // components={components}
                    bordered
                    dataSource={this.state.data}
                    columns={this.columns}
                    rowClassName="editable-row"
                    pagination={{
                        onChange: this.cancel,
                    }}
                />
                <Modal
                    title={this.state.EMRProgTitleID !== "" ? "编辑" : "添加"}
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <Form labelCol={{ span: 8 }} wrapperCol={{ span: 12 }} onSubmit={this.handleSubmit}>

                        <Form.Item label="标题描述">
                            {getFieldDecorator('EMRProgTitleDesc', {
                                rules: [{ required: true, message: '请填写标题描述!' }],
                            })(<Input />)}
                        </Form.Item>

                        <Form.Item label="医院">
                            {getFieldDecorator('hospDesc', {
                                rules: [{ required: true, message: '请选择医院!' }],
                            })(
                                <Select style={{width: "100%"}} allowClear>
                                    {
                                        this.state.hospitalList.map(item => {
                                            return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                                        })
                                    }
                                </Select>,
                            )}
                        </Form.Item>
                        <Form.Item label="模板">
                            {getFieldDecorator('EMRTemplateIDs', {
                                rules: [{ required: true, message: '请填写模板!' }],
                            })(
                                <Select style={{width: "100%"}}  mode="multiple" optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                    {
                                        this.state.templateList.map(item => {
                                            return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                                        })
                                    }
                                </Select>,
                            )}
                        </Form.Item>
                        <Form.Item label="是否与父病历同级目录">
                            {getFieldDecorator('progIsSuperCatalog', {
                                initialValue: "N",
                                // rules: [{ required: true, message: 'Please input your note!' }],
                            })(<Select style={{width: "100%"}} >
                                <Option key={"Y"} value="Y">是</Option>
                                <Option key={"N"} value="N">否</Option>
                            </Select>)}
                        </Form.Item>
                        <Form.Item label="显示顺序">
                            {getFieldDecorator('EMRProgTitleSeqNo', {
                                initialValue: undefined,
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item label="是否有效">
                            {getFieldDecorator('EMRProgTitleAvailable', {
                                initialValue: "Y",
                                // rules: [{ required: true, message: 'Please input your note!' }],
                            })(<Select style={{width: "100%"}} >
                                <Option key={"Y"} value="Y">是</Option>
                                <Option key={"N"} value="N">否</Option>
                            </Select>)}
                        </Form.Item>
                    </Form>
                </Modal>
            </EditableContext.Provider>
        );
    }
}