/*
 * Creator:     ML
 * CreatDate:   2019-12-19
 * descripts：  床位费类型关联费用项目添加/编辑
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Modal, Table, Icon, AutoComplete, message, Divider, Tooltip, Checkbox } from 'antd';
import moment from 'moment';
import { $http } from '../../../containers/config/https';
import ShowCommonTableModal from 'pages/workstation/component/ShowCommonTableModal'
import store from '../../../store';
const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 9 },
    wrapperCol: { span: 15 },
}
const formLayoutItem = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
}
const formLayoutItemType = {
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
}
const BedCostTypeToMedModal = Form.create()(
    class BedCostTypeToMedModal extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                visible: false,
                baseParms: {},
                edit: -1,
                params: {},
                id: "",
                isShowCommonTableModal: false,
                pageSizeTop: 10,
                pageTop: 1,
                rowMedID: ""
            }
        }
        componentDidMount() {
            this.props.OnChildrefs(this);
            this.getHopSelect()
            this.getFeeType()
        }
        showModal = (record, num) => {
            this.setState({
                visible: true,
            })
            if (record && num && num == "1") {
                let arr = []
                this.setState({
                    edit: num,
                    params: record,
                    id: record.ID,
                    rowMedID: record.medItemID
                })
            }
        }
        //获取医院下拉框
        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
                        })
                    }
                }
            })
        }
        handleCancel = () => {
            this.props.form.resetFields();
            this.setState({ visible: false, params: {}, edit: -1, id: "" });
        }
        //添加/编辑
        handleCreat = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    let data = {}
                    data = {
                        params: [{
                            updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                            ID: this.state.id && this.state.id ? this.state.id : "",//修改
                            hospID: values.hospID || "",
                            medItemID: this.state.medItemID,//医嘱项目
                            bedFeeTypeID: values.bedFeeTypeID || "",//费用类型	
                            createDate: values.createDate ? moment(values.createDate).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,//失效日期
                        }]
                    }
                    $http.post('urlS', this, {
                        code: '01040142',
                        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.ID);
                                }
                                this.setState({
                                    visible: false,
                                    edit: -1,
                                    params: {},
                                    id: ""
                                })
                                this.props.form.resetFields();
                            }
                        }
                    })
                }
            })
        }
        //选择医院清空费用项目
        handleHos = () => {
            this.setState({
                itemArr: [],
                rowMedID: ""
            }, () => {
                this.props.form.setFieldsValue({ medItemID: undefined, })
            })
        }
        //清空已选费用项目
        handleClear = (e) => {
            if (!e.target.value) {
                this.handleHos()
            }
        }
        //回车检索费用项目
        getItem = () => {
            if (!this.props.form.getFieldValue("hospID")) {
                message.warning("请先选择医院")
            } else {
                this.setState({
                    isShowCommonTableModal: true,
                    rowMedID: "",
                    searchTop: "search",
                    pageTop: 1
                }, () => {
                    this.loadSelectData()
                    this.childs.showModal();
                })
            }
        }
        loadSelectData = () => {
            let data = {
                params: [{
                    hospID: this.props.form.getFieldValue("hospID"), // 医院id
                    findCode: this.props.form.getFieldValue("medItemID")//医嘱项搜索名称
                }], pagination: [{
                    pageSize: this.state.pageSizeTop,
                    currentPage: this.state.pageTop,
                }]
            }
            $http.post('urlS', this, {
                code: "01010002",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            itemArr: res.result.Data, //  费用项目
                            rowMedID: res.result.Data ? res.result.Data[0].id : '',
                            totalTop: res.result.TotalCount
                        })
                    }
                }
            });
        }
        onRef = (ref) => {
            this.childs = ref;
        }
        setRowClassNamePublic = (record) => {
            return (record.id || record.id) === this.state.rowMedID ? 'clickRowStyle' : '';
        }
        onClickRowPublic = (record) => {
            // console.log("onClickRowPublic", record)
            return {
                onClick: () => {
                    this.setState({
                        rowMedID: record.id
                    })
                },
                onDoubleClick: () => {
                    this.rowClick(record)
                }
            }

        }
        //隐藏弹出框
        hideModal(name) {
            this.setState({
                [name]: false,//将所有参数置为false
            });
        }
        //分页切换
        changePageSize(current, pageSize) {
            this.setState({ pageSizeTop: pageSize, pageTop: current }, () => {
                this.loadSelectData();
            });
        }
        rowClick = (record) => {
            this.setState({
                rowMedID: record.id
            }, () => {
                this.props.form.setFieldsValue({ medItemID: record.descripts })
                this.childs.handleCancel();
            })
        }
        handleOnKeydown(e) {
            var e = window.event || e;
            let scroll_height = 50;
            let id = '';
            let oneArr = this.state.itemArr && this.state.itemArr.length > 0 ? this.state.itemArr : [];
            switch (e.keyCode) {
                case 13:
                    if (this.state.rowMedID) {
                        let obj = {}
                        for (var i = 0; i < oneArr.length; i++) {
                            if ((oneArr[i].id) === this.state.rowMedID) {
                                obj = i > 0 ? oneArr[i] : oneArr[0];
                                break;
                            }
                        }
                        this.rowClick(obj);
                    } else {

                    }
                    break;
                case 38: //上
                    if (this.state.rowMedID) {
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].id === this.state.rowMedID) {
                                id = i > 0 ? oneArr[i - 1].id : oneArr[0].id;
                                break;
                            }
                        }
                        this.setState({ rowMedID: id }, () => {
                            var orderItem = document.getElementById("orderItem");
                            orderItem.scrollTop = orderItem.scrollTop - scroll_height;
                        })
                    } else {
                        this.setState({ rowMedID: oneArr[0] ? oneArr[0].id : '' })
                    }
                    break;
                case 40: //下
                    if (this.state.rowMedID) {
                        for (let i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].id === this.state.rowMedID) {
                                id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].id
                                    : oneArr[i + 1].id;
                                break;
                            }
                        }
                        this.setState({ rowMedID: id }, () => {
                            var orderItem = document.getElementById("orderItem");
                            orderItem.scrollTop = orderItem.scrollTop + scroll_height;
                        })
                    } else {
                        this.setState({ rowMedID: oneArr[0] ? oneArr[0].id : '' })
                    }
                    break;
            }
        }

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

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

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



        render() {
            const { getFieldDecorator, } = this.props.form;
            const { params } = this.state
            //医院
            let hosOp = []
            this.state.hospArr && this.state.hospArr.map((item) => {
                hosOp.push(<Option key={item.id} onClick={this.handleHos} 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>)
            })
            let column = [{
                key: '1',
                title: '医嘱项代码',
                dataIndex: 'code',
                width: 100,
                align: "center",
            }, {
                key: '2',
                title: '医嘱项描述',
                dataIndex: 'descripts',
                width: 160,
                align: 'center'
            }]

            let param = {
                width: '103vh',
                // height: 300,
                top: "28%",
                left: "24%",
                columns: column,
                data: this.state.itemArr,
                isOnRow: true,
                TableClassName: 'tab-placeholder',
                rowClassName: true,
                showPagination: true,
                search: this.state.searchTop,
                page: this.state.pageTop,
                total: this.state.totalTop,
            }

            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 {...formLayoutItemType} label='医院'>
                                            {getFieldDecorator('hospID', {
                                                initialValue: params && params.hospID ? params.hospID : undefined,
                                                rules: [{ required: true, message: '请选择医院' }],
                                            })(
                                                <Select
                                                    onChange={this.handleHos}
                                                >
                                                    {hosOp}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={8} style={paddRightCol}>
                                        <FormItem {...formLayoutItemType} label='床位费类型'>
                                            {getFieldDecorator('bedFeeTypeID', {
                                                initialValue: params && params.bedFeeTypeID ? params.bedFeeTypeID : undefined,
                                                rules: [{ required: true, message: '请选择床位费类型' }],
                                            })(
                                                <Select
                                                >
                                                    {feeOp}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>

                                    <Col span={8} style={paddRightCol}>
                                        <FormItem {...formLayoutItemType} label='费用项目'>
                                            {getFieldDecorator('medItemID', {
                                                initialValue: params && params.medItemDescripts ? params.medItemDescripts : this.state.medItemID,
                                                rules: [{ required: true, message: '请输入检索费用项目' }],
                                            })(
                                                <AutoComplete placeholder="输入内容回车检索" onSearch={this.handleValue.bind(this, 'bedTypeID')}
                                                    onSelect={this.handleSelectOption.bind(this, 'medItemID')} allowClear
                                                    dataSource={ordNoteListtOption} />
                                            )}
                                        </FormItem>
                                    </Col>


                                    {/* <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 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.stopDate, "YYYY-MM-DD") : undefined,
                                                rules: [{ required: false, message: '' }],
                                            })(
                                                <DatePicker style={{ width: '100%' }} />
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </div>
                    </Modal>
                    <div className='doctor-advice-common-modal'
                        tabIndex={1}
                        onKeyDown={this.handleOnKeydown.bind(this)}
                        style={{ outline: 'none' }}
                    >
                        <ShowCommonTableModal
                            onClickRowPublic={this.onClickRowPublic}
                            setRowClassNamePublic={this.setRowClassNamePublic}
                            isShow={this.state.isShowCommonTableModal}
                            // handleFocus={this.handleFocus.bind(this)}
                            onHide={this.hideModal.bind(this, 'isShowCommonTableModal')}
                            param={param}
                            onRef={this.onRef}
                            search={this.state.search}
                            id="orderItem"
                            compilePage={this.changePageSize.bind(this)}
                        >
                        </ShowCommonTableModal></div>
                </div>
            )
        }
    })
export default BedCostTypeToMedModal