//科室岗位设置
import React from 'react';
import '../../assets/css/system.css';
import store from '../../store';
import {
    Select,Table, Input, Popconfirm, Row, Col, Button, Pagination, message, Divider, Icon,Modal
  } from 'antd';
import { $http } from '../../containers/config/https';
import DepartmentSettingAdd from './DepartmentSettingAdd.jsx'

const { Option } = Select;

let user;

export default  class DepartmentSetting extends React.Component {
    constructor({history}) {
        super();
        this.history = history;
        this.state = {
            // 医院名称
            hospitalId: undefined,
            // 科室名称
            locDesc: undefined,
            DepartmentInformation: [], // 科室名称下拉框
            // 主菜单列表数据
            selectData: {}, // 科室信息下拉框数据
            data: [],//岗位表格数据
            datasource1:[],//表格数据
            loading: true,
            // 主菜单分页数据
            total: 0,
            page: 1,
            pageSize: 10,
            flag: '',
            title: '',
            hospitalData: [], // 医院
            // 是否显示loading
            showLoading: true,
            visible: false
            
        };
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.columns = [
            {
                title: '医院', 
                dataIndex: 'HospDescripts',
                width: '20%',
                align: "center"
            },
            {
                title: '科室',
                dataIndex: 'LocDescripts',
                width: '20%',
                align: "center"
            },
            {
                title: '岗位代码',
                width: '20%',
                dataIndex: 'PostCode',
                align: "center"
            },
            {
                title: '岗位名称',
                dataIndex: 'PostDescripts',
                width: '20%',
                align: "center"
            },
            {
                title: '操作',
                dataIndex: 'operation',
                align: "center",
                width: 130,
                render: (text,record) => (
                    <span>
                         <span className='span'  onClick={this.showModal.bind(this, record.PostDr)}>查看</span> 
                        {/* onConfirm-- 点击确认的回调*/}
                        {/* 分割线 */}
                        <Divider type="vertical" />
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                        <span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
                        </Popconfirm>
                    </span>
                )
            },
        ];
    }
   
    componentDidMount() {
        // 初始化设置table的高度以及表体的高度
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
        // 初始化下拉框数据
        // this.getSelectData();
         // 初始化列表数据
         this.handleQuery();
         this.loadHospitalMsg();
        // 组件加载完毕关闭loading
        this.setState({showLoading: false});
        
    }
    
    onFocusLocDesc = () => {
		if (this.state.hospitalId === undefined) {
			message.info("请先选择医院");
		}
	}

