// 生命体征记录
import React from 'react';
import {Tabs, List} from 'antd-mobile';
import './style/index.less';
import { Chart, Axis, Geom, Tooltip, Legend, Guide } from 'bizgoblin';
import { $http } from "containers/config/https";
import {Util} from 'tools';

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

export default class VitalSignsRecord extends React.Component {
  constructor({history}) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    this.state = {
      userData,
      activeTabs: "1",
      activeTabsDesc: "",
      latelyActive: "month",
      tabsData: [],
      patientVitalSignsRecord: {}
    };
    this.history = history;
  }

  componentDidMount() {
    this.getTabsData();
  }

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  // 获取命体征类型下拉数据
  getTabsData = () => {
    let data = {
			params: [{}]
		}
		$http.post("urlS", this, {
			code: "03070020",
      data: data,
      namespace: "HIS",
			success: function(res) {
				if (+res.errorCode === 0) {
          for(var i = 0; i < res.result.length; i++) {
            res.result[i].key = res.result[i].id;
          }
          this.setState({tabsData: res.result}, () => {
            if (this.state.tabsData&&this.state.tabsData.length > 0) {
              this.setState({activeTabs: this.state.tabsData[0].key, activeTabsDesc: this.state.tabsData[0].descripts}, () => {
                this.getPatientVitalSignsRecord();
              })
            }
          })
				} else {
					this.setState({tabsData: []});
				}
			}
		});
  }

  // 查询患者生命体征记录
  getPatientVitalSignsRecord = () => {
    let {latelyActive, userData, activeTabs} = this.state;
    let startDate = "";
    let endDate = "";
    if (latelyActive === "day") {
      startDate = Util.getLastWeek().last;
      endDate = Util.getLastWeek().now;
    } else {
      startDate = Util.getLastMonth().last;
      endDate = Util.getLastMonth().now;
    }
    let data = {
			params: [{
        patID: userData&&userData.hisPatID ? userData.hisPatID : "",
        startDate,
        endDate,
        signTypeID: activeTabs
      }]
		}
		$http.post("urlS", this, {
			code: "03070023",
      data: data,
      namespace: "HIS",
			success: function(res) {
				if (+res.errorCode === 0) {
          this.setState({patientVitalSignsRecord: res.result});
				} else {
					this.setState({patientVitalSignsRecord: {}});
				}
			}
		});
  }

  handleTabsChange = (tab) => {
    this.setState({activeTabs: tab.key, activeTabsDesc: tab.descripts}, () => {
      this.getPatientVitalSignsRecord();
    });
  }

  handleLatelyBtnClick = type => {
    this.setState({latelyActive: type}, () => {
      this.getPatientVitalSignsRecord();
    });
  }

  gotoEnterPhysicalData = () => {
    this.history.push("/0003/00030009");
  }

  // 过滤chartData
  filterChartData = () => {
    let {patientVitalSignsRecord} = this.state;
    let res = patientVitalSignsRecord.data&&patientVitalSignsRecord.data.map((item, index) => {
      return {
        ...item,
        date: item.collectDate,
        type: item.signType + "(正常范围：" + item.usualValueFrom + "-" + item.usualValueTo + ")",
        value: parseInt(item.signValue)
      }
    })
    return res;
  }

  marker(x, y, r, ctx) {
    ctx.lineWidth = 1;
    ctx.strokeStyle = ctx.fillStyle;
    ctx.moveTo(x - r - 3, y);
    ctx.lineTo(x + r + 3, y);
    ctx.stroke();
    ctx.arc(x, y, r, 0, Math.PI * 2, false);
    ctx.fill();
  }

  onShowTooltip(ev) {
    const items = ev.items;
    for(var i = 0; i < items.length; i++) {
      items[i].name = items[i].origin.colDateTime;
    }
  }

  // 遍历出所有的体征类型
  arrayWeightRemoval = (data) => {
    let newArr = [];
    for(let i = 0; i < data.length; i++) {
      let objTemp = {};
      if(!objTemp[data[i].signCode]) {
        newArr.push(data[i]);
      }
    }
    return newArr;
  }

  render() {
    let {activeTabs, latelyActive, tabsData, patientVitalSignsRecord} = this.state;
    let latelyData = [
      {
        label: "最近七天",
        value: "day"
      },
      {
        label: "最近一个月",
        value: "month"
      }
    ]
    let latelyBtn = (
      <div className="lately-btn border-bottom-after">
        {latelyData&&latelyData.map((item, index) => {
          return <span key={index} className={latelyActive === item.value ? "active" : ""} onClick={() => this.handleLatelyBtnClick(item.value)}>{item.label}</span>
        })}
      </div>
    )

    let isAbnormal = patientVitalSignsRecord&&patientVitalSignsRecord.exceptionQty > 0 ? true : false;
    const defs = [
      {
        dataKey: 'value',
        tickCount: 5,
        min: 0,
      },
      {
        dataKey: 'date',
        type: 'cat',
        range: [0, 1],
        tickCount: 5,
      },
    ];
    let tabsContentDom = () => (
      <div>
        {latelyBtn}
        <div>
          <Chart padding={40} width="100%" data={this.filterChartData()} defs={defs} pixelRatio={window.devicePixelRatio * 2} >
            <Axis dataKey="date" />
            <Axis dataKey="value" label={{ fontSize: 12 }} />
            {patientVitalSignsRecord.data&&patientVitalSignsRecord.data.length > 0 ? Util.uniqArr(patientVitalSignsRecord.data, "signCode").map((item, index) => {
              return (
                <Guide
                  key={index}
                  type='rect'
                  top={false} // 指定 guide 是否绘制在 canvas 最上层，默认为 false, 即绘制在最下层
                  start= {[0, item.usualValueFrom]} // 辅助线起始位置，值为原始数据值，支持 callback
                  end= {[Util.uniqArr(patientVitalSignsRecord.data, "collectDate") ? Util.uniqArr(patientVitalSignsRecord.data, "collectDate").length : 0, item.usualValueTo]} // 辅助线结束位置，值为原始数据值，支持 callback
                  style = {{
                    lineWidth: 0, // 辅助框的边框宽度
                    fill: item.signCode === "DBP" ? '#4BD863' : "#0079FE", // 辅助框填充的颜色
                    fillOpacity: 0.1, // 辅助框的背景透明度
                    stroke: '#ccc' // 辅助框的边框颜色设置
                  }}
                />
              )
            }) : ""}
            <Tooltip showItemMarker={false} showCrosshairs onShow={this.onShowTooltip} offsetY={10} />
            <Legend marker={this.marker} position="bottom" align="right" />
            <Geom geom="line" position="date*value" color="type" />
            <Geom geom="point" position="date*value" color="type" style={{ lineWidth: 1, stroke: '#FFF' }} />
          </Chart>
        </div>
        <div className="vsr-footer">
          {patientVitalSignsRecord.data&&patientVitalSignsRecord.data.length > 0 ? (<List className="vsr-message">
            <Item
              thumb={<i className={isAbnormal ? "iconfont icon-yichang" : "iconfont icon-zhengchang"}></i>}
              multipleLine
              className={isAbnormal ? "info" : "success"}
            >
              {isAbnormal ? "异常提示" : "指标正常"} <Brief>{isAbnormal ? "您有指标异常，如有突发情况请及时就医！" : "该阶段无异常情况。"}</Brief>
            </Item>
          </List>) : ""}
          <p onClick={this.gotoEnterPhysicalData}>
           手动录入体征数据
          </p>
        </div>
      </div>
    )
    return (
      <div className="vital-signs-record">
        <div className="vsr-content">
          <Tabs tabs={tabsData}
            page={activeTabs}
            onChange={this.handleTabsChange}
            renderTab={tab => <span>{tab.descripts}</span>}
          >
            {tabsContentDom}
          </Tabs>
        </div>
      </div>
    )
  }
}