// 医疗分组维护
import React from 'react';
import '../../assets/css/system.css';
import store from '../../store';
import {
    Table, Input, Popconfirm, Row, Col, Button, Pagination, message, Divider, Spin, Select
} from 'antd';
import { $http } from '../../containers/config/https';
// 增删改弹框
import MedicalGroupModel from './MedicalGroupModel.jsx';

const Option = Select.Option

export default class EditableTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userInfo: {},
            // 主菜单列表数据
            data: [],
            // 科室下拉框数据
            list: [],
            // 科室id
            locID: '',
            // 抽屉显示
            visible: false,
            // 代码
            code: '',
            // 描述
            describe: '',
            // 主菜单分页数据
            total: 0,
            page: 1,
            pageSize: 10,
            flag: '',
            title: '',
            // 是否显示loading
            showLoading: true,
            // 表格loading
            loading: true
        };

        this.columns = [
            {
                title: '代码',
                dataIndex: 'Code',
                width: 60,
                align: "center"
            },
            {
                title: '描述',
                dataIndex: 'Descripts',
                width: 200,
                align: "center"
            },
            {
                title: '英文描述',
                dataIndex: 'ENDesc',
                width: 200,
                align: "center"
            },
            {
                title: '开始日期',
                dataIndex: 'StartDate',
                width: 200,
                align: "center"
            },
            {
                title: '失效日期',
                dataIndex: 'StopDate',
                width: 200,
                align: "center"
            },
            {
                title: '显示名称',
                dataIndex: 'ShowDesc',
                width: 80,
                align: "center",
                render(ShowDesc){
                    let config = {
                        'Y': '是',
                        'N': '否'
                    }
                    return config[ShowDesc];
                }
            },
            {
                title: '门诊标志',
                dataIndex: 'OPFlag',
                width: 80,
                align: "center",
                render(OPFlag){
                    let config = {
                        'Y': '是',
                        'N': '否'
                    }
                    return config[OPFlag];
                }
            },
            {
                title: '住院标志',
                dataIndex: 'IPFlag',
                width: 80,
                align: "center",
                render(IPFlag){
                    let config = {
                        'Y': '是',
                        'N': '否'
                    }
                    return config[IPFlag];
                }
            },
            {
                title: '更新日期',
                dataIndex: 'UpdateDate',
                width: 200,
                align: "center"
            },
            {
                title: '更新人',
                dataIndex: 'UpdateUserDesc',
                width: 200,
                align: "center"
            },
            {
                title: '操作',
                dataIndex: 'operation',
                align: "center",
                width: 100,
                render: (text, record) => (
                    <span>
                        <span className='span' onClick={this.handleCompile.bind(this, record)}>修改</span>
                        {/* onConfirm-- 点击确认的回调*/}
                        {/* 分割线 */}
                        <Divider type="vertical" />
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDetele.bind(this, record)} >
                            <span className='span'>删除</span>
                        </Popconfirm>
                    </span>
                )
            },
        ];
    }

    // 新增
    handleAdd = () => {
        if (this.state.locID) {
            // 显示弹框
            this.child.showModal()
            // 初始化数据
            this.setState({ flag: 'add', title: '新增'})
        }else  {message.error('请先选择科室');}

    }

    // 查询
    handleQuery = () => {
        let { code, page, describe, pageSize } = this.state;
        let data = {};
        if (code || describe) {
            data = {
                params: [{
                    Code: code,
                    Descripts: describe
                }],
                pagination: [{
                    pageSize: 10,
                    currentPage: 1,
                    sortColumn: "Code",
                    sortOrder: "asc"
                }]
            }
        } else {
            data = {
                params: [{
                    Code: code,
                    Descripts: describe
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: "Code",
                    sortOrder: "asc"
                }]
            }
        }
        // console.log(data);
        $http.post('urlS', this, {
            code: 'cs001',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    for (var i = 0; i < res.result.Data.length; i++) {
                        res.result.Data[i].key = i
                    }
                    this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false })
                    //console.log(res.result.Data)
                } else {
                    setTimeout(() => {
                        this.setState({ data: [], total: 0, loading: false })
                    }, 1000)
                }
            }
        })
    }
    // 科室查询
    handleLocQuery = () => {
        let data = {}

        data = {
            params: [{
                hospID: '',
                descripts: ''
            }]
        }
        $http.post('urlS', this, {
            code: '1008',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.hbLoc) {
                    let tempList = this.state.list
                    // console.log(res)
                    for (var i = 0; i < res.hbLoc.length; i++) {
                        tempList.push(<Option key={res.hbLoc[i].id} alias={res.hbLoc[i].descspell}>{res.hbLoc[i].descripts}</Option>)
                    }
                    this.setState({
                        list: tempList
                    })

                    //console.log(tempList)
                } else {
                    setTimeout(() => {
                        this.setState({ list: [] })
                    }, 1000)
                }
            }
        })
    }

    // 编辑
    handleCompile(record) {
        // console.log(record)
        // 重置form表单
        this.child.resetFields()
        // 打开弹框
        this.child.showModal();
        // 初始化数据
        this.setState({ flag: 'compile', userInfo: record, title: '编辑' });
    }

    // 删除
    handleDetele(record) {
        let data = {
            params: [{
                ID: record.ID
            }]
        }
        console.log(data)
        $http.post('urlADS', this, {
            code: 'cs003',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('删除成功');
                    // 刷新列表数据
                    this.handleQuery()
                } else {
                    message.error('删除失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('删除失败：' + error);
            }
        })
    }

    // 查询条件 --- 代码
    onChangeCode = (e) => {
        this.setState({ code: e.target.value });
    }

    // 查询条件 --- 描述
    onChangeDescribe = (e) => {
        this.setState({ describe: e.target.value });
    }
    // 查询条件科室描述
    handleChange = (val, opt) => {
        this.setState({
            locID: val,
            describe: opt.props.children
        }, () => {
            this.handleQuery();
        });

    }

    // 页码改变的回调，参数是改变后的页码及每页条数
    onChange = (page, pageSize) => {
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 重置userInfo
    resetUserInfo() {
        this.setState({ userInfo: {} })
    }

    componentDidMount() {
        // 初始化科室下拉框数据
        this.handleLocQuery();
        // 初始化列表数据
        this.handleQuery();
        // 初始化设置table的高度以及表体的高度
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
        // 数据异步请求，请求成功之后setState
        this.setState({
            showLoading: false
        })
    }

    render() {
        return (
            <Spin tip="加载中..." spinning={this.state.showLoading}>
                <div>
                    <div style={{ padding: 24, marginBottom: 24 }}>
                        <div className="table-operations" style={{ marginBottom: '30px' }}>
                            <Row>
                                <Col span={24}>

                                    科室描述:
                                    <Select
                                        showSearch
                                        style={{ width: 200 }}
                                        placeholder="请选择科室"
                                        optionFilterProp="children"
                                        onChange={this.handleChange}
                                        /*onFocus={handleFocus}
                                        onBlur={handleBlur}*/
                                        filterOption={(input, option) =>
                                            (option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0)||(option.props.alias.toLowerCase().indexOf(input.toLowerCase()) >= 0)
                                        }
                                    >
                                        {this.state.list}

                                    </Select>

                                    <Button type="primary" className="margiRight16" onClick={this.handleQuery}>查询</Button>
                                    <Button type="primary" onClick={this.handleAdd}>新增</Button>
                                </Col>
                            </Row>
                        </div>
                        <div>
                            <Table
                                style={{ height: store.getState().tableHeight.y + 45 + 'px' }}
                                dataSource={this.state.data}
                                columns={this.columns}
                                rowClassName="editable-row"
                                pagination={false}
                                scroll={{ x: 1300, y: store.getState().tableHeight.y }}
                                bordered
                                loading={this.state.loading}
                            />
                            {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                            <Pagination
                                size="small"
                                showQuickJumper
                                showSizeChanger
                                defaultCurrent={1}
                                total={this.state.total}
                                onChange={this.onChange}
                                onShowSizeChange={this.onShowSizeChange}
                                style={{ textAlign: "right", marginTop: '13px' }}
                            />
                        </div>
                    </div>

                    {/* 新增弹框*/}
                    <MedicalGroupModel
                        onRef={this.onRef}
                        userInfo={this.state.userInfo}
                        flag={this.state.flag}
                        handelThis={this}
                        title={this.state.title}
                    />
                </div>
            </Spin>
        );
    }
}
