/*
 * Creator:     ML
 * CreatDate:   2019-12-19
 * descripts：  床位费类型和费用项目关联
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Popconfirm, Modal, Table, Icon, Pagination, message, Divider, Tooltip } from 'antd';
import moment from 'moment';
import { $http } from '../../containers/config/https';
import store from '../../store';
import BedCostTypeToMedModal from './component/BedCostTypeToMedModal';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import ShowCommonTableModal from 'pages/workstation/component/ShowCommonTableModal'

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
}
const formItemLayoutType = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 }
}
const formItemLayoutFree = {
    labelCol: { span: 10 },
    wrapperCol: { span: 14 }
}
const BedCostTypeToMedItem = Form.create()(
    class BedCostTypeToMedItem extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                loading: false,
                visible: false,
                baseParms: [],//下拉框数据
                total: 0,//表格总数据
                bedData: [],//查询数据
                values: {},//查询条件数据
                searchLoading: false,//查询请求
                initCard: '',
                rowIds: '',//表格行选中 页面数据
                bindVail: true,//点击绑定前是否通过验证
                bindLoading: false,//点击绑定loading
                headerHeight: "",
                page: 1,
                pageSize: 10,
                size: "small",
                search: "",
                isShowCommonTableModal: false,
                pageSizeTop: 10,
                pageTop: 1
            }
        }
        componentDidMount() {
            // 初始化设置table的高度以及表体的高度
            document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 52 + 'px';
            let box = document.querySelector(".department-header");
            if (box) { //此处在加一层判断，更加严密，如果box存在的情况下获取
                this.setState({ headerHeight: box.offsetHeight })
            }
            this.getHopSelect()
            this.getFindDate()
            this.getMainTableColumns()
            this.getFeeType()
            this.getRoomType()
        }
        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "HBBedFeeTypeItem",
                    reactCode: ['HBBedFeeTypeItem'],
                    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,
                                // render: (text, record) => {
                                //    if (item.code == "status") {
                                //      return (
                                //      <span>{record.status=="Y"?"生效":"失效"}</span>
                                //      )
                                //    }
                                //    return text
                                //  }
                            }
                        }) : '';
                        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>
                                        <a onClick={(e) => this.toggleEditable(row, "1")}>编辑</a>
                                        <Divider type="vertical" />
                                        <Popconfirm title="是否要删除此行" onConfirm={() => this.toggleEditable(row, "2")}>
                                            <a style={{ color: "red" }} >删除</a>
                                        </Popconfirm>
                                    </span>
                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                        // console.log("res.totalWidth",res.totalWidth)
                    }
                }
            })
        }
        //获取医院下拉框
        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
                        })
                    }
                }
            })
        }
        //选择医院清空费用项目
        handleHos = () => {
            this.setState({
                itemArr: [],
                rowMedID: ""
            }, () => {
                this.props.form.setFieldsValue({ getItem: 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("getItem")//医嘱项搜索名称
                }], 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
                        })
                    }
                }
            });
        }
        // 修改page和pageSize 跳转至---
        onChange = (e, pageSize) => {
            this.setState({ page: e, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values);
            })
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values, "search");
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        //定位到最新添加/当前修改的记录
        getNewData = (id) => {
            //跳至最后一页 并定位到刚添加的这条记录
            if (id) {
                let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
                this.onChange(lastPage, this.state.pageSize)
                this.setState({
                    rowIds: id
                })
            } else {
                this.onChange(this.state.page, this.state.pageSize)
            }

        }
        //获取查询数据
        getFindDate = (values, e) => {
            if (this.state.total == 0) {
                this.setState({
                    searchLoading: true
                })
            }
            let { page, pageSize, } = this.state;
            let data = {}
            data = {
                params: [{
                    userID: JSON.parse(sessionStorage.userData).userID || '',
                    // logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                    hospID: values && values.hospId || "",
                    medItemID: this.state.rowMedID,
                    bedFeeTypeID: values && values.getBed || "",
                    startDate: values && values.dateFrom ? moment(values.dateFrom).format('YYYY-MM-DD') : undefined,//生效日期
                    stopDate: values && values.dateTo ? moment(values.dateTo).format('YYYY-MM-DD') : undefined,//失效日期
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '01040141',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({
                            searchLoading: false,
                            search: e
                        })
                        for (var i = 0; i < res.result.data.length; i++) {
                            res.result.data[i].key = i + 'bed'
                        }
                        this.setState({ bedData: res.result.data, total: res.result.TotalCount, }, () => {
                        })
                    } else {
                        this.setState({
                            searchLoading: false
                        })
                    }
                    //  if (res.result.data && res.result.data.length == 0 && res.result.totalCount > 0) {
                    //      let prevPage = this.state.page - 1
                    //      this.onChange(prevPage, this.state.pageSize)
                    //  }
                },
                error: function () {
                    this.setState({
                        searchLoading: false
                    })
                }
            })

        }
        //点击查询---
        findData = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    this.setState({
                        values: values,
                        rowIds: ""
                    }, () => {
                        this.onShowSizeChange("1", this.state.pageSize)
                    })
                }
            })
        }
        // 调用子组件的连接事件 -- 添加新
        OnChildrefs = (ref) => {
            this.child = ref
        }
        add = () => {
            this.child.showModal()
        }
        //点击查询后 表格行
        setRowClassNames = (record) => {
            return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
        }
        //点击Row
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.setState({
                        parms: record,
                    })
                    if (this.state.rowId === "") {
                        this.setState({
                            rowIds: record.ID,
                        });
                    } else {
                        if (this.state.rowId !== record.ID) {
                            this.setState({
                                rowIds: record.ID,
                            });
                        } else {
                            this.setState({
                                rowIds: "",
                                detailInfo: {},
                            });
                        }
                    }
                },
            };
        }
        //编辑 /删除 
        toggleEditable = (record, num) => {
            if (num == "1") {
                this.child.showModal(record, num)
            } else {
                let datas = {}
                datas = {
                    params: [{
                        updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                        ID: record.ID,
                    }],
                }
                $http.post('urlS', this, {
                    code: '01040143',
                    data: datas,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success("删除成功");
                            this.getFindDate()
                        }
                    }
                })
            }
        }
        //获取费用类别
        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
                        })
                    }
                }
            })
        }
        //获取房间类型
        getRoomType = () => {
            let data = {
                params: [{
                    roomTypeFlag: 1
                }],
            }
            $http.post('urlS', this, {
                code: '01040022',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            roomArr: res.roomType
                        })
                    }
                }
            })
        }
        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)
                }
            }

        }
        handleValue = () => {

        }
        //隐藏弹出框
        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({ getItem: 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;
            }
        }
        render() {
            const { getFieldDecorator } = this.props.form;
            const { searchLoading, columns } = this.state;
            const mesIcon = <Icon type="exclamation-circle" />
            //医院
            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 column = [{
                key: '1',
                title: '医嘱项代码',
                dataIndex: 'code',
                width: 100,
                align: "center",
            }, {
                key: '2',
                title: '医嘱项描述',
                dataIndex: 'descripts',
                width: 160,
                align: 'center'
            }]

            let param = {
                width: '96vh',
                // height: 300,
                top: "18%",
                left: "29%",
                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">
                    <div className="department-header">
                        <Form>
                            <Row gutter={60} style={{ margin: '0' }}>
                            <Col span={3} style={paddRightCol}>
                                    <FormItem {...formItemLayout} label='医院'>
                                        {getFieldDecorator('hospId', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                                onChange={this.handleHos}
                                            >
                                                {hosOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={6} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label='费用项目'>
                                        {getFieldDecorator('getItem', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Input placeholder="请确认选择医院后输入首拼回车检索项目" allowClear onChange={this.handleClear} onPressEnter={this.getItem}></Input>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={3} style={paddRightCol}>
                                    <FormItem {...formItemLayoutFree} label='床位费类别'>
                                        {getFieldDecorator('getBed', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                                onChange={this.findData}
                                            >
                                                {feeOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem label='生效日期' {...formItemLayout}>
                                        {getFieldDecorator('dateFrom', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                                return curDate && curDate > moment().endOf('day');
                                            }} />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem label='失效日期' {...formItemLayout}>
                                        {getFieldDecorator('dateTo', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <DatePicker style={{ width: '100%' }} />
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={{paddingLeft:"10px",paddingRight: "0px",width: "5%"}}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('posInp', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button onClick={this.findData} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>查询</Button>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={{ padding: "0px" }}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('addNewCard', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button onClick={this.add} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>+床位费类型关联费用项目</Button>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                            </Row>
                        </Form>
                    </div>
                    <div>
                        <Table
                            // scroll={{ x: 1160, y: store.getState().tableHeight.y + 156 }}
                            columns={columns}
                            dataSource={this.state.bedData}
                            pagination={false}
                            rowKey={record => record.key}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassNames}
                            bordered
                            style={{ height: store.getState().tableHeight.y + 106 + 'px' }}
                        />
                        <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.bedData}
                            onChange={this.onChange.bind(this)} />
                    </div>
                    <BedCostTypeToMedModal getNewData={this.getNewData} OnChildrefs={this.OnChildrefs}></BedCostTypeToMedModal>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='HBBedFeeTypeItem'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                     <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 BedCostTypeToMedItem    