// 挂号权限
import React from 'react';
import { Row, Col, Table, Select, Button, Pagination, message, Card, Popconfirm, Tabs, Spin } from 'antd';
import store from '../../store';
import { $http } from '../../containers/config/https';
import CommonPagination from 'components/pagination/index';

const Option = Select.Option

class RegRestrict extends React.Component {
    constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            total: 0,
            page:1,
            pageSize:20,
            size:"small",
            rowId: '',
            locID: '',
            groupID: '',
            descripts: '',
            // 角色下拉框数据
            groupList: [],
            // 科室下拉框数据
            locList: [],
            // 科室数据
            locData: [],
            // 科室医生数据
            docData: [],
            selectedRowKeys: [],
            loading: false,
            userData:userData
        };
        this.locColumns = [
            {
                title: '科室代码',
                dataIndex: 'code',
                width: 50,
                align: "center"
            },
            {
                title: '科室描述',
                dataIndex: 'descripts',
                width: 80,
                align: "center"
            },
            {
                title: '英文描述',
                dataIndex: 'enDescripts',
                width: 80,
                align: "center"
            },
        ];
        this.docColumns = [
            {
                title: '工号',
                dataIndex: 'code',
                width: 60,
                align: "center"
            },
            {
                title: '姓名',
                dataIndex: 'descripts',
                width: 100,
                align: "center"
            },
            {
                title: '职称',
                dataIndex: 'title',
                width: 100,
                align: "center"
            },
        ];
    }

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

    // 科室table点击事件
    onLocClickRow = (record) => {
        
        return {
            // 单击行选中
            onClick: () => {
                // 保存行ID
                this.setState({
                    rowId: record.id,
                    locID: record.id
                }, () => {
                    this.handleDocQuery();
                })

            },

        }
    }

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

    onSelectChange = (selectedRowKeys) => {
        this.setState({ selectedRowKeys });
    }


    // 角色查询
    handleGroupQuery = () => {
        let data = {}

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

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

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

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

    // 科室医生查询
    handleDocQuery = () => {
        let { locID, groupID } = this.state;
        if (groupID) {
            let data = {
                params: [{
                    groupID: groupID,
                    locID: locID
                }]
            }
            $http.post('urlS', this, {
                code: '03020049',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.depDoctor) {
                        let tempList = []
                        for (var i = 0; i < res.depDoctor.length; i++) {
                            res.depDoctor[i].key = res.depDoctor[i].id;
                            if (res.depDoctor[i].HBRRRowId) tempList.push(res.depDoctor[i].id)
                        }
                        this.setState({ docData: res.depDoctor, loading: false, selectedRowKeys: tempList })

                    } else {
                        setTimeout(() => {
                            this.setState({ docData: [], total: 0, loading: false })
                        }, 1000)
                    }
                }
            })
        }
        else { message.info('请选择角色'); }

    }

    handleQuery = () => {
        let { descripts, page, pageSize } = this.state;
        let data = {
            params: [{
                hospID: this.state.userData.hospID,
                descripts: descripts
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Code",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: '03020046',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result.Data) {
                    for (var i = 0; i < res.result.Data.length; i++) {
                        res.result.Data[i].key = i
                    }
                    this.setState({ locData: res.result.Data, total: res.result.TotalCount, loading: false })

                } else {
                    setTimeout(() => {
                        this.setState({ locData: [], total: 0, loading: false })
                    }, 1000)
                }
            }
        })
    }

    handleLocFind = () => {
        this.setState({
            descripts:this.refs.locInput.value
        },()=>{
            this.handleQuery();
        })
    }

    locInputKeyUp = (e) => {
        if (e.keyCode===13) this.handleLocFind();
    }

    handleGroupChange = (val) => {
        this.setState({
            groupID: val,
        });
    }

    handleSave = () => {
        let docData = this.state.docData;
        let selectedRowKeys = this.state.selectedRowKeys;
        let addList = [];
        let deleteList = [];
        for (var i = 0; i < docData.length; i++) {
            let flag = 0
            for (var j = 0; j < selectedRowKeys.length; j++) {
                if (docData[i].id === selectedRowKeys[j]) {
                    flag = 1;
                    if (docData[i].HBRRRowId === '') {
                        let addObj = {}
                        addObj.groupID = this.state.groupID;
                        addObj.locID = this.state.locID;
                        addObj.docID = selectedRowKeys[j]
                        addList.push(addObj);
                    }
                }
            }
            if (flag === 0 && docData[i].HBRRRowId) {
                let deleteObj = {};
                deleteObj.ID = docData[i].HBRRRowId;
                deleteList.push(deleteObj);
            }
        }
        if (addList.length === 0 && deleteList.length === 0) { message.info('没有需要保存的数据！'); }
        if (addList.length > 0) { this.handleFunction('03010001', addList);}
        if (deleteList.length > 0) { this.handleFunction('03010002', deleteList);}
    }
    handleFunction(code, list) {
        let data = {
            params: list
        }
        $http.post('urlADS', this, {
            code: code,
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    // 提示
                    message.success('保存成功');
                    this.handleDocQuery();
                }
            },
            error: function (error) {
                message.error('保存失败：' + error);
                this.handleDocQuery();
            }
        })
    }

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


    render() {
        const { selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        return (
            <div>
                <div style={{ padding: 24 }} id="content-row">
                    <Row >
                        <Card >
                            角色:
                            <Select
                                showSearch
                                style={{ width: 250 }}
                                placeholder="请选择角色"
                                optionfilterprop="children"
                                onChange={this.handleGroupChange}
                                /*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.groupList}
                            </Select>
                            
                            <Button type="primary" onClick={this.handleSave} style={{ margin: '0px 0px 0px 50px' }}>保存</Button>
                        </Card>
                    </Row>
                    <Row >
                        <Col style={{ width: '39%', float: 'left' }}>
                            <Card > 
                                科室:
                                <input
                                    style={{ width: 250 }}
                                    placeholder="请输入科室名称"
                                    optionfilterprop="children"
                                    ref="locInput"
                                    onKeyUp={this.locInputKeyUp}
                                >
                                </input>
                                <Button onClick={this.handleLocFind}>查询</Button>
                                <Table
                                    scroll={{y: store.getState().tableHeight.y - 50 }}
                                    rowClassName={this.setRowClassName}
                                    onRow={this.onLocClickRow}
                                    style={{ height: store.getState().tableHeight.y +  'px' }}
                                    dataSource={this.state.locData}
                                    columns={this.locColumns}
                                    pagination={false}
                                    rowKey="id"
                                    bordered
                                    loading={this.state.loading}
                                />
                                <CommonPagination 
                                    size={this.state.size} current={this.state.page} pageSize={this.state.pageSize} total={this.state.total} search={this.state.search}
                                    onShowSizeChange={this.changePageSize.bind(this)} complete={true} dataSource={this.state.locData}
                                    onChange={this.onChange.bind(this)}
                                />
                             </ Card>

                        </Col>
                        <Col style={{ width: '61%', float: 'left' }}>
                            <Card >
                                <span style={{ marginLeft: 8 ,color: '#4169E1'}}>
                                    {hasSelected ? `共选中 ${selectedRowKeys.length} 条数据` : ''}
                                </span>
                                <Table rowSelection={rowSelection} columns={this.docColumns} dataSource={this.state.docData} style={{ height: store.getState().tableHeight.y +40+  'px',margin: '10px 0px 0px 0px' }}></Table>
                            </Card>
                        </Col>
                    </Row>
                </div>
            </div>
        );
    }
}

export default RegRestrict;