/*
 * Creator:     ML
 * CreatDate:   2019-12-18
 * descripts：  床位关联床位费添加/编辑
 * */
import React from 'react';
import { Form, Input, Select, Button, message, Row, Popconfirm, DatePicker, Table, Col, TimePicker } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import store from 'store';
import DecoctingOrderModal from '../../orderdiatemplet/component/DecoctingOrderModal'
import CommonPagination from 'components/pagination';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

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

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

class BedCostToBedDetails extends React.Component {
    constructor() {
        super();
        this.state = {
            info: {},
            size: 'small',
            search: '',
            page: 1,
            pageSize: 10,
            totalWidth: 0
        };
    }

    componentDidMount() {
        this.props.onAttRef(this)
        this.getMainTableColumns()
        this.getFeeType()
    }

    onRef = (ref) => {
        this.onChildRef = ref
    }

    ondiaRef = (ref) => {
        this.onChilddiaRef = ref
    }

    searchICD = (e) => {
        this.onChildRef.showModal(e.target.value)
    }

    searchdiaICD = (e) => {
        this.onChilddiaRef.showModal(e.target.value)
    }

    changeICD = (e) => {
        if (e && e.target.value.length == 0) {
            this.setState({
                ICD: ''
            })
        }
    }

    changediaICD = (e) => {
        if (e && e.target.value.length == 0) {
            this.setState({
                diaID: ''
            })
        }
    }

    handleParms = (data) => {
        this.setState({
            ICD: data.id,
        })
        this.props.form.setFieldsValue({ ICDID: data.descripts, })
    }

    handlediaParms = (data) => {
        this.setState({
            diaID: data.id
        })
        this.props.form.setFieldsValue({ diaICDID: data.descripts })
    }

    handleClear = () => {
        if (this.state.ICD && this.state.ICD) {
            this.setState({
                // ICD,
            })
        } else {
            this.setState({ ICD: '' })
            this.props.form.setFieldsValue({ ICDID: undefined })
        }
    }

    handlediaClear = () => {
        if (this.state.diaID && this.state.diaID) {
            this.setState({
                // diaID,
            })
        } else {
            this.setState({ diaID: '' })
            this.props.form.setFieldsValue({ diaICDID: undefined })
        }
    }

    getInfo = (info) => {
        this.getDetail(info)
        this.setState({
            info,
            //   ICD:info.nationDiaID,
            //   diaID:info.diaID
        })
    }

