// 账户
import React from 'react';
import { Accordion, List, Toast } from 'antd-mobile';
import './style/index.less';
import "./style/visitRecords.less";
import "assets/less/common.less";
import { $http } from "containers/config/https";
import { Util } from 'tools';
import store from "store";

import zhYuE from 'assets/images/zh-yue.png';
import zhZhuyuanfeiyong from 'assets/images/zh-zhuyuanfeiyong.png';

const Item = List.Item;
// const Brief = Item.Brief;

export default class Account extends React.Component {
  constructor({ history }) {
    super();
    this.state = {
      userData: JSON.parse(localStorage.getItem("userData")) || {},
      admData: {},
      unsettledBillInformation: [],
      depositListData: []
    }
    this.history = history;
  }

  componentDidMount() {
    let admData = this.props.location && this.props.location.state ? this.props.location.state : "";
    store.dispatch({
      type: "isSelectPatient",
      value: "no"
    });
    if (admData && admData.admID) {
      this.setState({ admData }, () => {
        this.getUnsettledBillInformation();
        this.getVisitRecordsListData();
        this.getDepositListData();
        window.sessionStorage.setItem(
          "admData",
          JSON.stringify(
            { ...admData }
          )
        );
      })
    } else {
      // 不做缓存
      let storeAdmData = sessionStorage.getItem("admData") ? JSON.parse(sessionStorage.getItem("admData")) : {};
      if (storeAdmData && storeAdmData.admID) {
        this.setState({ admData: storeAdmData }, () => {
          this.getUnsettledBillInformation();
          this.getVisitRecordsListData();
          this.getDepositListData();
        })
      } else { // 扫码
        let url = window.location.href.indexOf("?") !== -1 ? String(window.location.href).split("?")[1] : "";
        let admID = Util.interceptTheValueOfTheURL(Util.interceptTheValueOfTheURL(url, "params", "&", "="), "admID", "^", ":");
        let patNo = Util.interceptTheValueOfTheURL(Util.interceptTheValueOfTheURL(url, "params", "&", "="), "patNo", "^", ":");
        let urlObj = {};
        urlObj.admID = admID;
        urlObj.patNo = patNo;
        this.setState({ admData: urlObj }, () => {
          this.getUnsettledBillInformation();
          this.getVisitRecordsListData(true);
          this.getDepositListData();
        })
      }
    }
  }

  componentWillUnmount() {
    store.dispatch({
      type: "isSelectPatient",
      value: "yes"
    });
  }

  // 获取就诊记录
  getVisitRecordsListData = (isUpdataPatInfo) => {
    Toast.loading('数据加载中...', 30);
    let { userData, admData } = this.state;
    // console.log(admData)
    let data = {
      params: [{
        hospCode: userData && userData.hisHospID ? userData.hisHospID : "",
        patDesc: userData && userData.patDesc ? userData.patDesc : "",
        userCode: "wxsf",
        patNO: admData.patNo,
        // patNO: "0000038961",
        admID: admData.admID
      }]
    }
    $http.post("urlS", this, {
      code: "130972",
      data: data,
      namespace: "UPP",
      success: function (res) {
        if (+res.errorCode === 0) {
          let newAdmData = res.result && res.result.length > 0 && res.result[0].admDetail.length > 0 ? res.result[0].admDetail[0] : {};
          this.setState({ admData: { ...this.state.admData, ...newAdmData } }, () => {
            if (isUpdataPatInfo) {
              this.getAdmSelectData();
            } else {
              Toast && Toast.hide && Toast.hide();
            }
          });
        } else {
          Toast && Toast.hide && Toast.hide();
          // Toast.info(res.errorMessage, 3, () => {}, false)
        }
      },
      error: function () {
        Toast.hide();
      }
    });
  }



