// 慢病精细化管理
import React from 'react';
import {List, Card, Flex, Grid, Badge} from 'antd-mobile';
import { Chart, Axis, Geom, Tooltip, Legend, Guide } from 'bizgoblin';
import './style/index.less';
import 'assets/less/common.less';
import { $http } from "containers/config/https";
import {Util} from 'tools';

import xiaoxi from 'assets/images/xiaoxi.png';
import quankeyisheng from 'assets/images/quankeyisheng.png';
import zhuankeyisheng from 'assets/images/zhuankeyisheng.png';
import hulirenyuan from 'assets/images/hulirenyuan.png';
import shegong from 'assets/images/shegong.png';
import shengmingtizheng from 'assets/images/shengmingtizheng.png';
import zhengliaojilu from 'assets/images/zhengliaojilu.png';
import jiatingchengyuan from 'assets/images/jiatingchengyuan.png';
import fuwuxieyishu from 'assets/images/fuwuxieyishu.png';
import noDoc from 'assets/images/no-doc.png';

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

export default class CDMHome extends React.Component {
  constructor({history}) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    this.state = {
      userData,
      latelyActive: "month",
      contractDoctorData: [],
      patientVitalSignsRecord: {},
      patMessageList: [],
      signRecordID: "",
      visible: false
    };
    this.history = history;
    this.timer = null;
  }

  componentDidMount() {
    this.getPatMessageList();
    this.getContractDoctorData();
    this.getPatientVitalSignsRecord();
    this.timer = setInterval(() => {
      this.getContractDoctorData();
    }, 5000)
  }

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

  // 获取患者消息列表
  getPatMessageList = () => {
    let {userData} = this.state;
    let data = {
			params: [{
        patID: userData&&userData.hisPatID ? userData.hisPatID : "",
      }]
		}
		$http.post("urlS", this, {
			code: "03070073",
      data: data,
      namespace: "HIS",
			success: function(res) {
				if (+res.errorCode === 0) {
          this.setState({patMessageList: res.result})
				} else {
					this.setState({patMessageList: []});
				}
			}
		});
  }

  // 查询签约医生
  getContractDoctorData = () => {
    let {userData} = this.state;
    let data = {
			params: [{
        patID: userData&&userData.hisPatID ? userData.hisPatID : "",
        hospCode: userData&&userData.hisHospID ? userData.hisHospID : "",
      }]
		}
		$http.post("urlS", this, {
			code: "03070066",
      data: data,
      namespace: "HIS",
			success: function(res) {
				if (+res.errorCode === 0) {
          let data = res.result&&res.result.doctorData instanceof Array ? res.result.doctorData : []
          for(var i = 0; i < data.length; i++) {
            if (data[i].data&&data[i].data.length === 1) {
              data[i] = {...data[i].data[0]}
            } else if (data[i].data.length > 1) {
              data[i].signDoctorTypeDesc = data[i].data[0].signDoctorTypeDesc;
              for(var j = 0; j < data[i].data.length; j++) {
                data[i].data[j].menuTitle = data[i].data[j].doctorName;
                data[i].data[j].isConsultation = true;
              }
            }
          }
          // console.log(res)
          this.setState({contractDoctorData: data, signRecordID: res.result.signRecordID})
				} else {
					this.setState({contractDoctorData: [], signRecordID: ""});
				}
			}
		});
  }

  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();
  }

  // 一键呼叫
  oneTouchCallClick = item => {
    this.history.push({
      pathname: "/0003/00030002",
      state: {...item}
    }) 
  }

  // 满意度调查
  gotoSatisfactionSurvey = item => {
    if (item.messageTypeCode !== "02") {
      return;
    }
    this.history.push({
      pathname: "/0003/00030004",
      state: {...item}
    }) 
  }

  handleGridChildClick = (el, index) => {
    let {signRecordID} = this.state;
    this.history.push({
      pathname: el.path,
      state: signRecordID
    });
  }

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

  // 查询患者生命体征记录
  getPatientVitalSignsRecord = () => {
    let {latelyActive, userData} = 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: "2"
      }]
		}
		$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: {}});
				}
			}
		});
  }

  // 过滤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;
  }

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

  render() {
    let {latelyActive, contractDoctorData, patientVitalSignsRecord, patMessageList} = this.state;

    let gridData = [{
      icon: shengmingtizheng,
      text: "生命体征记录",
      path: "/0003/00030005"
    }, {
      icon: zhengliaojilu,
      text: "健康管理记录",
      path: "/0003/00030006"
    }, {
      icon: jiatingchengyuan,
      text: "家庭成员",
      path: "/0003/00030007"
    }, {
      icon: fuwuxieyishu,
      text: "服务协议书",
      path: "/0003/00030008"
    }];

    let latelyData = [
      {
        label: "最近七天",
        value: "day"
      },
      {
        label: "最近一个月",
        value: "month"
      }
    ];

    const defs = [
      {
        dataKey: 'value',
        tickCount: 5,
        min: 0,
      },
      {
        dataKey: 'date',
        type: 'cat',
        range: [0, 1],
        tickCount: 3,
      },
    ];
    
    return (
      <div className="cdm-home">
        <List className="cdm-remind-list">
          {patMessageList&&patMessageList.map((item, index) => {
            return (
              item.readFlag === "N" ? <Item key={index} onClick={() => this.gotoSatisfactionSurvey(item)} thumb={<img src={xiaoxi} alt="消息"></img>} arrow={item.messageTypeCode === "02" ? "horizontal" : ""}>
                {item.title} <Brief>{item.note}</Brief>
              </Item> : ""
            )
          })}
        </List>
        <Card className="h-one-touch-call">
          <Card.Header
            title={<div className="card-header-icon">
              <div></div>
              一键呼叫
            </div>}
          />
          <Card.Body>
            <div>
              {contractDoctorData&&contractDoctorData.length > 0 ? contractDoctorData.map((item, index) => {
                let imgPath = item.signDoctorTypeCode === "01" ? quankeyisheng : (item.signDoctorTypeCode === "02" ? zhuankeyisheng : (item.signDoctorTypeCode === "03" ? hulirenyuan : shegong));
                return (<span key={index}
                  onClick={() => this.oneTouchCallClick(item)}
                  style={{width: "25%", display: "inline-block", textAlign: "center", cursor: "pointer"}}>
                  <Flex direction="column">
                    <Flex.Item>
                      {+item.msgCount > 0 ? (
                        <Badge text={item.msgCount}>
                          <img alt="" src={imgPath} /> 
                          {/* <i className={"iconfont " + icon}></i> */}
                        </Badge>
                      ) : (
                        <img alt="" src={imgPath} /> 
                        // <i className={"iconfont " + icon}></i>
                      )}
                      {/* <img alt="" src={item.icon} /> */}
                    </Flex.Item>
                    <Flex.Item className="item-title">{item.signDoctorTypeDesc}<div className="it-name" style={{display: item.signDoctorTypeCode === "01" ? "block" : "none"}}>{item.doctorName}</div></Flex.Item>
                  </Flex>
                </span>)
              }) : <div className="record-nodata"><img src={noDoc} alt="" /><span>暂无签约医生</span></div>}
            </div>
          </Card.Body>
        </Card>
        <Card className="h-wave-diagram">
          <Card.Header
            title={<div className="card-header-icon">
              <div></div>
              波动图
            </div>}
            extra={<div className="hwd-head-extra">
              {latelyData&&latelyData.map((item, index) => {
                return <span key={index} className={latelyActive === item.value ? "active" : ""} onClick={() => this.handleLatelyBtnClick(item.value)}>{item.label}</span>
              })}  
            </div>}
          />
          <Card.Body>
            <div>
              <Chart padding={40} width="100%" data={this.filterChartData()} defs={defs} pixelRatio={window.devicePixelRatio * 2} >
                <Axis dataKey="date" />
                <Axis dataKey="value" label={{ fontSize: 12 }} />
                {Util.uniqArr(patientVitalSignsRecord&&patientVitalSignsRecord.data instanceof Array ? 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&&patientVitalSignsRecord.data instanceof Array ? patientVitalSignsRecord.data : [], "collectDate") ? Util.uniqArr(patientVitalSignsRecord&&patientVitalSignsRecord.data instanceof Array ? 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>
              {/* <span className="chart-normal-range">{usualValueFrom + unit + "-"+usualValueTo + unit}</span> */}
            </div>
          </Card.Body>
        </Card>
        <div className="h-other">
          {/* <List>
            {gridData&&gridData.map((item, index) => {
              return (
                <Item key={index} onClick={() => this.handleGridChildClick(item)} thumb={<img src={item.icon} alt=""></img>} arrow="horizontal">
                  {item.text}
                </Item>
              )
            })}
          </List> */}
          <Grid data={gridData}
            columnNum={3}
            onClick={this.handleGridChildClick}
            renderItem={dataItem => (
              <div className="grid-cont border-bottom-after">
                <img src={dataItem.icon} alt="" />
                {/* <i className={"iconfont " + dataItem.icon}></i> */}
                <div style={{ color: '#888', fontSize: '14px', marginTop: '4px' }}>
                  <span>{dataItem.text}</span>
                </div>
              </div>
            )}
          />
        </div>
      </div>
    )
  }
}