/*
 * Creator:     ML
 * CreatDate:   2020-03-21
 * descripts：  患者中心 预约治疗
 * */
import React from 'react';
import { Toast, Button, List, SearchBar, Modal, Carousel } from 'antd-mobile';
import { $http } from "containers/config/https";
// import { Util } from 'tools';
import './style/index.less';
import store from "store";
import AppointmentItem from './componts/AppointmentItem'
const ListItem = List.Item;
const alert = Modal.alert;
class Appointment extends React.Component {
  constructor({ history }) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    this.state = {
      userData,
      smallClassModal: false,
      itemID: "",
    };
    this.history = history;
  }

  componentDidMount = () => {
    this.handleGetWek()
    setTimeout(() => {
      this.setState({
        data: ['AiyWuByWklrrUDlFignR', 'TekJlZRVCjLFexlOCuWn', 'IJOtIlfsYdTyaDTRVrLI'],
      });
    }, 100);
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }

  }
  //获取预约星期
  handleGetWek = () => {
    let data = {
      params: [{
      }],
    }
    $http.post("urlS", this, {
      code: "01040008",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            appointWekdayArr: res.result,
            wekDayItemID: res.result[0].id,
            appointWekdayLength: res.result.length
          }, () => {
            this.handleGetNoon()
          })
        } else {
          Toast.info(res.errorMessage)
        }
      }
    });
  }
  //获取上午中午下午
  handleGetNoon = () => {
    const { userData } = this.state
    let data = {
      params: [{
        hospCode: userData && userData.hospCode ?  userData.hospCode : "",
        resDate: this.state.wekDayItemID,
      }],
    }
    $http.post("urlS", this, {
      code: "01040001",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            appointafternoonArr: res.timeRange,
            noonItemID: res.timeRange[0].id
          }, () => {
            this.handleGetNDoctorList()
          })
        } else {
          Toast.info(res.errorMessage)
        }
      }
    });
  }
  //搜索医生排班信息
  handleSearch = () => {
    this.setState({
      wekDayItemID: "",
      noonItemID: ""
    }, () => {
      this.handleGetNDoctorList()
    })
  }
  //获取医生排班信息
  handleGetNDoctorList = () => {
    const { userData } = this.state
    let data = {
      params: [{
        timeRangeID: this.state.noonItemID,
        date: this.state.wekDayItemID,
        doctorStr: this.state.searchValue,
        cureAppID: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.cureAppID) || "",
        medItemID: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.medItemID) || (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.medID),
        locID: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.locID) || "",
        hospCode: userData && userData.hospCode ? userData.hospCode : "",
      }],
    }
    $http.post("urlS", this, {
      code: "01040002",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            projectArr: res.result.data
          })
        } else {
          Toast.info(res.errorMessage)
        }
      }
    });
  }
  //获取预约时间段 弹出框
  getAppointTimeArr = (item) => {
    const { userData } = this.state
    this.setState({
      resDetailID: item.resDetailID,
    })
    let data = {
      params: [{
        resDetailID: item.resDetailID,
        hospCode: userData && userData.hospCode ? userData.hospCode : "",
      }],
    }
    $http.post("urlS", this, {
      code: "01040003",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            appointTimeArr: res.data.resDetail
          })
        } else {
          Toast.info(res.errorMessage)
        }
      }
    });
  }
  //点击预约按钮 弹出预约时间选择
  handleAppiont = (item) => {
    this.getAppointTimeArr(item)
    this.setState({
      smallClassModal: true
    }, () => {
      if (document.querySelector(".appointTimeOp-dom .am-list-line .am-list-content")) {
        document.querySelector(".appointTimeOp-dom .am-list-line .am-list-content").style.display = "flex"
        document.querySelector(".appointTimeOp-dom .am-list-line .am-list-content").style.flexWrap = "wrap"
        document.querySelector(".edit-dom .am-list-line .am-list-content").style.display = "flex"
        document.querySelector(".edit-dom .am-list-line .am-list-content").style.flexWrap = "wrap"
        let arr = document.querySelectorAll(".edit-dom .am-list-line .am-list-content .am-button")
        for (var i = 0; i < arr.length; i++) {
          arr[i].style.width = "50%";
          arr[i].style.fontSize = "12px";
        }

      }
    })
  }
  //关闭弹窗
  onClose = () => {
    this.setState({
      smallClassModal: false,
      itemID: ""
    })
  }
  //点击选择预约时间段
  handleItem = (item, name) => {
    if ([name + "ID"] === item.id) {
      this.setState({
        [name + "ID"]: "",
      }, () => {
      })

    } else if ([name + "ID"] === "") {
      this.setState({
        [name + "ID"]: item.id
      }, () => {
        if ((name + "ID" === "noonItemID") || (name + "ID" === "wekDayItemID")) {
          this.handleGetNDoctorList()
        }
      })

    } else {
      this.setState({
        [name + "ID"]: item.id
      }, () => {
        if ((name + "ID" === "noonItemID") || (name + "ID" === "wekDayItemID")) {
          this.handleGetNDoctorList()
        }
      })
    }
  }
  //设置隐藏
  setNone = (arr) => {
    for (var i = 0; i < arr.length; i++) {
      arr[arr.length - 1].style.display = "none";
    }
  }
  //正在预约.....
  handleOpen = (n) => {
    const { userData } = this.state
    let okAndcancel = [
      { text: <span style={{ fontSize: "14px" }} onClick={this.handleAppiontRecord}>{"否>>返回预约记录"}</span>, onPress: () => this.handleCancel() },
      { text: <Button style={{ background: "#22a9a9", fontSize: "14px", color: "#fff", width: "100%", height: "100%", display: ("inline-block") }}>{"是>>继续预约"}</Button>, onPress: () => this.handleOk() }
    ]
    let cancel = [
      { text: <span style={{ fontSize: "14px" }} onClick={this.handleAppiontRecord}>{"否>>返回预约记录"}</span>, onPress: () => this.handleCancel() },
    ]
    // let x = []
    // let that = this
    let data = {
      params: [{
        curAppID: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.cureAppID) || "",
        resDetailID: this.state.resDetailID,
        resTimeID: this.state.itemID,
        locID: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.locID) || "",
        hospCode: userData && userData.hospCode ? userData.hospCode : "",
      }],
    }
    $http.post("urlS", this, {
      code: "01040004",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            smallClassModal: false,
            appQty: res.appQty,
            surQty: res.surQty,
          }, () => {
            //预约成功之后弹操作指引
            alert(
              "预约成功"
              ,
              <p style={{ fontSize: "12px" }}>
                已预约<span style={{ color: "#22a9a9" }}>{res.appQty + "次，"}</span>
                剩余<span style={{ color: "#22a9a9" }}>{res.surQty + "次，"}</span>
                <span>是否需要继续预约?</span>
              </p>,
              +res.surQty === 0 ? cancel : okAndcancel
            )
          })
        } else {
          Toast.info(res.errorMessage)
        }
      }
    });
  }
  //继续预约
  handleOk = () => {
    //刷新预约列表
    this.handleGetNDoctorList()
  }
  handleCancel = () => {

  }
  //返回预约记录
  handleAppiontRecord = () => {
    let item = this.props.location.state
    this.history.push({
      pathname: "/0002/0016",
      state: { ...item }
    })
  }
  //实时获取搜索框的值
  handleChangeValue = (e) => {
    this.setState({
      searchValue: e
    })
  }
  //查看申请
  handleCheckApply = (item, flag) => {
    let obj = item
    if (!flag) {
      obj["disabled"] = true
      obj["edit"] = 0
      this.history.push({
        pathname: "/0002/0011",
        state: { ...obj }
      })
    } else {
      obj["disabled"] = false
      obj["edit"] = 1
      this.history.push({
        pathname: "/0002/0011",
        state: { ...obj }
      })
    }

  }
  toHome = () => {
    this.history.push({
      pathname: "0010",
      state: {}
    })
    let item = {}
    store.dispatch({
      type: "treatmentItems",
      value: { ...item }
    });
  }
  render() {
    const { searchValue, itemID, wekDayItemID, noonItemID, appointafternoonArr, projectArr, appointTimeArr, appointWekdayArr } = this.state
    let ListItemOp = []
    projectArr && projectArr.map((item, i) => {
      return ListItemOp.push(
        <ListItem key={i}>
          <div className="appoint-lists" >
            <div>
              <span className={(+item.docSexCode === 1 ? 'card-splice-boy' : 'card-splice-girl') + " AvtorImg"}>
              </span>
              <span className="info">
                <span className="name">
                  <span>{item.doctorName}</span>
                  <span>{item.sessionType}</span>
                </span>
                <span className="type">{item.appMedItemDesc}</span>
              </span>
            </div>
            <div>
              <span onClick={() => this.handleAppiont(item)}>预约</span>
            </div>
          </div>
        </ListItem>
      )
    })
    let appointTimeOp = []
    appointTimeArr && appointTimeArr.map((item, i) => {
      return appointTimeOp.push(
        <ListItem key={i} className="appointime-lists" >
          <div onClick={() => this.handleItem(item, "item")}>
            <Button
              disabled={item.workStatusCode === "F" ? true : false}
              style={{ width: "80px", fontSize: "12px", height: "56px", background: (itemID === item.id ? "rgba(16, 142, 233, 0.6)" : "#fff") }}
            >
              <p style={{ height: "30px", lineHeight: "30px" }}>{item.timeDetail}</p>
              <p style={{ height: "30px", lineHeight: "30px" }}>{item.regResources}</p>
            </Button>
          </div>
        </ListItem>
      )
    })
    let appointWekdayOp = []
    appointWekdayArr && appointWekdayArr.map((item, i) => {
      return appointWekdayOp.push(
        <ListItem key={i} className="appointime-lists" >
          <div onClick={() => this.handleItem(item, "wekDayItem")}>
            <Button
              // disabled={true}
              style={{ width: "62px", fontSize: "12px", height: "56px", background: (wekDayItemID === item.id ? "rgba(16, 142, 233, 0.6)" : "#fff") }}
            >
              <p style={{ height: "30px", lineHeight: "30px" }}>{item.week}</p>
              <p style={{ height: "30px", lineHeight: "30px" }}>{item.monthDate}</p>
            </Button>
          </div>
        </ListItem>
      )
    })
    let appointafternoonOp = []
    appointafternoonArr && appointafternoonArr.map((item, i) => {
      return appointafternoonOp.push(
        <div key={i} className="noon-dom" >
          <Button
            style={{ background: (noonItemID === item.id ? "rgba(16, 142, 233, 0.6)" : "#fff") }}
            onClick={() => this.handleItem(item, "noonItem")}>
            {item.descripts}
          </Button>
        </div>
      )
    })
    return (
      <div className="appoint-dom">
        <AppointmentItem info={this.props.location.state} handleCheckApply={this.handleCheckApply} toHome={this.toHome}></AppointmentItem>
        {/* <WhiteSpace /> */}
        <SearchBar
          placeholder="输入医生搜索"
          cancelText={<span>搜索</span>}
          onCancel={this.handleSearch}
          showCancelButton
          value={searchValue}
          onChange={(e) => this.handleChangeValue(e)}
        />
        <Carousel className="space-carousel"
          frameOverflow="visible"
          dots={false}
          cellSpacing={10}
          slideWidth={0.8}
          afterChange={index => this.setState({ slideIndex: index })}
        >
          {
            appointWekdayOp
          }
        </Carousel>

        <div className="appointNoon-dom">
          {appointafternoonOp}
        </div>
        <div className="scroll-doctor">
          <List>
            {
              this.state.projectArr && this.state.projectArr.length > 0 ? ListItemOp : <p style={{ textAlign: "center", color: "#888", padding: "18px 0" }}>
                未检索到相关信息,请重新搜索
            </p>
            }
          </List>
        </div>

        <Modal
          popup
          visible={this.state.smallClassModal}
          onClose={this.onClose}
          animationType="slide-up"
        >
          <div className="modal-dom">
            <ListItem className="select-dom" style={{ padding: "0", background: "#22a9a9" }}>
              <p style={{ textAlign: "center", color: "#fff", fontSize: "14px", }}>
                <span >请选择预约时段</span>
                <span className="ok-btn" onClick={this.onClose} style={{ color: "#fff", fontSize: "16px", float: "right" }}>{"X"}</span>
              </p>
            </ListItem>
            <ListItem className="appointTimeOp-dom">
              {
                appointTimeOp
              }
            </ListItem>
            <ListItem className="edit-dom" style={{ display: "flex", }}>
              <Button onClick={this.onClose}>取消</Button>
              <Button
                disabled={!itemID}
                style={{ background: "#22a9a9", color: "#fff", }}
                onClick={this.handleOpen}
              >确认</Button>
            </ListItem>
          </div>
        </Modal>
      </div>
    )
  }
};
export default Appointment;