  // 获取就诊人下拉数据
  getAdmSelectData = () => {
    let { admData } = this.state;
    let sessionAmdSelectData = sessionStorage.getItem("admSelectData") ? JSON.parse(sessionStorage.getItem("admSelectData")) : [];
    // console.log("sessionAmdSelectData, admData", sessionAmdSelectData, admData)
    if (sessionAmdSelectData && sessionAmdSelectData.length > 0 && admData && (admData.patNo === sessionAmdSelectData[0].hisPatNo)) {
      this.setState({ admSelectData: sessionAmdSelectData }, () => {
        this.defaultAmdSelectData();
      })
      Toast && Toast.hide && Toast.hide()
      return;
    }
    // console.log("公共组件获取就诊人下拉数据");
    let data = {
      params: [{

      }]
    }
    $http.post("urlS", this, {
      code: "01030001",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          Toast && Toast.hide && Toast.hide()
          let admSelectData = res.result.rows && res.result.rows.length > 0 ? res.result.rows : [];
          for (var i = 0; i < admSelectData.length; i++) {
            admSelectData[i].value = admSelectData[i].patID;
            admSelectData[i].label = admSelectData[i].patName + '（' + admSelectData[i].hisPatNo + '）';
          }
          window.sessionStorage.setItem('admSelectData', JSON.stringify([...admSelectData]));
          this.setState({ admSelectData }, () => {
            this.defaultAmdSelectData(true);
          });
        } else {
          this.setState({ admSelectData: [] });
        }
      },
      error: function () {
        Toast && Toast.hide && Toast.hide()
      }
    });
  }

  // 处理就诊人默认数据
  defaultAmdSelectData = (isReRenderHead) => {
    let { admData } = this.state;
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    if (admData && admData.patNo) {
      let isAdmInfo = false;
      let newUserData = {};
      for (var i = 0; i < this.state.admSelectData.length; i++) {
        if (this.state.admSelectData[i].hisPatNo === admData.patNo) {
          newUserData = this.state.admSelectData[i];
          isAdmInfo = true;
          break;
        }
      }
      // console.log(isAdmInfo, newUserData, admData)
      if (isAdmInfo) {
        let admObj = {};
        admObj.patID = newUserData.patID;
        admObj.patDesc = newUserData.patName;
        admObj.idCardNo = newUserData.idCardNo;
        admObj.hisPatID = newUserData.hisPatID;
        admObj.hisPatNo = newUserData.hisPatNo;
        admObj.imUserID = newUserData.imUserID;
        admObj.patMobile = newUserData.mobile;
        window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...admObj }));
        this.setState({ admData: { ...admData, ...newUserData }, admID: admData && userData.patID ? [userData.patID] : [] }, () => {
          if (isReRenderHead) {
            store.dispatch({
              type: "isReRenderHead",
              value: true
            });
          }
        });
      } else {
        let admObj = {};
        admObj.patID = "";
        admObj.patDesc = "";
        admObj.idCardNo = "";
        admObj.hisPatID = "";
        admObj.hisPatNo = "";
        admObj.imUserID = "";
        admObj.patMobile = "";
        window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...admObj }));
        this.setState({ admData: { ...admData, ...admObj }, admID: [] }, () => {
          if (isReRenderHead) {
            store.dispatch({
              type: "isReRenderHead",
              value: true
            });
          }
        })
      }
    }
  }

  // 未结算账单信息
  getUnsettledBillInformation = () => {
    let { userData, admData } = this.state;
    let data = {
      params: [{
        hospCode: userData.hisHospID,
        userCode: "wxsf",
        patNO: admData.patNo,
        // patNO: "0000038961",
        admID: admData.admID
      }]
    }
    $http.post("urlS", this, {
      code: "130973",
      data: data,
      namespace: "UPP",
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ unsettledBillInformation: res.result });
        } else {
          this.setState({ unsettledBillInformation: [] });
        }
      }
    });
  }

  // 路由返回
  handleGoBack = () => {
    this.history.push("/0001/00000001");
  }

  // 跳转到相对应的子界面
  handlePushChildren = (childPath) => {
    let { admData } = this.state;
    if ((admData && admData.depositflagDesc)) {
      Toast.info("此住院记录已出院，不允许再充值", 3, () => { }, false)
      return;
    }
    this.history.push({
      pathname: childPath,
      state: admData
    });
  }

  handleGoPaymentSlipDetails = (item) => {
    item.activeTabs = '1'
    this.history.push({
      pathname: "/0001/00020006",
      state: item
    })
  }

  // 获取押金列表
  getDepositListData = () => {
    let { userData, admData } = this.state;
    let data = {
      params: [{
        hospCode: userData.hisHospID,
        userCode: "wxsf",
        patNO: admData.patNo,
        // patNO: "0000038961",
        admID: admData.admID
      }]
    }
    $http.post("urlS", this, {
      code: "130976",
      data: data,
      namespace: "UPP",
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ depositListData: res.result });
        } else {
          this.setState({ depositListData: [] });
        }
      }
    });
  }

  render() {
    let { admData, unsettledBillInformation, depositListData } = this.state;
    return (
      <div className="electronic-health-card">
        <div className="account">
          <div className="account-balance daily-list">
            {/* defaultActiveKey="0" */}
            <div className="ab-head" onClick={() => this.handlePushChildren("/0001/00020002")}>
              <p>押金余额<span style={{ color: "#333", fontSize: '18px' }}>（预缴）</span></p>
              <p>¥<span>{admData.deposit ? admData.deposit : '0.00'}</span></p>
            </div>
            <div className="ab-cont">
              <div>
                <img src={zhYuE} alt="可用余额" />
                <span>可用余额<br /><strong>{admData.balance ? admData.balance : '0.00'}</strong></span>
              </div>
              <div>
                <img src={zhZhuyuanfeiyong} alt="住院费用" />
                <span>住院费用<br /><strong>{admData.totalamount ? admData.totalamount : '0.00'}</strong></span>
              </div>
            </div>
            <List renderHeader={() => '未结算订单'}>
              {unsettledBillInformation && unsettledBillInformation.length ? unsettledBillInformation.map((item, index) => {
                return (
                  <Item className="pending-item" key={index} arrow="horizontal" multipleLine extra={<div style={{ color: "#1890FFFF" }}>去缴费</div>} onClick={() => this.handleGoPaymentSlipDetails(item)}>
                    <div className="pending-type">
                      {item.locName} <span className="tabs-type">{admData.admType}</span><span className="pending-admdate">（{item.admdate}）</span>
                    </div>
                    <div className="pending-payment">¥<strong>{item.blance}元</strong></div >
                  </Item>
                )
              }) : <Item>暂无未缴费订单数据</Item>}
            </List>
            <Accordion className="my-accordion">
              <Accordion.Panel header="就诊记录明细">
                <List className="account-balance-list">
                  <List.Item><span>就诊科室：</span>{admData.admLoc}</List.Item>
                  <List.Item><span>就诊医生：</span>{admData.admDoctor}</List.Item>
                  <List.Item><span>费别：</span>{admData.admReasonDesc}</List.Item>
                  <List.Item><span>就诊人：</span>{admData.patName}</List.Item>
                  <List.Item><span>登记号：</span>{admData.patNo}</List.Item>
                  <List.Item><span>就诊日期：</span>{admData.admDate + admData.admTime}</List.Item>
                </List>
              </Accordion.Panel>
            </Accordion>
            <div className="accordion-content">
              <Accordion onChange={this.onChange}>
                <Accordion.Panel header={<div>押金列表</div>}>
                  <div className="primary-table">
                    <table border="0" cellSpacing="1" cellPadding="0">
                      <tbody>
                        <tr>
                          <th>支付方式</th>
                          <th>支付金额</th>
                          <th>支付状态</th>
                          <th>支付日期</th>
                        </tr>
                        {depositListData instanceof Array && depositListData.map((item, index) => {
                          return (<tr key={index}>
                            <td>{item.PayMode}</td>
                            <td>{item.payAmout}</td>
                            <td>{item.payFlag}</td>
                            <td>{item.payTime}</td>
                          </tr>)
                        })}
                      </tbody>
                    </table>
                  </div>
                </Accordion.Panel>
              </Accordion>
            </div>
            {/* <div className="am-list-header">押金列表</div> */}
          </div>
        </div>
      </div>
    )
  }
}