// 家庭成员
import React from 'react';
import {Button, WhiteSpace, Modal, Toast} from 'antd-mobile';
import { $http } from "containers/config/https";
// import {Util} from 'tools';
import './style/index.less';
import '../common/style/index.less';
import store from "store";

import jtcyNoDataImg from 'assets/images/jtcy-nodata.png';

const alert = Modal.alert;

var startX, endX;
export default class MemberOfFamily extends React.Component {
	constructor({history}) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
		this.state = {
      userData,
      visiListData: [], // 就诊人列表数据
      visible: false,
		};
		this.history = history;
	}

	componentDidMount() {
    this.getVisiListData();
	}

	componentWillUnmount() { 
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state,callback)=>{ return; }
  }
  
  // 获取就诊人列表数据
	getVisiListData = () => {
    let {userData} = this.state;
		let data = {
			params: [{
        patNo: userData&&userData.hisPatNo ? userData.hisPatNo : ""
			}]
		}
		$http.post("urlS", this, {
			code: "03070007",
      data: data,
      namespace: "HIS",
			success: function(res) {
				if (+res.errorCode === 0) {
          let visiListData = res.result.data&&res.result.data.length > 0 ? res.result.data : [];
          let currentDom = document.getElementsByClassName("the-patient");
          for(var j = 0; j < currentDom.length; j++) {
            currentDom[j].classList.remove("active");
          }
          this.setState({visiListData});
				}
			}
		});
	}

	// 更换就诊人
  handleChangePatient = item => {
    let {userData} = this.state;
    window.localStorage.setItem('userData', JSON.stringify({
      ...userData,
      patID: item.id,
      patDesc: item.patName,
      idCardNo: item.idCardNo,
      hisPatID: item.hisPatID,
      hisPatNo: item.hisPatNo,
      imUserID: item.imUserID
    }));
    store.dispatch({
      type: "isReRenderHead",
      value: true
    });
    this.history.push("/0003/00030001");
  }

  // 添加就诊人
  handleGoAddPatient = () => {
    this.history.push({
      pathname: "/0003/00030010",
      state: {}
    })
  }

  handleOnTouchStart = (index, e) => {
    var touch = e.touches[0]; //获取触摸对象
    startX = touch.pageX; //获取触摸坐标
    this.timeOutEvent = setTimeout(() => {
      this.timeOutEvent = 0;
      this.setState({visible: true})
    }, 400);
  }
  
  handleOnTouchmove = (e) => {
    var touch = e.touches[0];
    endX = touch.pageX; //手指水平方向移动的距离
    clearTimeout(this.timeOutEvent);  
    this.timeOutEvent = 0;  
  }

  handleOnTouchend = (index, e) => {
    e.stopPropagation();
    let currentDom = document.getElementsByClassName("the-patient");
    for(var i = 0; i < currentDom.length; i++) {
      currentDom[i].classList.remove("active");
      if (i === index) {
        if (startX - endX >= 60) { //手指向左滑动
          currentDom[i].classList.add("active");
        } else { //手指向右滑动
          currentDom[i].classList.remove("active");
        }
      }
    }
    clearTimeout(this.timeOutEvent);  
    if (this.timeOutEvent !== 0) {  
      console.log('你点击了');  
    }  
    return false; 
  }

  // 修改
  handleModify = (item, e) => {
    e.stopPropagation();
    this.history.push({
      pathname: "/0003/00030010",
      state: {...item}
    })
  }

  // 删除
  handleDelete = (item, e) => {
    e.stopPropagation();
    alert('删除家庭成员', '删除后不可恢复确认删除吗???', [
      { text: '取消', onPress: () => e.stopPropagation() },
      { text: '确认', onPress: () => this.handleConfirmDeletion(item, e) },
    ])
  }

  // 确认删除
  handleConfirmDeletion = (item, e) => {
    e.stopPropagation();
    let data = {
			params: [{
        ID: item&&item.ID ? item.ID : "",
        updateUserID: ""
			}]
		}
		$http.post("urlS", this, {
			code: "03070009",
      data: data,
      namespace: "HIS",
			success: function(res) {
        Toast.info(res.errorMessage, 3, () => {}, false);
				if (+res.errorCode === 0) {
          this.getVisiListData()
				}
      },
      error: function(error) {
        Toast.info(error, 3, () => {}, false);
      }
		});
  }

	render() {
    let {visiListData} = this.state;
    let admListDom = visiListData&&visiListData.map((item, index) => {
      return (
        <li key={index} className="the-patient" 
          // onClick={() => this.handleChangePatient(item)} 
          onTouchStart={(e) => this.handleOnTouchStart(index, e)} 
          onTouchMove={this.handleOnTouchmove}
          onTouchEnd={(e) => this.handleOnTouchend(index, e)}
        >
          <i className={item.sex === "男" ? "iconfont icon-nanshi icon-boy" : (item.sex === "女" ? "iconfont icon-nvshi icon-girl" : "iconfont icon-ertong icon-child")}></i> 
          {item.name}
          <strong className="iconfont icon-xiugai" onClick={(e) => this.handleModify(item, e)}></strong>
          {/* <span className={userData&&(userData.patID === item.id) ? "check-pat radio-checked" : "check-pat"}></span> */}
          <span className="moditybtn" onClick={(e) => this.handleModify(item, e)}>修改</span>
          <span className="delbtn" onClick={(e) => this.handleDelete(item, e)}>删除</span>
        </li>
      )
    })
		return(
			<div className="visit-list chronic-disease-management">
        {/* <p className="title-p">就诊人</p> */}
        {visiListData&&visiListData.length > 0 ? (
          <ul className="vl-list-item">
            {admListDom}
          </ul>
        ): (
          <div className="record-nodata"><img src={jtcyNoDataImg} alt="" /><span>暂无家庭成员数据</span></div>
        )}
       
        <div className="add-card-button">
          <Button type="primary" onClick={this.handleGoAddPatient}>添加家庭成员</Button>
          <WhiteSpace />
          <p style={{textAlign: "center", color: "#999", padding: "0 12px"}}>您可通过向右边滑动家庭成员进行修改或者删除操作（仅限手机端）。</p>
        </div>
        
			</div>
		)
	}
}