/*
 * Creator:     ML
 * CreatDate:   2019-12-13
 * descripts：  医院关联床位费
 * */
import React from 'react';
import { Form, Row, Col, Select, Button, Popconfirm, Table, message, Divider } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';
import BedToHosModal from './component/BedToHosModal';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: '0px'
}
const formItemLayoutType = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 }
}

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

const BedToHospital = Form.create()(
    class BedToHospital extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                total: 0,//表格总数据
                bedData: [],//查询数据
                values: {},//查询条件数据
                searchLoading: false,//查询请求
                rowIds: '',//表格行选中 页面数据
                headerHeight: '',
                page: 1,
                pageSize: 10,
                size: 'small',
                search: '',
                totalWidth: 0
            }
        }

        componentDidMount() {
            let box = document.querySelector('.department-header');
            if (box) { //此处在加一层判断，更加严密，如果box存在的情况下获取
                this.setState({ headerHeight: box.offsetHeight })
            }
            this.getHopSelect()
            this.getFindDate()
            this.getMainTableColumns()
        }

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

        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: 'HospitalAssociatedBedFee',
                    reactCode: ['HospitalAssociatedBedFee'],
                    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: '130px',
                            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, 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
                        })
                    }
                }
            })
        }

        // 修改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 || '',
                    logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                    logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                    ID: values && values.getHop || '',
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '01040008',
                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
                        })
                    }
                },
                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: '01040007',
                    data: datas,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success("删除成功");
                            this.getFindDate()
                        }
                    }
                })
            }
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            const { searchLoading, columns, totalWidth } = this.state;
            //医院
            let hosOp = []
            this.state.hospArr && this.state.hospArr.map((item) => {
                hosOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
            })

            return (
                <div style={{ padding: '12px 24px' }} className="bedDom">
                    <div className="department-header">
                        <Form>
                            <Row gutter={60} style={{ margin: '0' }}>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label="医院">
                                        {getFieldDecorator('getHop', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                allowClear
                                            >
                                                {hosOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={paddRightCol}>
                                    <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>
                        </Form>
                    </div>
                    <div className="table-body-height">
                        <Table
                            scroll={{ x: totalWidth, y: store.getState().tableHeight.y + 26 }}
                            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 + 76 + '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>
                    <BedToHosModal getNewData={this.getNewData} OnChildrefs={this.OnChildrefs} prioritySelectData={this.props.prioritySelectData}></BedToHosModal>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='HospitalAssociatedBedFee'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                </div>

            )
        }
    })
export default BedToHospital    