// 患者取药确认
import React from 'react';
import { Tabs, List, Toast } from 'antd-mobile';
import './style/index.less';
import ListCheckboxItem from './common/ListCheckboxItem.jsx';
import { $http } from "containers/config/https";

const Item = List.Item;

export default class ConfirmationOfDrugTaking extends React.Component {
  constructor({ history }) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    this.state = {
      userData,
      activeTabs: '1',
      listData: []
    };
    this.history = history;
  }

  componentDidMount() {
    let confirmationOfDrugTaking = sessionStorage.getItem("confirmationOfDrugTaking") ? JSON.parse(sessionStorage.getItem("confirmationOfDrugTaking")) : {};
    this.setState({ activeTabs: confirmationOfDrugTaking && confirmationOfDrugTaking.activeTabs ? confirmationOfDrugTaking.activeTabs : '1' }, () => {
      this.getListData();
    })
  }

  // 获取需要确认的药品
  getListData = () => {
    let confirmationOfDrugTaking = sessionStorage.getItem("confirmationOfDrugTaking") ? JSON.parse(sessionStorage.getItem("confirmationOfDrugTaking")) : {};
    let checkboxData = confirmationOfDrugTaking && confirmationOfDrugTaking.checkboxData ? confirmationOfDrugTaking.checkboxData : [];
    let { userData, activeTabs } = this.state;
    if (!(userData && userData.hisPatID)) {
      Toast.info("请选择就诊人。", 3, () => { }, false);
      return;
    }
    let data = {
      params: [{
        patID: userData.hisPatID || '',
        // patID: "1",
        statusCode: activeTabs === "1" ? "N" : "Y"
      }]
    }
    $http.post("urlS", this, {
      code: "02030100",
      data: data,
      namespace: "HIS",
      success: function (res) {
        if (+res.errorCode === 0) {
          for (var i = 0; i < res.result.rows.length; i++) {
            res.result.rows[i].checked = false
          }
          this.setState({ listData: this.processingData(res.result.rows, checkboxData), checkboxData: this.processingData(res.result.rows, checkboxData, 'check') })
        } else {
          Toast.info(res.errorMessage, 3, () => { }, false);
        }
      },
      error: function (error) {
        Toast.info(error, 3, () => { }, false);
      }
    });
    // let data = [{id: "1", checked: false}, {id: "2", checked: false}, {id: "3", checked: false}]
    // this.setState({listData: this.processingData(data, checkboxData), checkboxData})
  }

  processingData = (arr, checkArr, isCheck) => {
    let newArr = [];
    if (isCheck === 'check' && !(checkArr && checkArr.length > 0)) {
      return []
    }
    if (!(checkArr && checkArr.length > 0)) {
      return arr
    };
    for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < checkArr.length; j++) {
        if (arr[i].id === checkArr[j].id) {
          newArr.push( arr[i])
          arr[i] = checkArr[j]
        }
      }
    }
    if (isCheck === 'check') {
      return newArr
    } else {
      return arr
    }
  }

  // 切换tabs
  handleTabsChange = (tab) => {
    this.setState({ activeTabs: tab.key }, () => {
      this.getListData();
      let confirmationOfDrugTaking = sessionStorage.getItem("confirmationOfDrugTaking") ? JSON.parse(sessionStorage.getItem("confirmationOfDrugTaking")) : {};
      window.sessionStorage.setItem(
        "confirmationOfDrugTaking",
        JSON.stringify(
          {
            ...confirmationOfDrugTaking,
            activeTabs: this.state.activeTabs
          }
        )
      );
    })
  }

  // 获取已勾选的待确认数据
  getCheckboxData = (listData) => {
    let newArr = [];
    for (let i = 0; i < listData.length; i++) {
      if (listData[i].checked) {
        newArr.push(listData[i])
      }
    }
    this.setState({ listData, checkboxData: newArr }, () => {
      let confirmationOfDrugTaking = sessionStorage.getItem("confirmationOfDrugTaking") ? JSON.parse(sessionStorage.getItem("confirmationOfDrugTaking")) : {};
      window.sessionStorage.setItem(
        "confirmationOfDrugTaking",
        JSON.stringify(
          {
            ...confirmationOfDrugTaking,
            checkboxData: this.state.checkboxData
          }
        )
      );
    })
  }

  // 下一步
  handleNextStep = () => {
    let { checkboxData } = this.state;
    window.sessionStorage.setItem(
      "prescriptionActiveRadio",
      JSON.stringify(
        ''
      )
    );
    this.history.push({
      pathname: "/0001/00020012",
      state: [...checkboxData]
    })
  }

  render() {
    let { activeTabs, listData, checkboxData } = this.state;
    let patInfo = listData && listData.length > 0 ? listData[0] : {};
    const tabs = [
      { title: '待确认', key: '1' },
      { title: '已确认', key: '2' },
    ];
    let checkboxDataLen = checkboxData instanceof Array ? checkboxData.length : 0;
    return (
      <div className={activeTabs === '1' ? "confirmation-of-drug-taking" : "confirmation-of-drug-taking no-padding-bottom"}>
        <div className="codt-content">
          <Tabs tabs={tabs}
            page={activeTabs}
            onChange={this.handleTabsChange}
            className="codt-tabs"
          >
            <div className="codt-list">
              <List className={activeTabs === '2' ? 'no-check' : ''}>
                <Item className="list-item-head" extra={<span>{(patInfo && patInfo.patName ? patInfo.patName + ' / ' : '') + (patInfo && patInfo.patSexDesc ? patInfo.patSexDesc + ' / ' : "") + (patInfo && patInfo.patAge ? patInfo.patAge + ' / ' : '') + (patInfo && patInfo.mobile ? patInfo.mobile : "")}</span>} arrow="horizontal">就诊人</Item>
                <ListCheckboxItem history={this.history} listData={listData} getCheckboxData={this.getCheckboxData} takeMedicine={activeTabs === "2" ? true : false} mode={activeTabs === "2" ? true : false} />
              </List>
            </div>
          </Tabs>
        </div>
        <div onClick={this.handleNextStep} className={checkboxDataLen > 0 ? "codt-footer" : "codt-footer codt-footer-disabled"} style={{ display: activeTabs === '1' ? 'block' : 'none' }}>
          {checkboxDataLen > 0 ? ("已选" + checkboxDataLen + "张处方，下一步") : "请选择需要确认的处方"}
        </div>
      </div>
    )
  }
}