/*
 * Create:      TC
 * CreateDate:  2022/08/24
 * Describe：   医嘱项参数配置
 * */
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm, DatePicker, Col } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import '../style/childStyle.less';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const { Option } = Select;
let user;
class MedItemPropConfig extends React.Component {
    constructor() {
        super();
        user = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            hospData: [],
            configData: [], // 下拉框数据
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 10,
            rowData: {}, // 编辑回显数据
            medID: '',
        };
        this.columns = [
            {
                key: 1,
                title: '序号',
                dataIndex: 'key',
                align: "center",
                width: 50,
                render: (text, record, index) => {
                    return this.state.tableData.findIndex((value, index) => {
                        return value === record;
                    }) + 1;
                }
            },
            {
                key: 2,
                title: '配置项',
                dataIndex: 'configDesc',
                align: "center",
                width: 150
            },
            {
                key: 3,
                title: '配置值',
                dataIndex: 'configValue',
                align: "center",
                width: 150
            },
            {
                title: '操作',
                key: 4,
                align: "center",
                width: 80,
                render: (text, record) => (
                    <span>
                        <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                        <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                        {/* 分割线 */}
                        <Divider type="vertical" />
                        <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                        </Popconfirm>
                    </span>
                ),
            }
        ];
    }

    componentDidMount() {
        this.getSelectData();
        if ((this.props.medData && this.props.medData.medID ? this.props.medData.medID : '') !== this.state.medID) {
            this.setState({ medID: this.props.medData.medID }, () => {
                this.handleQuery();
            })
        } else {
            this.child.handleLoading();
        }
    }

    componentWillReceiveProps(nextProps) {
        if ((nextProps.medData && nextProps.medData.medID ? nextProps.medData.medID : '') !== this.state.medID) {
            this.setState({ medID: nextProps.medData.medID }, () => {
                this.handleQuery();
                this.resetFields();
            })
        }
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 获取下拉框数据
    getSelectData = () => {
        let data = {
            params: [{
                logonHospID: user.hospID,
                logonGroupID: user.groupID,
                hospFlag: 'Y',
            }]
        }
        $http.post('urlS', this, {
            code: "03010118",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    this.setState({ configData: res.result });
                }
            }
        })
        $http.post('urlS', this, {
            code: "03010037",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    this.setState({ hospData: res.result.hosp });
                }
            }
        })
    }

    // 请求列表数据
    getTableData() {
        let { page, pageSize, medID } = this.state;
        let data = {
            params: [{
                medItemID: medID // 医嘱项id
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "03010120",
            data: data,
            success: function (res) {
                if (+res.errorCode == 0 && res.result) {
                    this.setState({ tableData: res.result.rows, total: res.result.total }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                } else {
                    this.setState({ tableData: [], total: 0 }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                }
            },
            error: function () {
                this.setState({ tableData: [], total: 0 }, () => {
                    // 数据加载成功关闭loading
                    this.child.handleLoading();
                })
            }
        })
    }

    // 查询
    handleQuery = () => {
        this.setState({ page: 1, pageSize: 10 }, () => {
            this.getTableData();
        })
    }


    // 保存
    handleSave = () => {
        const { rowData, user, medID } = this.state;
        this.props.form.validateFields((errors, values) => {
            if (errors) {
                return;
            }
            let data = {
                params: [{
                    id: rowData.id,
                    medID: medID,
                    hospID: values.hospID,
                    configID: values.configID,
                    configValue: values.configValue,
                }]
            };

            $http.post('urlADS', this, {
                code: '03010119',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success('保存成功');
                        this.handleQuery();
                        this.resetFields();
                    }
                }
            })
        })
    }

    // 重置
    resetFields = () => {
        this.props.form.resetFields(); //清空所有
        this.setState({
            rowData: {}
        })
    }

    // 编辑
    handleCompile = record => {
        this.resetFields();
        this.setState({ rowData: record });
    }

    // 删除
    handleDelete = record => {
        let data = {
            params: [{
                id: record.id,
            }]
        }
        $http.post('urlADS', this, {
            code: '03010121',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('删除成功');
                    // 刷新列表数据
                    this.getTableData();
                }
            }
        })
    }

    onHospChange = (value) => {
        // 过敏源
        const { configData } = this.state;
        let hospData = [];
        configData.hospData && configData.hospData.map((item, index) => {
            if (value == item.typeID) {
                hospData.push(item)
            }
        })
        this.setState({ hospData: hospData });
        this.props.form.setFieldsValue({ configID: undefined });
    }

    compilePage = (page, pageSize) => {
        this.setState({
            page,
            pageSize,
        }, () => {
            this.getTableData()
        })

    }
    render() {
        const { configData, tableData, total, page, rowData, hospData } = this.state;

        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.columns,
            // 表格数据
            data: tableData,
            // 数据总条数
            total: total,
            // 当前页数
            page: page,
            // 表格的宽度
            x: 900,
            y: 360,
            TableClassName: "medAll",
            height: '400px'
        };

        const formLayout = {
            labelCol: { span: 10 },
            wrapperCol: { span: 14 },
        }

        // 过敏源类型
        let hospOpt = [];
        hospData && hospData.map((item, index) => {
            hospOpt.push(<Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        });

        let configOpt = [];
        configData && configData.map((item, index) => {
            configOpt.push(<Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        });

        return (
            <div>
                <Form layout={'horizontal'}>
                    <Row>
                        <Col span={5}>
                            <Form.Item label="医院" {...formLayout}>
                                {getFieldDecorator('hospID', {
                                    initialValue: rowData.hospID ? rowData.hospID : user.hospID,
                                    rules: [{ required: true, message: '不能为空' }]
                                })(
                                    <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100%' }} placeholder="请选择">
                                        {hospOpt}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={5}>
                            <Form.Item label="配置项" {...formLayout}>
                                {getFieldDecorator('configID', {
                                    initialValue: rowData.configID ? rowData.configID : undefined,
                                    rules: [{ required: true, message: '不能为空' }]
                                })(
                                    <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100%' }} placeholder="请选择">
                                        {configOpt}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={5}>
                            <Form.Item label="值"  {...formLayout}>
                                {getFieldDecorator('configValue', {
                                    initialValue: rowData.configValue ? rowData.configValue : undefined,
                                    rules: [{ required: true, message: '请输入...' }]
                                })(
                                    <Input />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Button style={{ margin: '3px 10px 0 10px' }} type="primary" onClick={this.handleSave}>{rowData.linkID ? '修改' : '保存'}</Button>
                            <span style={{ display: 'inline-block', marginTop: '4px' }}>
                                <Button onClick={this.resetFields}>清空</Button>
                            </span>
                        </Col>
                    </Row>
                </Form>
                <div>
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
            </div>
        )
    }
};
const MedItemPropConfigForm = Form.create()(MedItemPropConfig);
export default MedItemPropConfigForm;