import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Table, Space, TreeSelect } from 'antd';
import apiObj from '@api/index';
import { organizationData } from '@utils/index'
const { post, api,} = apiObj;
const { SHOW_PARENT } = TreeSelect;

function DoctorList(props) {
  useEffect(() => {
    getDoctorPage();
    getHospitalTree()
  }, []);

  const { checkeds, checkDoct } = props;
  const [form] = Form.useForm();
  const [doctorList, setDoctorList] = useState([]);
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [treeData, setTreeData] = useState([]);
  const [total, setTotal] = useState(0);
  const [size, setSize] = useState(10);
  // const [selectedRowKeys, setSelectedRowKeys] = useState();
  const [addHospitalTreeVO, setAddHospitalTreeVO] = useState({
    depts: [],
    hospitals: []
  });
  const selectedRowKeys = checkeds;
  let params = {
    asc: ["id"],
    pages: 1,
    current: 1,
    size: 10
  }
  //获取可看医生列表
  function getDoctorPage() {
    post(api.getDoctorPage, params).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        setDoctorList(data.records);
        setTotal(data.total)
      }
    })
  }
  //获取当前用户组织
  function getHospitalTree() {
    post(api.getHospitalTree).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        let arr = data ? data : []
        arr = organizationData(arr)
        setTreeData(arr)
      }
    })
  }
  // 去重
  function unique(arr) {
    return arr.filter(function (item, index, arr) {
      return arr.indexOf(item, 0) === index;
    });
  }
  const onReset = () => {
    form.resetFields();
    getDoctorPage();
  };
  const handleName = (event) => {
    setName(event.target.value)
  }
  const handlePhone = (event) => {
    setPhone(event.target.value)
  }

  const columns = [
    { title: '姓名', dataIndex: 'name', key: 'index' },
    { title: '电话号码', dataIndex: 'mobilePhone', key: 'index' },
    { title: '所属组织', dataIndex: 'hospitalName', key: 'index' },
  ]
  const onChange = value => {
    let addHospitalTreeVO = {
      depts: [],
      hospitals: []
    }
    value.forEach(it => {
      let arr = JSON.stringify(it).split('-')
      let len = arr.length
      if (len == 2) {
        addHospitalTreeVO.depts.push(arr[1])
      } else {
        addHospitalTreeVO.hospitals.push(arr[0])
      }
    })
    setAddHospitalTreeVO(addHospitalTreeVO)
  };
  function changePage(page, pageSize) {
    params.current = page
    params.size = pageSize
    getDoctorPage()
  }
  function onSizeChange(current, pageSize) {
    params.current = current
    params.size = pageSize
    setSize(pageSize)
    getDoctorPage()
  }
  function onSelectChange(selectedRowKeys) {
    checkDoct(selectedRowKeys)
  }
  function submit() {
    params = {
      ...params,
      mobilePhone: phone,
      name: name,
      depts: addHospitalTreeVO.depts,
      hospitals: unique(addHospitalTreeVO.hospitals)
    }
    getDoctorPage()
  }
  return (
    <div className="doctor_wrapper">
      <div className="doctor_header">
        <div className="doctor_header_left">
          <div className="left_item">
            姓名：<Input placeholder="用户名" onChange={e => handleName(e)} />
          </div>
          <div className="left_item">
            手机号码：<Input placeholder="用户名" onChange={e => handlePhone(e)} />
          </div>
          <div className="left_item">
            所属组织：
            <TreeSelect
              showSearch={false}
              treeData={treeData}
              onChange={onChange}
              treeCheckable
              maxTagCount={1}
              showCheckedStrategy={SHOW_PARENT}
              placeholder="请选择组织"
            />
          </div>
          <div className="left_item">
            <Space size="middle">
              <Button onClick={onReset}>
                重置
              </Button>
              <Button type="primary" onClick={submit}>
                查询
              </Button>
            </Space>
          </div>
        </div>
      </div>

      <div className="table">
        <div className="table-header">
          <span className="table-header-title">医生列表</span>
        </div>
        <div className="table-cont">
            <Table
                rowSelection={{
                    selectedRowKeys,
                    onChange: onSelectChange,
                }}
                scroll={{ y: '260px' }}
                className='doctorTable'
                columns={columns}
                dataSource={doctorList}
                rowKey={record => record.id + '-' + record.name}
                pagination={{
                    pageNo: 1,
                    size,
                    size: 'small',
                    showSizeChanger: true,
                    pageSizeOptions: ['15', '30', '60', '120'],
                    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条数据`,
                    onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize), // 改变每页数量时更新显示
                    onChange: (page, pageSize) => changePage(page, pageSize),//点击页码事件
                    total: total
                }} />
        </div>

      </div>
    </div>
  )
}
export default DoctorList;