    //获取费用类别
    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
                    })
                }
            }
        })
    }

    //获取详细信息
    getDetail = (info) => {
        // debugger
        const { pageSize, page } = this.state
        this.setState({
            info: info,
            CBBedId: info.bedID,
            hBBedId: info.ID
        })
        let data = {
            params: [{
                hBBedID: info.ID,
                CBBedId: info.bedID,
            }],
            pagination: [{
                pageSize: parseInt(pageSize),
                currentPage: parseInt(page),
            }]
        }
        $http.post('urlS', this, {
            code: '01040139',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        tableData: res.result.data,
                        total: res.result.TotalCount,
                        rowIds: '',
                        params: {}
                    })
                }
            }
        })
    }

    //清空数据
    initDeatail = () => {
        this.clearInfo()
        this.setState({
            rowIds: '',
            hBBedId: '',
            CBBedId: '',
            info: {},
            tableData: [],
            total: 0,
            page: 1,
        })
    }

    clearInfo = () => {
        this.props.form.resetFields();
        this.setState({
            params: {},
        })
    }

    handleSave = () => {
        const { params, ICD, diaID, info } = this.state
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = {
                    params: [{
                        ID: params && params.ID ? params.ID : '',
                        hBBedID: this.state.hBBedId,
                        cBMedItemID: this.state.medItemID,
                        updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                        qty: values.qty || '',
                        feeTypeID: values.feeTypeID || '',
                        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, // 失效日期
                        billTime: values.billTime ? moment(values.billTime).format('HH:mm') : '', // 计费时间
                    }]
                }
                $http.post('urlS', this, {
                    code: '01040138',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            if (params && params.id) {
                                message.success('更新成功')
                                this.getDetail(info)
                                this.clearInfo()
                            } else {
                                message.success('添加成功')
                                let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
                                this.setState({
                                    page: lastPage,
                                }, () => {
                                    this.getDetail(info)
                                    this.clearInfo()
                                })

                            }
                        }
                    }
                })

            }
        })
    }

    del = (row) => {
        let data = {
            params: [{
                ID: row && row.ID ? row.ID : '',
                updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ''
            }]
        }
        $http.post('urlS', this, {
            code: '01040137',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('删除成功')
                    this.getDetail(this.state.info)
                    this.clearInfo()
                }
            }
        })
    }

    //动态表头
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: 'BedRelatedBedFee',
                reactCode: ['BedRelatedBedFee'],
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo,
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    let seqArr = {
                        align: 'center',
                        widthNum: 140,
                        width: '50px',
                        code: 'edit',
                        dataIndex: 'edit',
                        title: '操作',
                        display: 'Y',
                        render: (value, row, index) => {
                            return (
                                <span>
                                    <Popconfirm title="是否要删除此行" onConfirm={() => this.del(row)}>
                                        <a style={{ color: 'red' }} >删除</a>
                                    </Popconfirm>
                                </span>
                            )
                        },
                    }
                    filterArr.push(seqArr)
                    this.setState({ columns: filterArr, totalWidth: res.totalWidth })
                }
            }
        })
    }

    //子组件 搜索医嘱项
    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.getTableData()
        })
    }

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

    getTableData() {
        let data = {}
        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({ dataSource: res.result })
                }
            }
        })
    }

    // 修改page和pageSize 跳转至---
    onChange = (e) => {
        this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
            // 重新调用查询方法
            let { values, info } = this.state;
            this.getDetail(info);
        })
    }

    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
        // console.log('page',page,'pagesize',pageSize)
        this.setState({ page: 1, pageSize: pageSize, search: 'search' }, () => {
            // 重新调用查询方法
            let { values, info } = this.state;
            this.getDetail(info);
        })
    }

    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }

    //点击Row
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    parms: record,
                })
                if (this.state.rowIds === '') {
                    this.setState({
                        rowIds: record.ID,
                        params: record
                    })
                } else {
                    if (this.state.rowIds !== record.ID) {
                        this.setState({
                            rowIds: record.ID,
                            params: record
                        });
                    } else {
                        this.setState({
                            rowIds: '',
                            params: {}
                        });
                        this.props.form.resetFields()
                    }
                }
            },
        };
    }

    //点击查询后 表格行
    setRowClassNames = (record) => {
        return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
    }

    render() {
        const { prioritySelectData } = this.props;
        const { getFieldDecorator } = this.props.form;
        const { params, columns, totalWidth } = this.state

        let ordNoteListtOption = []
        this.state.dataSource && this.state.dataSource.map((item, index) => {
            ordNoteListtOption.push(<Option key={index} value={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>)
        })

        return (
            <div className="department-header">
                <Form>
                    <Row gutter={60} style={{ margin: '0' }}>

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

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

                        <Col span={6} style={paddRightCol}>
                            <FormItem label='费用数量' {...formItemLayout}>
                                {getFieldDecorator('qty', {
                                    initialValue: params && params && params.qty ? params.qty : undefined,
                                    rules: [{ required: true, message: '请输入数量' }],
                                    getValueFromEvent: (event) => {
                                        return event.target.value.replace(/\D/g, '')
                                    },
                                })(
                                    <Input allowClear />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6} style={paddRightCol}>
                            <FormItem label='创建日期' {...formItemLayout}>
                                {getFieldDecorator('createDate', {
                                    initialValue: params && 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={6} style={paddRightCol}>
                            <FormItem label='生效日期' {...formItemLayout}>
                                {getFieldDecorator('dateFrom', {
                                    initialValue: params && 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={6} style={paddRightCol}>
                            <FormItem label='失效日期' {...formItemLayout}>
                                {getFieldDecorator('dateTo', {
                                    initialValue: params && params.StopDate ? moment(params.StopDated, "YYYY-MM-DD") : undefined,
                                    rules: [{ required: false, message: '' }],
                                })(
                                    <DatePicker style={{ width: '100%' }} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={6} style={paddRightCol}>
                            <FormItem label='指定天开始' {...formItemLayout}>
                                {getFieldDecorator('startDay', {
                                    initialValue: params && 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={6} style={paddRightCol}>
                            <FormItem label='指定天结束' {...formItemLayout}>
                                {getFieldDecorator('stopDay', {
                                    initialValue: params && params.stopDay ? moment(params.stopDay, "YYYY-MM-DD") : undefined,
                                    rules: [{ required: false, message: '' }],
                                })(
                                    <DatePicker style={{ width: '100%' }}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6} 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={6} style={paddRightCol}>
                            <FormItem label="计费时间" {...formItemLayout}>
                                {getFieldDecorator('billTime', {
                                    initialValue: params && 'billTime' in params && params.billTime ? moment(params.billTime, 'HH:mm') : undefined,
                                })(
                                    <TimePicker format="HH:mm" style={{ width: '100%' }} />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <Button key="submitc" type="primary" disabled={this.state.CBBedId == ''} onClick={this.clearInfo} style={{ margin: '0 8px' }}>清空</Button>
                            <Button key="submits" type="primary" disabled={this.state.CBBedId == ''} onClick={this.handleSave}>保存</Button>
                        </Col>
                    </Row>
                </Form>
                <DecoctingOrderModal OnChildrefs={this.OnChildrefs} handleParms={this.handleParms}></DecoctingOrderModal>
                <div className="table-body-height">
                    <Table
                        columns={columns}
                        dataSource={this.state.tableData}
                        pagination={false}
                        rowKey={record => record.key}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassNames}
                        bordered
                        scroll={{ x: totalWidth, y: store.getState().tableHeight.y - 160 }}
                        style={{ height: store.getState().tableHeight.y - 110 + 'px', overflow: "auto" }}
                    />
                </div>
                <CommonPagination size={this.state.size} page={this.state.page} current={this.state.page} total={this.state.total} search={this.state.search}
                    onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                    onChange={this.onChange.bind(this)} />
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='BedRelatedBedFee'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const BedCostToBedDetail = Form.create()(BedCostToBedDetails);
export default BedCostToBedDetail

