// 预约挂号
import React from 'react';
import {Tabs, List, Badge} from 'antd-mobile';
import './style/appointmentRegistration.less';
import { $http } from "containers/config/https";
import store from "store";

import VisitDateAndPeriod from './component/VisitDateAndPeriod.jsx';

export default class AppointmentRegistration extends React.Component {
  constructor({history}) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    this.state = {
      userData,
      tabs: [],
      adminStatus: true,
      visible: false,
      admID: "2",
      activeTabs: "",
      departmentChildItem: {},
      schedulingData: []
    }
    this.history=history;
  }

  componentDidMount() {
    let departmentChildItem = this.props.location&&this.props.location.state ? this.props.location.state : "";
    if (departmentChildItem&&departmentChildItem.id) {
      this.setState({departmentChildItem}, () => {
        store.dispatch({
          type: "departmentChildItem",
          value: departmentChildItem
        });
        this.getTabsData()
      })
    } else {
      let storeDepartmentChildItem = store.getState().appointRegRedux&&store.getState().appointRegRedux.departmentChildItem ? store.getState().appointRegRedux.departmentChildItem : {};
      if (storeDepartmentChildItem&&storeDepartmentChildItem.id) {
        this.setState({departmentChildItem: storeDepartmentChildItem}, () => {
          this.getTabsData()
        })
      } else {
        this.history.goBack();
      }
    }
  }

  // 获取tab数据
  getTabsData = () => {
    let data = {
			params: [{
        date: ""
      }]
		}
		$http.post("urlS", this, {
			code: "03040002",
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
          let tabs = res.result&&res.result.length > 0 ? res.result : [];
          let arActiveKey = store.getState().appointRegRedux&&store.getState().appointRegRedux.arActiveKey ? store.getState().appointRegRedux.arActiveKey : "";
          let activeTabs = "";
          let tab = {};
          for(var i = 0; i < tabs.length; i++) {
            tabs[i].key = tabs[i].dataIndex;
          }
          for(var j = 0; j < tabs.length; j++) {
            if (tabs[j].currentFlag === "Y") {
              tab = tabs[j];
              activeTabs = tabs[j].dataIndex;
              break;
            }
          }
          this.setState({tabs, activeTabs: arActiveKey ? arActiveKey : activeTabs}, () => {
            store.dispatch({
              type: "arActiveKey",
              value: this.state.activeTabs,
            });
            if (this.state.departmentChildItem&&this.state.departmentChildItem.id&&this.state.departmentChildItem.id === "最近挂号") {
              this.getTheLatestRegistrationData(tab);
            } else {
              this.getSchedulingData(tab);
            }
          });
				} else {
					this.setState({tabs: []});
				}
			}
		})
  }

  // 切换tabs
  handleTabsChange = (tab) => {
    this.setState({activeTabs: tab.dataIndex}, () => {
      store.dispatch({
        type: "arActiveKey",
        value: this.state.activeTabs,
      });
      if (this.state.departmentChildItem&&this.state.departmentChildItem.id&&this.state.departmentChildItem.id === "最近挂号") {
        this.getTheLatestRegistrationData(tab);
      } else {
        this.getSchedulingData(tab);
      }
    })
  }

  // 获取最近挂号相关数据
  getTheLatestRegistrationData = (tab) => {
    let {userData} = this.state;
    let data = {
			params: [{
        hospID: userData&&userData.hisHospID ? userData.hisHospID : "",
        patNo: "0000000002",
        date: tab&&tab.date ? tab.date : "",
      }]
		}
		$http.post("urlS", this, {
			code: "03040005",
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
          let schedulingData = res.result&&res.result.data&&res.result.data.length > 0 ? res.result.data : [];
          for(var i = 0; i < schedulingData.length; i++) {
            for(var j = 0; j < schedulingData[i].data.length; j++) {
              schedulingData[i].data[j].locDesc = schedulingData[i].locDesc;
            }
          }
          this.setState({schedulingData});
				} else {
					this.setState({schedulingData: []});
				}
			}
		});
  }

  // 获取排班数据
  getSchedulingData = (tab) => {
    let {userData, departmentChildItem} = this.state;
    let data = {
			params: [{
        userID: "",
        hospID: userData&&userData.hisHospID ? userData.hisHospID : "",
        groupID: "",
        locID: departmentChildItem&&departmentChildItem.id ? departmentChildItem.id : "",
        doctorID: "",
        date: tab&&tab.date ? tab.date : "",
      }]
		}
		$http.post("urlS", this, {
			code: "03040003",
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
          let schedulingData = res.result&&res.result.data&&res.result.data.length > 0 ? res.result.data : [];
          for(var i = 0; i < schedulingData.length; i++) {
            for(var j = 0; j < schedulingData[i].data.length; j++) {
              schedulingData[i].data[j].locDesc = schedulingData[i].locDesc;
            }
          }
          this.setState({schedulingData});
				} else {
					this.setState({schedulingData: []});
				}
			}
		})
  }
  
  // 查询排班详情
  handleShowVisitDateAndPeriod = (item, childItem) => {
    let obj = {
      item,
      childItem: childItem&&childItem.title ? childItem : {},
    }
    this.modalChild.showModal(obj);
  }

  // 跳转到医生个人主页
  handleGoDoctorProfile = (item) => {
    this.history.push({
      pathname: "/0002/00040003",
      state: {...item}
    })
  }

  handleOnRef = ref => {
    this.modalChild = ref
  }

  render() {
    let {tabs, activeTabs, schedulingData} = this.state;
    let tabsContentDom = () => (
      <div style={{height: "100%", overflow: "auto"}} className="ehc-list">
        {schedulingData&&schedulingData.map((i, key) => {
          return (
            <div key={key}>
              <p className="ehc-list-head">{i.locDesc || ""}</p>
              {i.data&&i.data.map((item, index) => {
                return <List key={index}>
                  <div className="list-header" onClick={() => this.handleGoDoctorProfile(item)}>
                    <div className="list-header-avatar">
                      <i className="iconfont icon-yonghutouxiang"></i>
                    </div>
                    <div className="list-header-title">
                      {item.isBadge ? (
                        <Badge text={<span className="font12">管挂号</span>} corner size="large">
                          <div className="list-header-title-content" style={{borderBottom: "1px solid #ddd"}}>
                            <div>
                              {item.doctorName} <span>{item.title}</span>
                            </div>
                            <div>
                              线上就诊量：<span>49999</span>
                              <span>评价：☆☆☆☆☆</span>
                            </div>
                          </div>
                        </Badge>
                      ) : (
                        <div className="list-header-title-content" style={{borderBottom: "1px solid #ddd"}}>
                          <div>
                            {item.doctorName} <span>{item.title}</span>
                          </div>
                          <div>
                            线上就诊量：<span>49999</span>
                            <span>评价：☆☆☆☆☆</span>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                  <List.Item data-seed="logId">{item.introduce || "暂无数据"}</List.Item>
                  {item.resList&&item.resList.map((childItem, childIndex) => {
                    return (
                      <List.Item key={childIndex} onClick={() => this.handleShowVisitDateAndPeriod(item, childItem)} multipleLine extra={<div>{childItem.usableNum > 0 ? "余号："+childItem.usableNum : "挂号已满"}</div>} arrow="horizontal" className={childItem.usableNum > 0 ? "" : "registered-full"}>
                        {childItem.title}
                      </List.Item>
                    )
                  })}
                  <List.Item multipleLine arrow="horizontal" onClick={() => this.handleShowVisitDateAndPeriod(item, {})}>
                    更多……
                  </List.Item>
                </List>
              })}
            </div>
          )
        })}
        
      </div>
    )
    return (
      <div className="electronic-health-card" style={{height: "100%", overflow: "hidden"}}>
        <div style={{height: "100%", overflow: "hidden", position: "relative"}} className="appointment-registration paddingtop10">
          <Tabs tabs={tabs}
            page={activeTabs}
            onChange={this.handleTabsChange}
            renderTab={tab => <div>
              {tab.dataIndex !== "all" ? (<div className="tabs-header">
                <span className={tab.currentFlag === "Y" ? "the-day" : ""}>{tab.currentFlag === "Y" ? "今天" : tab.title}</span>
                {tab.week}
              </div>) : tab.week}
            </div>}
          >
            {tabsContentDom}
          </Tabs>
        </div>
        <VisitDateAndPeriod onRef={this.handleOnRef} history={this.history} />
      </div>
    )
  }
}
