// 录入体征数据 
import React from 'react';
import { createForm } from 'rc-form';
import {InputItem, Button, List, DatePicker, Toast} from 'antd-mobile';
import { $http } from "containers/config/https";
import './style/index.less';
import Moment from 'moment';

class EnterPhysicalData extends React.Component {
  constructor({history}) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    this.state = {
      userData,
      formElement: [],
      errorInfo: {}
    };
    this.history = history;
  }

  componentDidMount() {
    this.getFormElement();
  }

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

  // 获取生命体征类型
  getFormElement = () => {
    let data = {
			params: [{}]
		}
		$http.post("urlS", this, {
			code: "03070056",
      data: data,
      namespace: "HIS",
			success: function(res) {
				if (+res.errorCode === 0) {
          this.setState({formElement: res.result});
				} else {
          this.setState({formElement: []});
				}
			}
		});
  }

  // 处理提交数据
  processingSubmissionData = (values) => {
    let formElement = [...this.state.formElement];
    for(var i = 0; i < formElement.length; i++) {
      for(var j in values) {
        if (formElement[i].code === j) {
          formElement[i].vitalSignValue = values[j];
          formElement[i].vitalSignTypeID = formElement[i].id;
        }
      }
    }
    return formElement;
  }

  // 提交
  handleSubmit = () => {
    let {userData} = this.state;
    let isSave = false;
    this.props.form.validateFields((error, values) => {
      if (!error) {
        for(var key in values) {
          if (key !== "patBirthDate"&&values[key]) {
            isSave = true;
            break;
          }
        }
        if (isSave) {
          let data = {
            params: [{
              userCode: "000009",
              healthReocrdID: "",
              subData: this.processingSubmissionData(values),
              mainData: {
                patID: userData&&userData.hisPatID ? userData.hisPatID : "",
                sourceCode: "01",
                collectDate: values.patBirthDate ? Moment(values.patBirthDate).format("YYYY-MM-DD") : "",
                collectTime: values.patBirthDate ? Moment(values.patBirthDate).format("HH:mm:ss") : "",
              }
            }]
          }
          $http.post("urlS", this, {
            code: "03070029",
            data: data,
            namespace: "HIS",
            success: function(res) {
              Toast.info(res.errorMessage, 3, () => {}, false)
              if (+res.errorCode === 0) {
                this.history.goBack();
              }
            }
          });
        } else {
          Toast.info("请录入至少一个体征信息。", 3, () => {}, false);
        }
      } else {
        Toast.info("请完善相关信息。", 3, () => {}, false);
      }
    });
  }

  // 监听文本框变化
  handleVerification = (item, e) => {
    let {errorInfo} = this.state;
    if (item.usualValueFrom&&item.usualValueTo) {
      if (!((+e >= item.usualValueFrom)&&(+e <= item.usualValueTo))) { // 数据不正常
        errorInfo[item.code] = true;
        this.setState({errorInfo});
      } else {
        errorInfo[item.code] = false;
        this.setState({errorInfo});
      }
    }
  }

  render() {
    let {formElement, errorInfo} = this.state;
    const { getFieldProps } = this.props.form;
    return (
      <div className="enter-physical-data">
        <List>
          <form>
            <DatePicker
              {...getFieldProps('patBirthDate', {
                initialValue: new Date(),
              })}
            >
              <List.Item arrow="horizontal">时间</List.Item>
            </DatePicker>
            {formElement&&formElement.map((item, index) => {
              return (
                <InputItem key={index} type="digit"
                  {...getFieldProps(item.code, {
                    onChange: (e) => this.handleVerification(item, e),
                    initialValue: undefined,
                  })}
                  extra={item.unit}
                  className={errorInfo[item.code] ? "error-style" : ""}
                >{item.descripts}</InputItem>
              )
            })}
          </form>
        </List>
        <div className="epd-btn">
          <Button type="primary" onClick={this.handleSubmit}>
            提交
          </Button>
          <p>提示：体征数据字体颜色为红色则表示体征数据异常，反之为正常数据。</p>
        </div>
      </div>
    )
  }
};
const EnterPhysicalDataForm = createForm()(EnterPhysicalData);
export default EnterPhysicalDataForm;
