/*
 * Creator:     ML
 * CreatDate:   2019-12-13
 * descripts：  护理单元关联床位费添加/编辑
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Modal, message, TimePicker } from 'antd';
import moment from 'moment';
import { $http } from '../../../containers/config/https';

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}

const formItemLayout = { // label 和input宽度
    labelCol: { span: 9 },
    wrapperCol: { span: 15 },
}

const BedToNursModal = Form.create()(
    class BedToNursModal extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                visible: false,
                edit: -1,
                params: {},
                medItemID: undefined,
                id: '',
                roomSelectData: []
            }
        }

        componentDidMount() {
            this.props.OnChildrefs(this);
            this.getHopSelect()
            this.getFeeType()
            this.getRoomType();
        }

        showModal = (record, num) => {
            this.setState({
                visible: true,
            })
            if (record && num && num == "1") {
                // console.log("record",record)
                this.handleBaseHosp(record.hospID)
                this.setState({
                    edit: num,
                    params: record,
                    id: record.ID,
                    medItemID: record.medItemID,
                    bedTypeID: record?.feeTypeID || '', // 费用类别 - 2023/12/01添加
                }, () => {
                    this.props.form.setFieldsValue({ locID: record.locID })
                    this.getTableData();
                })
            }
        }

        //获取医院下拉框
        getHopSelect = () => {
            let data = {
                params: [{
                    hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
                    logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : '',
                    logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
                }],
            }
            $http.post('urlS', this, {
                code: '01040001',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            hospArr: res.result
                        })
                    }
                }
            })
        }

        //获取费用类别
        getFeeType = () => {
            let data = {
                params: [{

                }],
            }
            $http.post('urlS', this, {
                code: '01040130',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            feeArr: res.result.data
                        })
                    }
                }
            })
        }

        //医院选择带出科室
        handleBaseHosp = (id) => {
            this.props.form.setFieldsValue({ locID: undefined })
            if (id) {
                this.setState({
                    hosID: id
                }, () => {
                    this.getPublicBaseLocSelect()
                })
            } else {
                this.setState({
                    hosID: '',
                    publicBaseLocArr: []
                }, () => {
                    this.getPublicBaseLocSelect()
                })
            }
        }

        //获取科室下拉框
        getPublicBaseLocSelect = () => {
            let data = {}
            data = {
                params: [{
                    hospID: this.state.hosID || '',
                    locTypeID: this.state.locID || ''
                }],
            }
            $http.post('urlS', this, {
                code: '01050029',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result.Data) {
                        let arr = res.result.Data && res.result.Data.map((item, index) => {
                            res.result.Data[index].key = Number(index)
                        })
                        this.setState({
                            publicBaseLocArr: res.result.Data,
                        })
                    } else {

                    }
                }
            })
        }

        handleCancel = () => {
            this.props.form.resetFields();
            this.setState({ visible: false, params: {}, medItemID: undefined, edit: -1, id: '' });
        }

        //添加/编辑卡
        handleCreat = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    let data = {}
                    data = {
                        params: [{
                            createUserID: JSON.parse(sessionStorage.userData).userID || '',
                            ID: this.state.id && this.state.id ? this.state.id : '',//修改
                            hospID: values && values.hospID || '',
                            locID: values.locID || '',
                            qty: values.Qty || '',
                            medItemID: this.state.medItemID,//医嘱项目
                            feeTypeID: values.feeTypeDr || '',//费用类型	
                            priorityID: values.priorityID || '',//费用类型	
                            createDate: values.createDate ? moment(values.createDate).format('YYYY-MM-DD') : undefined, // 创建日期
                            startDay: values.startDay ? moment(values.startDay).format('YYYY-MM-DD') : undefined, // 指定天开始
                            stopDay: values.stopDay ? moment(values.stopDay).format('YYYY-MM-DD') : undefined, // 指定天结束
                            startDate: values.dateFrom ? moment(values.dateFrom).format('YYYY-MM-DD') : undefined, // 生效日期
                            stopDate: values.dateTo ? moment(values.dateTo).format('YYYY-MM-DD') : undefined, // 失效日期
                            roomTypeID: values?.roomTypeID || '', // 房间类型
                            billTime: values.billTime ? moment(values.billTime).format('HH:mm') : '', // 计费时间
                        }]
                    }
                    $http.post('urlS', this, {
                        code: '01040126',
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                if (this.state.edit == "1") {
                                    message.success('修改成功');
                                    this.props.getNewData();
                                } else {
                                    message.success('添加成功');
                                    this.props.getNewData(res.result.ID);
                                }
                                this.setState({
                                    visible: false,
                                    edit: -1,
                                    params: {},
                                    medItemID: undefined,
                                    id: ''
                                })
                                this.props.form.resetFields();
                            }
                        }
                    })
                }
            })
        }

        //子组件 搜索医嘱项
        OnChildrefs = (ref) => {
            this.child = ref
        }

        //接收子组件 医嘱项id 描述
        handleParms = (record) => {
            this.props.form.setFieldsValue({ medItemID: record.descripts })
            this.setState({
                medItemID: record.id
            })
        }

        //搜索医嘱项
        handleOrderItem = () => {
            // console.log("this.props.form.getFieldValue('orderItem')",this.props.form.getFieldValue("orderItem"))
            if (this.props.form.getFieldValue("medItemID") && this.props.form.getFieldValue('medItemID').length == 0) {
                message.warning("请输入医嘱项名称")
            } else {
                //调起
                this.child.showModal(this.props.form.getFieldValue("medItemID"))
            }
        }

        handleValue(name, e) {
            this.props.form.resetFields('medItemID', undefined);
            this.setState({
                [name]: e,
                medItemID: undefined
            }, () => {
                this.props.form.setFieldsValue('medItemID', undefined)
                this.getTableData()
            })
        }

        handleSelectOption(name, e) {
            this.setState({
                [name]: e
            })
        }

        getTableData() {
            let data = {
                params: [{
                    hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
                    bedTypeID: this.state.bedTypeID,
                }]
            }
            $http.post('urlS', this, {
                code: '01040227',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setState({ tableData: res.result })
                    }
                }
            })
        }

        //获取房间类型
        getRoomType = () => {
            let data = {
                params: [{
                    roomTypeFlag: 1
                }]
            }
            $http.post('urlS', this, {
                code: '01040022',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            roomSelectData: res?.roomType || []
                        })
                    }
                }
            })
        }

        render() {
            const { prioritySelectData } = this.props;
            const { getFieldDecorator, } = this.props.form;
            const { params, roomSelectData } = this.state
            //医院
            let hosOp = []
            this.state.hospArr && this.state.hospArr.map((item) => {
                hosOp.push(<Option key={item.id} onClick={(e,) => this.handleBaseHosp(item.id)} value={String(item.id)}>{item.descripts}</Option>)
            })
            //科室类型
            let locOp = []
            this.state.publicBaseLocArr && this.state.publicBaseLocArr.map(item => {
                locOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            //费用类别
            let feeOp = []
            this.state.feeArr && this.state.feeArr.map((item) => {
                feeOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
            })

            let ordNoteListtOption = []
            this.state.tableData && this.state.tableData.map((item, index) => {
                ordNoteListtOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
            })

            return (
                <div style={{ padding: '4px 2px' }} className="bedDom">
                    <Modal
                        className='findPatients'
                        width='1000px'
                        visible={this.state.visible}
                        title={this.state.edit == "1" ? "编辑护理单元关联床位费" : "添加护理单元关联床位费"}
                        onOk={this.handleOk}
                        onCancel={this.handleCancel}
                        footer={[
                            <Button key="submit" type="primary" loading={this.setState.loading} disabled={this.state.rowId == ''} onClick={this.handleCreat}>确定</Button>,
                            <Button key="cancel" loading={this.setState.loading} onClick={this.handleCancel}>取消</Button>,
                        ]}>
                        <div className="department-header">
                            <Form>
                                <Row gutter={60} style={{ margin: '0' }}>
                                    <Col span={8} style={paddRightCol}>
                                        <FormItem {...formItemLayout} label='医院'>
                                            {getFieldDecorator('hospID', {
                                                initialValue: params && params.hospID ? String(params.hospID) : undefined,
                                                rules: [{ required: true, message: '请选择医院' }],
                                            })(
                                                <Select
                                                    onChange={this.handleBaseHosp}
                                                >
                                                    {hosOp}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col span={8} style={paddRightCol}>
                                        <FormItem {...formItemLayout} label='费用类别'>
                                            {getFieldDecorator('feeTypeDr', {
                                                initialValue: params && params.feeTypeID ? String(params.feeTypeID) : undefined,
                                                rules: [{ required: true, message: '请选择费用类别' }],
                                            })(
                                                <Select onChange={this.handleValue.bind(this, 'bedTypeID')}
                                                >
                                                    {feeOp}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col span={8} style={paddRightCol}>
                                        <FormItem {...formItemLayout} label='医嘱项'>
                                            {getFieldDecorator('medItemID', {
                                                initialValue: params && params.medItemDescripts ? params.medItemDescripts : this.state.medItemID,
                                                rules: [{ required: true, message: '请输入检索医嘱项' }],
                                            })(
                                                <Select placeholder="输入内容回车检索" allowClear
                                                    onSelect={this.handleSelectOption.bind(this, 'medItemID')}>
                                                    {ordNoteListtOption}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col span={8} style={paddRightCol}>
                                        <FormItem {...formItemLayout} label='科室'>
                                            {getFieldDecorator('locID', {
                                                initialValue: params && params.locID ? String(params.locID) : undefined,
                                                rules: [{ required: true, message: '请选择科室' }],
                                            })(
                                                <Select
                                                    placeholder={"请先选择医院"}
                                                >
                                                    {locOp}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col span={8} style={paddRightCol}>
                                        <FormItem label='费用数量' {...formItemLayout}>
                                            {getFieldDecorator('Qty', {
                                                initialValue: params && params.qty ? params.qty : undefined,
                                                rules: [{ required: true, message: '请输入数量' }],
                                                getValueFromEvent: (event) => {
                                                    return event.target.value.replace(/\D/g, '')
                                                },
                                            })(
                                                <Input allowClear />
                                            )}
                                        </FormItem>
                                    </Col>
                                    {/* </Row>
                                <Row gutter={60} style={{ margin: '0' }}> */}
                                    {/* <Col span={8} style={paddRightCol}>
                                        <FormItem label='创建日期' {...formItemLayout}>
                                            {getFieldDecorator('createDate', {
                                                initialValue: params.createDate ? moment(params.createDate, "YYYY-MM-DD") : moment(),
                                                rules: [{ required: true, message: '请选择创建日期' }],
                                            })(
                                                <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                                    return curDate && curDate > moment().endOf('day');
                                                }} />
                                            )}
                                        </FormItem>
                                    </Col> */}
                                    <Col span={8} style={paddRightCol}>
                                        <FormItem {...formItemLayout} label='房间类型'>
                                            {getFieldDecorator('roomTypeID', {
                                                initialValue: params && params.roomTypeID ? String(params.roomTypeID) : undefined,
                                                // rules: [{ required: true, message: '请选择房间类型' }],
                                            })(
                                                <Select
                                                    showSearch
                                                    allowClear
                                                    optionFilterProp="search"
                                                    placeholder="请选择房间类型"
                                                >
                                                    {React.$SelectOptions(roomSelectData)}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={paddRightCol}>
                                        <FormItem label='生效日期' {...formItemLayout}>
                                            {getFieldDecorator('dateFrom', {
                                                initialValue: params.startDate ? moment(params.startDate, "YYYY-MM-DD") : moment(),
                                                rules: [{ required: true, message: '请选择生效日期' }],
                                            })(
                                                <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                                    return curDate && curDate > moment().endOf('day');
                                                }} />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={paddRightCol}>
                                        <FormItem label='失效日期' {...formItemLayout}>
                                            {getFieldDecorator('dateTo', {
                                                initialValue: params.StopDate ? moment(params.StopDated, "YYYY-MM-DD") : undefined,
                                                rules: [{ required: false, message: '' }],
                                            })(
                                                <DatePicker style={{ width: '100%' }} />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={paddRightCol}>
                                        <FormItem label='医嘱优先级' {...formItemLayout}>
                                            {getFieldDecorator('priorityID', {
                                                initialValue: params && params.priorityID ? params.priorityID : undefined,
                                            })(
                                                <Select
                                                    allowClear
                                                    showSearch
                                                    placeholder="请选择"
                                                    optionFilterProp="search"
                                                >
                                                    {React.$SelectOptions(prioritySelectData)}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={paddRightCol}>
                                        <FormItem label='指定天开始' {...formItemLayout}>
                                            {getFieldDecorator('startDay', {
                                                initialValue: params.startDay ? moment(params.startDay, "YYYY-MM-DD") : moment(),
                                                rules: [{ required: false, message: '' }],
                                            })(
                                                <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                                    return curDate && curDate > moment().endOf('day');
                                                }} />
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col span={8} style={paddRightCol}>
                                        <FormItem label='指定天结束' {...formItemLayout}>
                                            {getFieldDecorator('stopDay', {
                                                initialValue: params.stopDay ? moment(params.stopDay, "YYYY-MM-DD") : undefined,
                                                rules: [{ required: false, message: '' }],
                                            })(
                                                <DatePicker style={{ width: '100%' }}
                                                />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={paddRightCol}>
                                        <FormItem label="计费时间" {...formItemLayout}>
                                            {getFieldDecorator('billTime', {
                                                initialValue: params.billTime ? moment(params.billTime, 'HH:mm') : undefined,
                                            })(
                                                <TimePicker format="HH:mm" style={{ width: '100%' }} />
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                            {/* <DecoctingOrderModal OnChildrefs={this.OnChildrefs} handleParms={this.handleParms}></DecoctingOrderModal> */}
                        </div>
                    </Modal>
                </div>
            )
        }
    });

export default BedToNursModal;