	// 查询条件 --- 医院
	onChangehospitalId = (e) => {
		// console.log(e.target.value)
		this.setState({ hospitalId: e, locDesc: undefined }, () => {
			this.getDepartmentInformation(e)
		});
	}

    
    	//获取所属医院
	loadHospitalMsg() {
		var data = {
			params: [{
				hospID: '', // 医院id
				logonGroupID: user.groupID, //登录角色id
				logonHospID: user.hospID, // 登录医院id
			}]
		}
		$http.post('urlS', this, {
			code: "01040001",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						hospitalData: res.depDoctor,
						// hospitalId: res.depDoctor ? res.depDoctor[0].id : undefined
					})
					var result = res.depDoctor && res.depDoctor.some(item => {
						if (item.id === user.hospID) {
								return true
						}
					})
					if (!result) {
						this.setState({
								hospitalId: undefined
						})
					} else {
						this.setState({hospitalId: user.hospID ? user.hospID : undefined})
						this.getDepartmentInformation(user.hospID)
					}
				}
			}
		});
	}

 	// 3.13.23.获取科室信息
     getDepartmentInformation(id) {
		if (id) {
			let data = {
				params: [
					{ hospID: id}
				]
			}
			$http.post('urlS', this, {
				code: "04020008",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ DepartmentInformation: res.result.Data})
					} else {
						this.setState({ DepartmentInformation: [] })
					}
				}
			})
		} else {
			this.setState({ DepartmentInformation: [] })
		}
	}

 
	// 查询条件 --- 科室名称
	onChangeLocDesc = (e) => {
       // console.log(e)
		this.setState({ locDesc: e });
	}
    	// 查询
	handleQuery = () => {
		this.setState({page: 1, pageSize: 10}, () => {
           // let {hospitalDr, locDesc} = this.state;
			//let { HospDescripts,locDesc} = this.state;
		    this.getTableData()
		})
    }
    
    showModal = (PostDr) => {
        let data = {
            params: [{
                postID: PostDr,
            }]
        }
        $http.post('urlS', this, {
            code: "01050010",
            data: data,
            success:  (res)=> {
                if (+res.errorCode === 0) {
                  this.setState({ datasource1: res.result})
                    
                } else {
                    message.error('查询失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error("查询失败：" + error);
            }
        })
 
        this.setState({
          visible: true,
        });
      }
    
      handleOk = (e) => {
        //console.log(e);
        this.setState({
          visible: false,
        });
      }
    
      handleCancel = (e) => {
        //console.log(e);
        this.setState({
          visible: false,
        });
      }
 
    //科室岗位关联查询
         getTableData = () => { 
            // debugger;
              //console.log(0,0)
                const { hospitalId, locDesc } = this.state;
               // console.log(hospitalDr,locDesc )
                let {page, pageSize} = this.state;
                let data = {
                    params: [{
                        hospID: hospitalId,//医院ID
                        locID: locDesc  //科室ID
                    }],
                    pagination:[{ 
                        pageSize: pageSize,
                        currentPage: page,
                    }]
                }
               // console.log(this.state)
                $http.post('urlS', this, {
                    code: "01050006",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false})
                        } else {
                            message.error('查询失败：' + res.errorMessage);
                        }
                    }
                })
            }
    // 删除
    handleDelete = (record) => {
        let data = {
            params: [{
                locLinkPostID: record.ID,
                updateUserID:user.userID
            }]
        }
        $http.post('urlADS', this, {
            code: '01050009',
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                    message.success('删除成功');
                    // 刷新列表数据
                    this.getTableData();
                } else {
                    message.error('删除失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('删除失败：' + error);
            }
        })
    }
     
   // 显示分页总条数
   showTotal(total) {
    return `共 ${total} 条`;
    }

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

    onShowSizeChange = (current, size) => {
        this.setState({page: 1, pageSize: size}, () => {
                  // 重新调用查询方法
                  this.getTableData();
              });
      }
    
    render() {
        const columnr = [{
            title: '岗位名称',
            dataIndex: 'PostDesc',
            width: 150,
            align: "center"
        },
        {
            title: '角色名称',
            dataIndex: 'GroupDesc',
            width: 150,
            align: "center"
        }];
        return (
          <div>
             <Modal
                    title="岗位角色列表"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    >
                  <Table
                    bordered
                    style={{ height: '400px', maxHeight: '400px', overflow: 'scroll' }}
                    columns={columnr}
                    dataSource={this.state.datasource1}
                    rowKey={(row) => {
                        return row.id
                    }}
                    //rowkey={row => row.key}
                    onRow={this.onClickRow1}
                    pagination={false}
                />
                </Modal>
              <DepartmentSettingAdd 
                 getTableData={this.getTableData} 
                // selectData={this.state.selectData}
                // hospitalData={this.state.hospitalData}
                // DepartmentInformation={this.state.DepartmentInformation}
              ></DepartmentSettingAdd>
              <div style={{widht: '100%', height: '10px', background: '#f0f2f5'}}></div>
                <div className="table-operations" style={{height: '64px', lineHeight: '64px', padding: '0 24px'}}>
                    <Row>
                        <Col span={24}>
                        医院名称：<Select showSearch optionFilterProp="title" allowClear value={this.state.hospitalId} onChange={this.onChangehospitalId} style={{width: '150px', marginRight: '15px'}} placeholder="请选择医院">
											{this.state.hospitalData && this.state.hospitalData.map(item => {
												return <Option key={item.id} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
											})}
										</Select>
                     
                          科室名称：<Select showSearch optionFilterProp="title" allowClear  value={this.state.locDesc} onChange={this.onChangeLocDesc} style={{width: '150px', marginRight: '15px'}} placeholder="请选择科室名称">
                                {this.state.DepartmentInformation && this.state.DepartmentInformation.map(item => {
                                    return <Option key={item.id} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                })}
                            </Select>
                         
                            <Button onClick={this.getTableData} style={{ marginRight: '15px', background: 'rgba(255,255,255,1)'}}>查询</Button>
                        </Col>
                    </Row>
                </div>
              
                <div style={{ padding: 24 }}>
                    <div>
                        <Table
                            style={{height: store.getState().tableHeight.y + 45 + 'px'}}
                            dataSource={this.state.data}
                            columns={this.columns}
                            pagination={false}
                            rowKey={(row) => {
                                return row.ID
                            }}
                            scroll={{ x: 1000, y: store.getState().tableHeight.y }}
                            bordered
                            loading={this.state.loading}
                        />
                        {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                        <Pagination
                            showTotal={() => this.showTotal(this.state.total)}
                            size="small"
                            showQuickJumper
                            showSizeChanger
                            defaultCurrent={1}
                            current={this.state.page}
                            total={this.state.total}
                            onChange={this.onChange}
                            onShowSizeChange={this.onShowSizeChange}
                            style={{textAlign: "right", marginTop: '13px'}}
                        />
                    </div>
                </div>
          </div>
        )
    }
}