// 医疗分组
import React from 'react';
import { Row, Col, Table, Select, Button, message, Popconfirm, Tabs, Spin } from 'antd';
import store from '../../store';
import { $http } from '../../containers/config/https';
// 基本信息组件
import MedicalGroupModelNew from './MedicalGroupModelNew.jsx';
import MedGroupEntrance from './MedGroupEntrance.jsx';
import MedGroupUser from './MedGroupUser.jsx';
const Option = Select.Option
const TabPane = Tabs.TabPane;


export default class MedicalGroupMaintenanceNew extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userInfo: {},
            // 主菜单列表数据
            data: [],
            // 科室下拉框数据
            list: [],
            // 科室id
            locID: '',
            // 抽屉显示
            visible: false,
            // 代码
            code: '',
            // 描述
            describe: '',
            flag: '',
			title: '新增基本信息',
			// tab页签
			key: '1',
			// 选中行ID
			rowId: '',
			// 赋值数据给授权页面
			authorizationId: '',	
            // 主菜单分页数据
            total: 0,
            page: 1,
            pageSize: 10,
            // 是否显示loading
            showLoading: true,
            // 表格loading
            loading: true,

			// 选中的行数据
			rowData: []
        };

        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"
            },

        ];
    }

    // 设置为新增基本信息
    handleSetTitle = () => {
        this.setState({ title: '新增基本信息', rowData: [] })
    }

    // 查询
    handleQuery = () => {
        let { code, describe, page, pageSize } = this.state;
        let data = {}
        if (code || describe) {
            data = {
                params: [{
                    Code: code,
                    Descripts: describe
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                    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)
                }
            }
        })
    }

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

    // 复制
    handleAdd = () => {
        if (this.state.rowData.length >= 1) {
            this.child.resetFields()
            this.setState({ userInfo: this.state.rowData[0], flag: 'add', title: '新增基本信息', rowId: '', rowData: [], key: '1' })
        } else {
            message.info('请选择需要操作的数据');
        }
    }

    // 编辑
    handleCompile = () => {
        if (this.state.rowData.length >= 1) {
            this.child.resetFields();
            this.setState({ userInfo: this.state.rowData[0], flag: 'compile', title: '编辑基本信息', key: '1' });
        } else {
            message.info('请选择需要操作的数据');
        }
    }

    // 重置userInfo
    resetUserInfo() {
        this.setState({ userInfo: {},flag:'',title: '新增基本信息' })
    }

    // 删除
    handleDelete = () => {
        if (this.state.rowData.length >= 1) {
            let data = {
                params: [{
                    ID: this.state.rowData[0].ID,
                    UpdateUser: window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData).userId:''
                }]
            }
            $http.post('urlADS', this, {
                code: 'cs003',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success('删除成功');
                        // 刷新列表数据
                        this.handleQuery();
                        // 重置表单
                        this.resetUserInfo();
                        this.handleSetTitle()
                    }
                }
            })
        } else {
            message.info('请选择需要操作的数据');
        }
    }

    // 点击切换tabs的回调
    callback = (activeKey) => {
        // 当点击切换为菜单授权必须选中一条数据
        if (+activeKey === 2) {
            if (this.state.rowData.length >= 1) {
                this.setState({ key: '2' })
            } else {
                message.info('请选择需要操作的数据');
            }
        }else if(+activeKey === 3){
            if (this.state.rowData.length >= 1) {
                this.setState({ key: '3' })
            } else {
                message.info('请选择需要操作的数据');
            }
        }else {
            this.setState({ key: activeKey })
        }

    }

    // 设置行属性
    onClickRow = (record) => {
        return {
            // 单击行选中
            onClick: () => {
                if (this.state.rowId === '') {
                    // 保存行数据以及ID
                    this.setState({ rowData: [record], authorizationId: record.ID, rowId: record.ID })
                    
                } else {
                    this.setState({ rowData: [record], authorizationId: record.ID, rowId: record.ID })
                    
                    // if (this.state.rowId !== record.ID) {
                    // this.setState({rowData: [record], authorizationId: record.ID, rowId: record.ID})
                    // } else {
                    // 取消选中
                    // 	this.setState({rowData: [], authorizationId: '', rowId: '', title: '新增基本信息', flag: 'add'})
                    // 	this.resetUserInfo()
                    // }
                }
            },
            // 双击行编辑
            onDoubleClick: () => {
                this.dblclickRowCompile(record)
            },
        }
    }

    // 双击行编辑
    dblclickRowCompile = (record) => {
        setTimeout(() => {
            this.child.resetFields()
            this.setState({
                userInfo: record,
                flag: 'compile',
                rowId: record.ID,
                rowData: [record],
                title: '编辑基本信息',
                authorizationId: record.ID
            })
        }, 0)
    }
    // 查询条件科室描述
    handleChange = (val, opt) => {
        this.setState({
            locID: val,
            describe: opt.props.children
        }, () => {
            this.handleQuery();
        });

    }

    // 表格行的类名
    setRowClassName = (record) => {
        return record.ID === this.state.rowId ? 'clickRowStyle' : '';
    }

    componentDidMount() {
        this.handleQuery();
        this.handleLocQuery();
        // 数据异步请求，请求成功之后setState
        this.setState({
            showLoading: false
        })
    }

    render() {
        let rightWidth = document.getElementById('content-row') ? document.getElementById('content-row').clientWidth - 24 * 2 - 510 - 54 + 'px' : '';
        return (
            <Spin tip="加载中..." spinning={this.state.showLoading}>
                <div style={{ padding: 24 }} id="content-row">
                    <Row>
                        <Col style={{ width: '500px', float: 'left' }}>
                            <Row style={{ height: 102 }}>
                                <Col style={{ height: '50%', borderBottom: '1px solid #e8e8e8' }}>
                                    <Row style={{ height: '100%', lineHeight: '51px', borderRight: '1px solid #e8e8e8', }}>
                                        {/*名称：<Input placeholder="请输入" ref={input => this.input = input} style={{ width: '150px' }} onPressEnter={this.handleQuery} />*/}
                                        科室描述:
                                        <Select
                                            showSearch
                                            style={{ width: 250 }}
                                            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>
                                    </Row>
                                </Col>
                                <Col style={{ height: '50%' }}>
                                    <Row style={{ height: '100%', lineHeight: '51px', borderRight: '1px solid #e8e8e8' }}>
                                        <Button size="small" type="primary" onClick={this.handleQuery} style={{ marginRight: '10px' }}>查询</Button>
                                        {/*<Button size="small" type="ghost" onClick={this.handleAdd} style={{ marginRight: '10px' }}>复制</Button>*/}
                                        <Button size="small" type="dashed" onClick={this.handleCompile} style={{ marginRight: '10px' }}>编辑</Button>
                                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDelete} >
                                            <Button size="small" type="danger" style={{ marginRight: '10px' }}>删除</Button>
                                        </Popconfirm>
                                    </Row>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <Table
                                        rowClassName={this.setRowClassName}
                                        onRow={this.onClickRow}
                                        pagination={false}
                                        columns={this.columns}
                                        dataSource={this.state.data}
                                        scroll={{ x: 1300, y: store.getState().tableHeight.y + 40 }}
                                        bordered
                                        loading={this.state.loading}
                                    />
                                </Col>
                            </Row>
                        </Col>
                        <Col style={{ width: rightWidth, float: 'left', marginLeft: '20px' }}>
                            <Tabs activeKey={this.state.key} onChange={this.callback} type="card">
                                <TabPane tab={this.state.title} key="1" style={{ padding: '24px', height: store.getState().tableHeight.y + 130, overflow: 'auto' }}>
                                    <MedicalGroupModelNew userInfo={this.state.userInfo} onRef={this.onRef} handelThis={this} flag={this.state.flag} />
                                </TabPane>
                                <TabPane forceRender tab="分组人员维护" key="2" style={{ height: store.getState().tableHeight.y + 130, overflow: 'auto' }}>
                                    <MedGroupUser handelThis={this} />
                                </TabPane>
                                <TabPane tab="分组医嘱授权" key="3" style={{ height: store.getState().tableHeight.y + 130, overflow: 'auto' }}>
                                    <MedGroupEntrance handelThis={this} />
								</TabPane>
                            </Tabs>
                        </Col>
                    </Row>
                </div>
            </Spin>
        )
    }
}