// 下级医生维护
import React from 'react';
import {Select, Card, Table, Row, Col, Input, Button, message, Popconfirm, Icon} from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';

let {Option} = Select;

export default class MaintenanceJuniorDoctors extends React.Component {
  constructor() {
    super();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      leftColumns: [], 
      leftTableData: [], 
      rightRowKeys: [], 
      rightColumns: [], 
      rightTableData: [],
      departmentSelectData: [], // 科室下拉数据
      userSelectData: [], // 人员下拉数据
      locID: undefined,
      userID: undefined,
    }
  }

  componentDidMount() {
    this.getLeftColumns();
    this.getRightColumnsDate();
    this.getDepartmentSelectData();
    this.getUserSelectData();
  }

  // 查询科室下拉数据
  getDepartmentSelectData = () => {
    let {userData} = this.state;
    let data = {
			params: [{
				hospID: userData&&userData.hospID ? userData.hospID : '', // 所属医院
				locID: "", // 科室名称
				status: "", // 记录状态
				detailFlag: 1,
				type: "",
				linkFlag: '',
				docFlag: ''
			}]
		}
		$http.post('urlS', this, {
			code: "04020008",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
          this.setState({departmentSelectData: res.result.Data})
				}
			}
		})
  }

  // 获取人员下拉列表数据
  getUserSelectData = () => {
    let data = {
      params: [{}],
      pagination: [{
        pageSize: 10000,
        currentPage: 1
      }]
    }
    $http.post('urlS', this, {
        code: "06030013",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({userSelectData: res.result})
          }
        }
    });
  }

  // 获取左侧表头数据
  getLeftColumns = () => {
    let columns = [
      {
        title: '工号',
        dataIndex: 'userCode',
        align: 'center'
      },
      {
        title: '姓名',
        dataIndex: 'userDesc',
        align: 'center'
      },
      {
        title: '职称',
        dataIndex: 'userDutiesDesc',
        align: 'center'
      },
      {
        title: '科室描述',
        dataIndex: 'locDesc',
        align: 'center'
      },
      {
        title: '关联日期',
        dataIndex: 'userCreateDate',
        align: 'center'
      },
      {
			  title: '操作',
			  align: "center",
			  render: (text, record) => (
				<span>
					<Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
				  <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
						<span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
				  </Popconfirm>
				</span>
			  ),
			}
    ];
    this.setState({leftColumns: columns});
  }

  // 获取左侧表格数据
  getLeftTableData = () => {
    let {locID, userID} = this.state;
    let data = {
      params: [{
        eMRUserID: userID,
        locID
      }]
    }
    $http.post('urlS', this, {
        code: "06010077",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({leftTableData: res.result})
          }
        }
    });
  }

  // 获取右侧表头数据
  getRightColumnsDate = () => {
    let columns = [
      {
        title: '姓名',
        dataIndex: 'userDesc',
        align: 'center'
      },
      {
        title: '工号',
        dataIndex: 'userCode',
        align: 'center'
      },
      {
        title: '职称',
        dataIndex: 'enDescripts',
        align: 'center'
      }
    ];
    this.setState({rightColumns: columns});
  }

  // 获取右侧table数据
  getRightTableData = () => {
    let {locID} = this.state;
    let data = {
      params: [{
        locID,
      }],
    }
    $http.post('urlS', this, {
        code: "06010075",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            for(var i = 0; i < res.result.length; i++) {
              res.result[i].key = res.result[i].ID
            }
            this.setState({rightTableData: res.result})
          }
        }
    });
  }

  // 选择科室
  handleLocIDChange = e => {
    this.setState({locID: e, rightRowKeys: []}, () => {
      if (this.state.locID) {
        this.getLocAndUserSelectData("loc", this.state.locID); // 查询当前科室的人员信息
      } else {
        this.setState({rightTableData: []}, () => {
          this.getUserSelectData(); // 查询所有人员信息
        })
      }
    })
  }

  // 选择人员
  handleUserIDChange = e => {
    this.setState({userID: e}, () => {
      if (this.state.userID) {
        this.getLocAndUserSelectData("user", this.state.userID); // 查询当前人员所在科室
      } else {
        this.getDepartmentSelectData(); // 查询所有科室信息
      }
      this.getLeftTableData(); // 查询已关联下级医生
    })
  }

  // 根据科室获取人员或者根据人员获取科室数据 
  getLocAndUserSelectData = (flag, id) => {
    let data = {
      params: [{
        locID: flag === "loc" ? id : undefined,
        userID: flag === "loc" ? undefined : id,
      }],
    }
    $http.post('urlS', this, {
        code: "06010075",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            if (flag === "loc") { // 根据科室查人员
              for(var i = 0; i < res.result.length; i++) {
                res.result[i].key = res.result[i].ID
              }
              this.setState({userSelectData: res.result, rightTableData: res.result})
            } else { // 根据人员查科室
              this.setState({departmentSelectData: res.result})
            }
          }
        }
    });
  }

  // 批量添加
  handleBatchAddition = () => {
    let {userData, locID, userID, rightRowKeys} = this.state;
    if (!locID) {
      message.error("请选择科室。");
      return;
    }
    if (!userID) {
      message.error("请选择人员。");
      return;
    }
    if (!(rightRowKeys&&rightRowKeys.length > 0)) {
      message.error("请选择需要添加的科室内人员。");
      return;
    }
    let data = {
      params: [{
        hospID: userData&&userData.hospID ? userData.hospID : '', // 所属医院
        locID,
        eMRUserID: userID,
        updateUserID: userData&&userData.userID ? userData.userID : "", // 当前操作人
        childUser: rightRowKeys, // 下级医师id
      }],
    }
    $http.post('urlS', this, {
        code: "06010076",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success(res.errorMessage);
            this.getLeftTableData();
            this.getRightTableData()
          }
        }
    });
  }

  // 删除
  handleDelete = (record) => {
    let arr = [];
    arr.push(record&&record.eMRChildUserID ? record.eMRChildUserID : "");
    let data = {
      params: [{
        eMRPowerUserID: arr,
      }],
    }
    $http.post('urlS', this, {
        code: "06010078",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success(res.errorMessage);
            this.getLeftTableData();
          }
        }
    });
  }

  render() {
    let {leftColumns, leftTableData, rightRowKeys, rightColumns, rightTableData, departmentSelectData, locID, userSelectData, userID } = this.state;

    const rightRowSelection = { // 右侧表格
			selectedRowKeys: rightRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({rightRowKeys: selectedRowKeys})
      },
    }

    // 科室
    let departmentOption = departmentSelectData&&departmentSelectData.map((item, index) => {
      return (<Option key={index} value={item.locID} title={item.locDesc} seatchprop={item.locDesc + '^' + item.locDescSPCode}>{item.locDesc}</Option>)
    })

    // 人员
    let userOption = userSelectData&&userSelectData.map((item, index) => {
      return (<Option key={index} value={item.ID} title={item.userDesc} seatchprop={item.userDesc + '^' + item.userDescSPCode}>{item.userDesc}</Option>)
    })
    return (
      <div>
        <div style={{marginBottom: "8px", padding: "0 24px"}}>
          科室：<Select value={locID} onChange={this.handleLocIDChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" style={{width: '150px', margin: '8px 20px 0 0'}}>
            {departmentOption}
          </Select>
          人员：<Select value={userID} onChange={this.handleUserIDChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" style={{width: '150px', marginTop: '8px'}}>
            {userOption}
          </Select>

        </div>
        <div style={{height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%'}}></div>
        <div style={{height: "calc(100% - 91px)", overflow: "auto"}}>
          <Row>
            <Col span={12}>
              <div style={{paddingRight: '6px', position: 'relative'}}>
                <Card
                  size="small"
                  title={<div className="card-title-left-icon">
                    <div></div>
                    已关联科室下级医生
                  </div>}
                >
                  <div style={{height: store.getState().tableHeight.y + 126 + 'px', overflow: 'hidden'}}>
                    <div style={{textAlign: "right", marginBottom: "12px"}}>
                      <Input placeholder="请输入姓名/工号(Enter)" style={{width: "200px", marginRight: "12px"}} />
                      <Button onClick={this.getLeftTableData}>
                        查询
                      </Button>
                    </div>
                    <Table
                      style={{minHeight: "230px"}}
                      // rowSelection={leftRowSelection}
                      columns={leftColumns}
                      dataSource={leftTableData}
                      bordered
                      pagination={false}
                    />
                  </div>
                </Card>
                <div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%'}}></div>
              </div>
            </Col>
            <Col span={12}>
              <Card
                size="small"
                title={<div className="card-title-left-icon">
                  <div></div>
                  科室内人员
                  <div style={{float: 'right', cursor: "pointer"}} onClick={this.handleBatchAddition}>批量添加</div>
                </div>}
              >
                <div style={{height: store.getState().tableHeight.y + 126 + 'px', overflow: 'hidden'}}>
                  <div style={{textAlign: "right", marginBottom: "12px"}}>
                    <Input placeholder="请输入姓名/工号(Enter)" style={{width: "200px", marginRight: "12px"}} />
                    <Button onClick={this.getRightTableData}>
                      查询
                    </Button>
                  </div>
                  <Table
                    style={{minHeight: "230px"}}
                    rowSelection={rightRowSelection}
                    columns={rightColumns}
                    dataSource={rightTableData}
                    bordered
                    pagination={false}
                  />
                </div>
              </Card>
            </Col>
          </Row>
        </div>
      </div>
    )
  }
}