<template>
  <div id="today_panel">

    <div v-loading="loading"
         element-loading-text="拼命加载中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">

      <div class="grid">
        <div class="list">
          <ul>
            <li @click="menuClick(1)">
              <img src="@/assets/record/2.png"/>
              <p>透析处方</p>
            </li>
            <li @click="menuClick(2)">
              <img src="@/assets/record/3.png"/>
              <p>接诊评估</p>
            </li>
            <li @click="menuClick(3)">
              <img src="@/assets/record/4.png"/>
              <p>透前评估</p>
            </li>
            <li style="position: relative;" @click="menuClick(4)">
              <img src="@/assets/record/5.png"/>
              <span class="redpoint" v-if="getUnReadNum()">{{getUnReadNum()}}</span>
              <p>临时医嘱</p>
            </li>
            <li @click="menuClick(5)">
              <img src="@/assets/record/6.png"/>
              <p>双人核对</p>
            </li>
          </ul>
        </div>
        <div class="list">
          <ul>
            <li @click="menuClick(0)">
              <img src="@/assets/record/1.png"/>
              <p>透析上机</p>
            </li>
            <li @click="menuClick(6)">
              <img src="@/assets/record/7.png"/>
              <p>透析监测</p>
            </li>
            <li @click="menuClick(7)">
              <img src="@/assets/record/8.png"/>
              <p>透析下机</p>
            </li>
            <li @click="menuClick(8)">
              <img src="@/assets/record/9.png"/>
              <p>透后评估</p>
            </li>
            <li @click="menuClick(9)">
              <img src="@/assets/record/10.png"/>
              <p>治疗小结</p>
            </li>
          </ul>
        </div>
      </div>
      <div class="blueBorder"></div>

      <details-info title="基本信息" :patient="patient"
                    :device_number="getDeviceNumber()"
                    :step_data="stepData"></details-info>

      <div class="blueBorder"></div>

      <dialysis-prescription id="prescription" :prescription="prescription" :solution="solution" title="透析处方"
                             :device_number_map="device_map"></dialysis-prescription>


      <div class="blueBorder"></div>


    <accepts-assessment id="accepts_assessment" :record="receiver_treatment_access" title="接诊评估"></accepts-assessment>
    </div>


    <div class="blueBorder"></div>

    <assessment-before id="assessment_before" :record="predialysis_evaluation" ref="assessment_before"
                       title="透前评估" :dry_weights="dryWeight"
                       :last_predialysis="last_predialysis_evaluation"></assessment-before>

    <div class="blueBorder"></div>

    <stat-order id="stat_order" ref="stat_order" title="临时医嘱" :doctor_map="admin_user_map"
                :advice_groups="advice_groups"></stat-order>


    <div class="blueBorder"></div>

    <dialysis-computer id="dialysis_computer" ref="dialysis_computer" title="透析上机 " :record="dialysis_order"
                       :admin_map="admin_user_map" :device_number_map="device_number_map"></dialysis-computer>


    <div class="blueBorder"></div>

    <double-check id="double_check" ref="double_check" title="双人核对 " :record="double_check"></double-check>


    <div class="blueBorder"></div>

    <dialysis-monitoring id="monitoring" ref="monitoring" title="透析监测"></dialysis-monitoring>


    <div class="blueBorder"></div>

    <dialysis-off id="dialysis_off" ref="dialysis_off" title="透析下机 " :record="dialysis_order"
                  :admin_map="admin_user_map"></dialysis-off>


    <div class="blueBorder"></div>


    <assessment-after
      id="assessment_after"
      ref="assessment_after"
      title="透后评估"
      :record="assessment_after_dislysis"
    ></assessment-after>

    <div class="blueBorder"></div>

    <treatment-of id="treatment_of" ref="treatment_of" title="治疗小结" :record="treatment_summary"></treatment-of>

    <van-popup title="透析处方" v-model="menuList[1].showPopup" :overlay="true" :close-on-click-overlay="false">
      <prescription-dialog :patient_prop="patient" :solution_prop="solution" :machines_prop="devices" :config="config"
                           :prescription_prop="prescription" @finish="closePrescriptionDialog" :operators="operators"
                           :types="goodTypes" :info="goodInfos" :status="status" :targetAdvices="longAdvices"
                           :waitUploadAdvices="waitUploadAdvices" :is_open="is_open"
                           @close="closePrescriptionDialog" @prescription="prescriptionFunc"
                           :admin_users_prop="admin_users"
                           :predialysis="predialysis_evaluation"
                           :last_predialysis="last_predialysis_evaluation"
                           :record="assessment_after_dislysis"
                           :last_record="last_assessment_after_dislysis"
                           :last_prescription="last_prescription"
                           :dry_weight="dryWeight"

                           :schedual="schedual"
                           @longSolution="longSolutionFunc" ref="prescription_dialog"></prescription-dialog>

    </van-popup>

    <van-popup
      title="接诊评估"
      v-model="menuList[2].showPopup"
      :overlay="true"
      :close-on-click-overlay="false"
    >
      <accepts-dialog
        :accepts="receiver_treatment_access"
        :patient_prop="patient"
        @finish="closeAcceptsAssessment"
        @close="closeAcceptsAssessment"
      ></accepts-dialog>
    </van-popup>


    <van-popup title="透前评估" v-model="menuList[3].showPopup" :overlay="true" :close-on-click-overlay="false">
      <assessment-dialog :predialysis="predialysis_evaluation" :last_predialysis="last_predialysis_evaluation"
                         :dry_weight="dryWeight"
                         :patient_prop="patient" @evaluation="update_evaluation" @close="closeAssessmentBefore"
                         :admin_users_prop="admin_users"
                         ref="assessment_dialog" @weight_update="weightFunc"></assessment-dialog>
    </van-popup>


    <van-popup
      title="临时医嘱"
      v-model="menuList[4].showPopup"
      :overlay="true"
      :close-on-click-overlay="false"
    >
      <orders-dialog
        :patient_prop="patient"
        :advice_groups="advice_groups"
        :advice_list_prop="doctor_advices"
        :admin_users_prop="admin_users"
        :special_premission="special_premission"
        @orderDialog="closeStatOrder"
        ref="orders_dialog"
      ></orders-dialog>
    </van-popup>

    <van-popup
      title="双人核对"
      v-model="menuList[5].showPopup"
      :overlay="true"
      :close-on-click-overlay="false"
    >
      <double-dialog
        :patient_prop="patient"
        :record="double_check"
        :admin_users_prop="admin_users"
        @did_update="closeDoubleCheck"
        @close="closeDoubleCheck"
      ></double-dialog>
    </van-popup>

    <van-popup
      title="透析上机"
      v-model="menuList[0].showPopup"
      :overlay="true"
      :close-on-click-overlay="false"
    >
      <computer-dialog
        :schedule="schedual"
        :patient_prop="patient"
        :record="dialysis_order"
        :admins="admin_users"
        :device_numbers="device_numbers"
        :admin_map="admin_user_map"
        :special_premission="special_premission"
        :device_number_map="device_number_map"
        @did_start="closeDialysisComputer"
        @did_add_monitor="didAddMonitor"
        @close="closeDialysisComputerclose"
        ref="computer_dialog"
      ></computer-dialog>
    </van-popup>

    <van-popup
      title="透析监测"
      v-model="menuList[6].showPopup"
      :overlay="true"
      :close-on-click-overlay="false"
    >
      <monit-dialog
        :monitor_records="monitor_records"
        :last_monitor_record="last_monitor_record"
        :patient="patient"
        :order="dialysis_order"
        @did_add_monitor="didAddMonitor"
        @did_edit_monitor="didEditMonitor"
        @did_delete_monitor="didDelMonitor"
        @close="closeMonitoring"
        ref="monit_dialog"
      ></monit-dialog>
    </van-popup>

    <van-popup title="透析下机" v-model="menuList[7].showPopup" :overlay="true" :close-on-click-overlay="false">
      <plane-dialog :patient_prop="patient" :record="dialysis_order" :last_monitor_record="last_monitor_record"
                    :admins="admin_users" :admin_map="admin_user_map"
                    :special_premission="special_premission" :prescription_prop="prescription"
                    @did_off="closeDialysisOff" @close="closeDialysisOffclose" ref="plane_dialog"></plane-dialog>
    </van-popup>

    <van-popup
      title="透后评估"
      v-model="menuList[8].showPopup"
      :overlay="true"
      :close-on-click-overlay="false"
    >
      <thoroug-dialog
        :patient_prop="patient"
        :record="assessment_after_dislysis"
        :last_record="last_assessment_after_dislysis"
        @did_update="closeAssessmentAfter"
        @close="closeAssessmentAfter"
        ref="thoroug_dialog"
      ></thoroug-dialog>
    </van-popup>


    <van-popup title="治疗小结" v-model="menuList[9].showPopup" :overlay="true" :close-on-click-overlay="false">
      <treatment-dialog :patient_prop="patient" :record="treatment_summary" @did_update="updateTreatmentOf"
                        @close="closeTreatmentOf" ref="treatment_dialog"></treatment-dialog>

    </van-popup>


    <el-button
      class="goTop"
      v-show="goTopShow"
      @click="goTop"
      type="primary"
      icon="el-icon-arrow-up"
      circle
      style="position:fixed;right:50px;bottom:50px;"
    ></el-button>
  </div>
</template>
<script>
import DetailsInfo from './detailsInfo'
import DialysisPrescription from './dialysisPrescription'
import PastData from './pastData'
import AcceptsAssessment from './acceptsAssessment'
import AssessmentBefore from './assessmentBefore'
import StatOrder from './statOrder'
import DialysisComputer from './dialysisComputer'
import DoubleCheck from './doubleCheck'
import DialysisMonitoring from './dialysisMonitoring'
import DialysisOff from './dialysisOff'
import AssessmentAfter from './assessmentAfter'
import TreatmentOf from './treatmentOf'
import OperationStaff from './operationStaff'

import LongDialog from '../dialog/LongDialog'
import PrescriptionDialog from '../dialog/PrescriptionDialog'
import AssessmentDialog from '../dialog/AssessmentDialog'
import ThorougDialog from '../dialog/ThorougDialog'
import AcceptsDialog from '../dialog/AcceptsDialog'
import PlaneDialog from '../dialog/PlaneDialog'
import TreatmentDialog from '../dialog/TreatmentDialog'
import DoubleDialog from '../dialog/DoubleDialog'
import OrdersDialog from '../dialog/OrdersDialog'
import MonitDialog from '../dialog/MonitDialog'
import ComputerDialog from '../dialog/ComputerDialog'

import {CreateGroupAdvice, dialysisGlobalConfig, getDialysisRecord} from '@/api/dialysis'
import {GetRemindLongAdvice} from '@/api/advice'

import {parseTime} from '@/utils'

  export default {
    name: 'TodayTab',
    components: {
      DetailsInfo,
      DialysisPrescription,
      PastData,
      AcceptsAssessment,
      AssessmentBefore,
      StatOrder,
      DialysisComputer,
      DoubleCheck,
      DialysisMonitoring,
      DialysisOff,
      AssessmentAfter,
      TreatmentOf,
      OperationStaff,
      LongDialog,
      PrescriptionDialog,
      AssessmentDialog,
      ThorougDialog,
      AcceptsDialog,
      PlaneDialog,
      TreatmentDialog,
      DoubleDialog,
      OrdersDialog,
      MonitDialog,
      ComputerDialog
    },
    data () {
      return {
        loading: true,
        // show_fixed_nav: false,
        patient_id: 0,
        date: 0,
        menuList: [
          {value: '2', label: ' 透析处方', showPopup: false},
          {value: '3', label: ' 接诊评估', showPopup: false},
          {value: '4', label: ' 透前评估', showPopup: false},
          {value: '5', label: ' 临时医嘱', showPopup: false},
          {value: '6', label: ' 透析上机', showPopup: false},
          {value: '1', label: ' 双人核对', showPopup: false},
          {value: '7', label: ' 透析监测', showPopup: false},
          {value: '8', label: ' 透析下机', showPopup: false},
          {value: '9', label: ' 透后评估', showPopup: false},
          {value: '10', label: ' 治疗小结', showPopup: false}
        ],
        isPullData: 1,
        config: {}, // 库存自动扣减
        operators: [], // 操作人
        patient: {}, // 患者信息
        schedual: {}, // 患者排班信息
        prescription: {}, // 透析处方
        solution: {}, // 透析方案
        last_prescription:{},
        receiver_treatment_access: {}, // 接诊评估
        predialysis_evaluation: {}, // 透前评估
        last_predialysis_evaluation: {}, // 上次透前评估
        doctor_advices: [], // 临时医嘱
        advice_groups: [], // 对 doctor_advices 进行分组后的组列表，元素为 { group_no, start_time, advices:[advice object] }
        double_check: {}, // 双人核对
        assessment_after_dislysis: {}, // 透后评估
        last_assessment_after_dislysis: {}, // 上次透后评估
        treatment_summary: {}, // 治疗小结
        monitor_records: [], // 透析监测
        special_premission: [],
        last_monitor_record: {
          id: 0,
          operate_time: new Date().getTime(),
          sodium_concentration: '',
          dialysate_temperature: ''
        }, // 上一次透析的监测记录
        dialysis_order: {}, // 透析记录
        admin_users: [], // 系统用户列表
        devices: [], // 设备
        device_numbers: [], // 床位号
        admin_user_map: {}, // {user_id: admin_user object}
        device_map: {}, // {device_id: device}
        device_number_map: {}, // {device_number_id: device_number}
        scrollTop: '',
        goTopShow: false,
        goodTypes: [],
        goodInfos: [],
        dryWeight: {},

        longAdvices: [],
        waitUploadAdvices: [],
        is_open: 0,
        targetAdvices: [],
        status: '',
      }
    },
    computed: {
      stepData: function () {
        var steps = [
          {title: '透析处方', name: 'prescription', value: 0},
          {title: '接诊评估', name: 'accepts_assessment', value: 0},
          {title: '透前评估', name: 'assessment_before', value: 0},
          {title: '临时医嘱', name: 'stat_order', value: 0},
          {title: '双人核对', name: 'double_check', value: 0},
          {title: '透析上机', name: 'dialysis_computer', value: 0},
          {title: '透析监测', name: 'dialysis_monitoring', value: 0},
          {title: '透析下机', name: 'dialysis_off', value: 0},
          {title: '透后评估', name: 'assessment_after', value: 0},
          {title: '治疗小结', name: 'treatment_of', value: 0}
        ]

        if (!isNaN(this.prescription.id) && this.prescription.id > 0 && this.prescription.creater > 0) {
          steps[0].value = 1
        }
        if (
          !isNaN(this.receiver_treatment_access.id) &&
          this.receiver_treatment_access.id > 0
        ) {
          steps[1].value = 1
        }

        if (typeof this.predialysis_evaluation.id != 'undefined' && !isNaN(this.predialysis_evaluation.id) && this.predialysis_evaluation.id > 0 && this.predialysis_evaluation.creater > 0) {
          steps[2].value = 1
        }

        if (this.advice_groups.length > 0) {
          steps[3].value = 1
        }

        if (!isNaN(this.dialysis_order.id) && this.dialysis_order.id > 0) {
          steps[5].value = 1
          if (this.dialysis_order.stage == 2) {
            steps[7].value = 1
          }
        }
        if (
          !isNaN(this.double_check.creater) &&
          this.double_check.creater > 0 &&
          !isNaN(this.double_check.modifier) &&
          this.double_check.modifier > 0
      ) {
        steps[4].value = 1
      }
      if (this.monitor_records.length > 0) {
        steps[6].value = 1
      }
      if (
        !isNaN(this.assessment_after_dislysis.id) && this.assessment_after_dislysis.id > 0  && this.assessment_after_dislysis.creater > 0) {
        steps[8].value = 1
      }
      if (!isNaN(this.treatment_summary.id) && this.treatment_summary.id > 0) {
        steps[9].value = 1
      }

      return steps
    }
  },
  created () {
    var patient_id = this.$route.query.patient_id
    var date = this.$route.query.date
    this.patient_id = patient_id
    this.date = date
    this.requestDialysisRecord()
    this.requestLongAdvice()
    this.goTop()
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  watch: {
    doctor_advices: function () {
      this.$refs.stat_order.setAdvices(this.doctor_advices)
    },
    monitor_records: function () {
      this.$refs.monitoring.setRecords(this.monitor_records)
    },

    // $route: 'requestDialysisRecord'
  },
  methods: {
    // handleScroll: function() {
    //   var scrollTop =
    //     window.pageYOffset ||
    //     document.documentElement.scrollTop ||
    //     document.body.scrollTop;
    //   this.show_fixed_nav = scrollTop > 160;
    // },

    didAddMonitor (monitor) {
      this.monitor_records.push(monitor)
      this.monitor_records.sort((a, b) => b.operate_time - a.operate_time)
      this.monitor_records.reverse()
      this.$refs.monit_dialog.setRecords(this.monitor_records)
      this.last_monitor_record = monitor
    },

    didEditMonitor (monitor) {
      var mrl = this.monitor_records.length
      var monitor_index = -1
      for (let index = 0; index < mrl; index++) {
        if (this.monitor_records[index].id == monitor.id) {
          monitor_index = index
          break
        }
      }

      console.log(monitor)
      console.log(this.monitor_records[monitor_index])

      this.monitor_records[monitor_index].arterial_pressure =
          monitor.arterial_pressure
      this.monitor_records[monitor_index].blood_flow_volume =
          monitor.blood_flow_volume
      this.monitor_records[monitor_index].breathing_rate =
          monitor.breathing_rate
      this.monitor_records[monitor_index].dialysate_temperature =
          monitor.dialysate_temperature
      this.monitor_records[monitor_index].temperature =
          monitor.temperature
      this.monitor_records[monitor_index].diastolic_bp = monitor.diastolic_bp
      this.monitor_records[monitor_index].displacement_quantity =
          monitor.displacement_quantity
      this.monitor_records[monitor_index].dispose = monitor.dispose
      this.monitor_records[monitor_index].ktv = monitor.ktv
      this.monitor_records[monitor_index].monitor_date = monitor.monitor_date
      this.monitor_records[monitor_index].monitoring_nurse =
          monitor.monitoring_nurse
      this.monitor_records[monitor_index].operate_time = monitor.operate_time
      this.monitor_records[monitor_index].pulse_frequency =
          monitor.pulse_frequency
      this.monitor_records[monitor_index].replacement_rate =
          monitor.replacement_rate
      this.monitor_records[monitor_index].result = monitor.result
      this.monitor_records[monitor_index].sodium_concentration =
          monitor.sodium_concentration
      this.monitor_records[monitor_index].symptom = monitor.symptom
      this.monitor_records[monitor_index].systolic_bp = monitor.systolic_bp
      this.monitor_records[monitor_index].transmembrane_pressure =
          monitor.transmembrane_pressure
      this.monitor_records[monitor_index].ultrafiltration_rate =
          monitor.ultrafiltration_rate
      this.monitor_records[monitor_index].ultrafiltration_volume =
          monitor.ultrafiltration_volume
      this.monitor_records[monitor_index].venous_pressure =
          monitor.venous_pressure
      this.monitor_records[monitor_index].diastolic_blood_pressure =
          monitor.diastolic_blood_pressure
      this.monitor_records[monitor_index].systolic_blood_pressure =
          monitor.systolic_blood_pressure
      this.monitor_records[monitor_index].conductivity =
          monitor.conductivity
      this.monitor_records[monitor_index].displacement_flow_quantity =
          monitor.displacement_flow_quantity
      this.monitor_records.sort((a, b) => a.operate_time - b.operate_time)

      // if (monitor_index >= 0) {
      //   var record = this.monitor_records[monitor_index]
      //
      //   this.monitor_records.splice(monitor_index, 1)
      //   if(this.monitor_records.length == 0){
      //     this.monitor_records.splice(0, 0, monitor)
      //   }else {
      //
      //     for (let index = 0; index < this.monitor_records.length; index++) {
      //       const temp = this.monitor_records[index];
      //       if (temp.operate_time <= monitor.operate_time) {
      //         this.monitor_records.splice(index, 0, monitor)
      //         break
      //       }
      //     }
      //   }
      // }
    },
    didDelMonitor (record_id) {
      var mrl = this.monitor_records.length
      for (let index = 0; index < mrl; index++) {
        if (this.monitor_records[index].id == record_id) {
          this.monitor_records.splice(index, 1)
          break
        }
      }
    },

    menuClick: function (popupIndex) {
      this.index = popupIndex
      if (popupIndex >= 0) {
        this.menuList[popupIndex].showPopup = true
      }
      if (
        popupIndex == 1 &&
          typeof this.$refs.prescription_dialog !== 'undefined'
      ) {
        this.$refs.prescription_dialog.open()
      } else if (
        popupIndex == 3 &&
          typeof this.$refs.assessment_dialog !== 'undefined'
      ) {
        this.$refs.assessment_dialog.open()
      } else if (
        popupIndex == 4 &&
          typeof this.$refs.orders_dialog !== 'undefined'
      ) {
        // this.$refs.orders_dialog.open();
      } else if (
        popupIndex == 0 &&
          typeof this.$refs.computer_dialog !== 'undefined'
      ) {
        this.$refs.computer_dialog.open()
      } else if (
        popupIndex == 6 &&
          typeof this.$refs.monit_dialog !== 'undefined'
      ) {
        this.$refs.monit_dialog.open()
      } else if (
        popupIndex == 7 &&
          typeof this.$refs.plane_dialog !== 'undefined'
      ) {
        this.$refs.plane_dialog.open()
      } else if (
        popupIndex == 8 &&
          typeof this.$refs.thoroug_dialog !== 'undefined'
      ) {
        this.$refs.thoroug_dialog.open()
      } else if (
        popupIndex == 9 &&
          typeof this.$refs.treatment_dialog !== 'undefined'
      ) {
        this.$refs.treatment_dialog.open()
      }
    },
    popupDidHide: function (popupIndex) {
      this.index = -1
    },
    closeDialog (index) {
      this.index = -1
      this.menuList[index].showPopup = false
    },
    refresh () {
      var dateStr = parseTime(this.$route.query.date, '{y}-{m}-{d}')
      var params = {
        patient_id: this.$route.query.patient_id,
        date: dateStr
      }
      getDialysisRecord(params).then(rs => {
        var resp = rs.data
        console.log(resp)
        if (resp.state == 1) {
          var patient = resp.data.patient // 患者信息
          var schedual = resp.data.schedual // 患者排班信息
          var prescription = resp.data.prescription // 透析处方
          var solution = resp.data.solution // 透析方案
          var receiver_treatment_access = resp.data.receiver_treatment_access // 接诊评估
          var predialysis_evaluation = resp.data.predialysis_evaluation // 透前评估
          var doctor_advices = resp.data.doctor_advices // 临时医嘱
          this.dryWeight = resp.data.dry_weight

          for (let i = 0; i < doctor_advices.length; i++) {
            doctor_advices[i]['is_selected'] = 0
          }
          console.log(doctor_advices)

          var double_check = resp.data.double_check // 双人核对
          var assessment_after_dislysis = resp.data.assessment_after_dislysis // 透后评估
          var treatment_summary = resp.data.treatment_summary // 治疗小结
          var monitor_records = resp.data.monitor_records // 透析监测
          var dialysis_order = resp.data.dialysis_order // 透析记录
          var operators = resp.data.operators // 操作人

          var last_predialysis_evaluation =
              resp.data.last_predialysis_evaluation // 上一次透前评估
          var last_assessment_after_dislysis =
              resp.data.last_assessment_after_dislysis // 上一次透前评估
          var last_monitor_record = resp.data.last_monitor_record

          this.patient = patient
          this.schedual = schedual == null ? {} : schedual
          this.prescription = prescription == null ? {id: ''} : prescription
          this.solution = solution == null ? {id: ''} : solution
          this.receiver_treatment_access =
              receiver_treatment_access == null
                ? {id: ''}
                : receiver_treatment_access
          this.predialysis_evaluation =
              predialysis_evaluation == null ? {} : predialysis_evaluation
          this.last_predialysis_evaluation =
              last_predialysis_evaluation == null
                ? {}
                : last_predialysis_evaluation

          this.doctor_advices = doctor_advices == null ? [] : doctor_advices

          if (this.doctor_advices.length > 0) {
            var group = this.newAdviceGroupObject()
            var initGroupBlock = function (group, advice) {
              group.group_no = advice.groupno
              // group.start_time = advice.start_time
              // group.advice_doctor = advice.advice_doctor
              // group.exec_staff = advice.execution_staff
              // group.exec_time = advice.execution_time
              // group.checker = advice.checker
            }
            for (let index = 0; index < this.doctor_advices.length; index++) {
              const advice = this.doctor_advices[index]
              if (advice.groupno == 0) {
                // 老版本的医嘱没有分组的概念，所以这一个 if 是解决这个问题的，将每个无分组的医嘱各自归为一组
                if (advice.parent_id > 0) {
                  if (this.advice_groups.length > 0) {
                    var parent_group = this.advice_groups[
                      this.advice_groups.length - 1
                    ]
                    if (parent_group.advices.length > 0) {
                      if (parent_group.advices[0].id == advice.parent_id) {
                        parent_group.advices.push(advice)
                      }
                    }
                  }
                  continue
                } else {
                  if (group.group_no > 0) {
                    this.advice_groups.push(group)
                    group = this.newAdviceGroupObject()
                  }

                  initGroupBlock(group, advice)
                  group.advices.push(advice)
                  this.advice_groups.push(group)
                  group = this.newAdviceGroupObject()
                  continue
                }
              }

              if (group.group_no > 0 && group.group_no != advice.groupno) {
                this.advice_groups.push(group)
                group = this.newAdviceGroupObject()
              }
              if (group.group_no == 0) {
                initGroupBlock(group, advice)
              }
              if (group.group_no == advice.groupno) {
                group.advices.push(advice)
              }
            }
            if (group.group_no > 0) {
              // 上述的算法会导致最后一组没有加到advice_groups，这里要手动加上
              this.advice_groups.push(group)
            }

            // console.log(this.advice_groups)
          }

          this.double_check = double_check == null ? {id: ''} : double_check
          this.assessment_after_dislysis = assessment_after_dislysis == null ? {id: ''} : assessment_after_dislysis
          this.last_assessment_after_dislysis =
              last_assessment_after_dislysis == null
                ? {id: ''}
                : last_assessment_after_dislysis
          this.treatment_summary =
              treatment_summary == null ? {id: ''} : treatment_summary
          this.monitor_records = monitor_records == null ? [] : monitor_records
          this.last_monitor_record =
              last_monitor_record == null
                ? this.last_monitor_record
                : last_monitor_record
          this.dialysis_order =
              dialysis_order == null ? {id: ''} : dialysis_order
          this.operators = operators
          this.$refs.stat_order.setAdvices(this.doctor_advices)
          this.$refs.monitoring.setRecords(this.monitor_records)

          this.title = patient.name

          dialysisGlobalConfig().then(rs => {
            var res = rs.data
            if (res.state == 1) {
              // console.log(res)
              // this.$refs.detail_menu.setGlobalConfig(res.data)
              this.admin_users = res.data.admin_users
              this.devices = res.data.devices
              this.device_numbers = res.data.device_numbers

              var device_map = {}
              for (let index = 0; index < this.devices.length; index++) {
                const device = this.devices[index]
                device_map[device.id] = device
              }
              this.device_map = device_map

              var admin_map = {}
              for (let index = 0; index < this.admin_users.length; index++) {
                const admin = this.admin_users[index]
                admin_map[admin.id] = admin
              }
              this.admin_user_map = admin_map

              var device_number_map = {}
              for (let index = 0; index < this.device_numbers.length; index++) {
                const device_number = this.device_numbers[index]
                device_number_map[device_number.id] = device_number
              }
              this.device_number_map = device_number_map
            }
            this.loading = false
          })
        } else {
          this.$toast({
            message: resp.msg
          })
          this.loading = false
        }
      })
    },
    weightFunc (val) {
      this.dryWeight = val


    },
    requestDialysisRecord () {
      var dateStr = parseTime(this.date, '{y}-{m}-{d}')
      var params = {
        patient_id: this.patient_id,
        date: dateStr
      }
      this.advice_groups = []
      this.doctor_advices = []

      getDialysisRecord(params).then(rs => {
        var resp = rs.data
        console.log(resp)

        if (resp.state == 1) {
          var waitstoredata = this.$store.getters.waitscheduals
          var waitscheduals = waitstoredata.waitscheduals
          var storedata = this.$store.getters.scheduals
          var scheduals = storedata.scheduals





          var patient = resp.data.patient // 患者信息
          var schedual = resp.data.schedual // 患者排班信息
          var prescription = resp.data.prescription // 透析处方
          var solution = resp.data.solution // 透析方案
          var receiver_treatment_access = resp.data.receiver_treatment_access // 接诊评估
          var predialysis_evaluation = resp.data.predialysis_evaluation // 透前评估
          var doctor_advices = resp.data.doctor_advices // 临时医嘱
          var last_prescription = resp.data.last_prescription

          this.dryWeight = resp.data.dry_weight

          if (prescription == null || prescription.creater == 0) {
            this.isPullData = 1
          } else {
            this.isPullData = 2
          }

          this.goodInfos = resp.data.goodInfos

          for (let i = 0; i < doctor_advices.length; i++) {
            doctor_advices[i]['is_selected'] = 0
          }
          console.log(doctor_advices)

          var double_check = resp.data.double_check // 双人核对
          var assessment_after_dislysis = resp.data.assessment_after_dislysis // 透后评估
          var treatment_summary = resp.data.treatment_summary // 治疗小结
          var monitor_records = resp.data.monitor_records // 透析监测
          var dialysis_order = resp.data.dialysis_order // 透析记录
          var operators = resp.data.operators // 操作人

          var special_premission = resp.data.special_premission // 特殊权限

          var config = resp.data.config // 库存自动扣减配置

          var types = resp.data.types // 所有系统库存商品类型

          var last_predialysis_evaluation = resp.data.last_predialysis_evaluation // 上一次透前评估
          var last_assessment_after_dislysis = resp.data.last_assessment_after_dislysis // 上一次透前评估
          var last_monitor_record = resp.data.last_monitor_record

          if (Object.keys(waitstoredata).length > 0) {
            for (let index = 0; index < waitscheduals.length; index++) {
              if (waitscheduals[index].patient_id == patient.id) {
                waitscheduals[index].patient = patient
                waitscheduals[index].assessment_before_dislysis = predialysis_evaluation
                waitscheduals[index].prescription = prescription
                waitscheduals[index].doctor_advice = doctor_advices
                waitscheduals[index].dialysis_order = dialysis_order
              }
            }
            this.$store.dispatch('SetWaitScheduals', {waitscheduals: waitscheduals})
          }

          if (Object.keys(storedata).length > 0) {
            for (let index = 0; index < scheduals.length; index++) {
              if (scheduals[index].patient_id == patient.id) {
                scheduals[index].patient = patient
                scheduals[index].assessment_before_dislysis = predialysis_evaluation
                scheduals[index].prescription = prescription
                scheduals[index].doctor_advice = doctor_advices
                scheduals[index].dialysis_order = dialysis_order
              }
            }
            this.$store.dispatch('SetScheduals', {scheduals: scheduals})
          }

          this.patient = patient
          this.schedual = schedual == null ? {} : schedual
          this.prescription = prescription == null ? {id: ''} : prescription
          this.solution = solution == null ? {id: ''} : solution
          this.last_prescription = last_prescription == null ? {id: ''} : last_prescription



          this.receiver_treatment_access =
              receiver_treatment_access == null
                ? {id: ''}
                : receiver_treatment_access
          this.predialysis_evaluation =
              predialysis_evaluation == null ? {} : predialysis_evaluation
          this.last_predialysis_evaluation =
              last_predialysis_evaluation == null
                ? {}
                : last_predialysis_evaluation

          this.doctor_advices = doctor_advices == null ? [] : doctor_advices
          this.special_premission = special_premission
          this.config = config
          this.goodTypes = types


          if (this.doctor_advices.length > 0) {
            var group = this.newAdviceGroupObject()
            var initGroupBlock = function (group, advice) {
              group.group_no = advice.groupno
              // group.start_time = advice.start_time
              // group.advice_doctor = advice.advice_doctor
              // group.exec_staff = advice.execution_staff
              // group.exec_time = advice.execution_time
              // group.checker = advice.checker
            }
            for (let index = 0; index < this.doctor_advices.length; index++) {
              const advice = this.doctor_advices[index]
              if (advice.groupno == 0) {
                // 老版本的医嘱没有分组的概念，所以这一个 if 是解决这个问题的，将每个无分组的医嘱各自归为一组
                if (advice.parent_id > 0) {
                  if (this.advice_groups.length > 0) {
                    var parent_group = this.advice_groups[
                      this.advice_groups.length - 1
                    ]
                    if (parent_group.advices.length > 0) {
                      if (parent_group.advices[0].id == advice.parent_id) {
                        parent_group.advices.push(advice)
                      }
                    }
                  }
                  continue
                } else {
                  if (group.group_no > 0) {
                    this.advice_groups.push(group)
                    group = this.newAdviceGroupObject()
                  }

                  initGroupBlock(group, advice)
                  group.advices.push(advice)
                  this.advice_groups.push(group)
                  group = this.newAdviceGroupObject()
                  continue
                }
              }

              if (group.group_no > 0 && group.group_no != advice.groupno) {
                this.advice_groups.push(group)
                group = this.newAdviceGroupObject()
              }
              if (group.group_no == 0) {
                initGroupBlock(group, advice)
              }
              if (group.group_no == advice.groupno) {
                group.advices.push(advice)
              }
            }
            if (group.group_no > 0) {
              // 上述的算法会导致最后一组没有加到advice_groups，这里要手动加上
              this.advice_groups.push(group)
            }

            // console.log(this.advice_groups)
          }

          this.double_check = double_check == null ? {id: ''} : double_check
          this.assessment_after_dislysis =
              assessment_after_dislysis == null
                ? {id: ''}
                : assessment_after_dislysis
          this.last_assessment_after_dislysis =
              last_assessment_after_dislysis == null
                ? {id: ''}
                : last_assessment_after_dislysis
          this.treatment_summary =
              treatment_summary == null ? {id: ''} : treatment_summary
          this.monitor_records = monitor_records == null ? [] : monitor_records
          this.last_monitor_record =
              last_monitor_record == null
                ? this.last_monitor_record
                : last_monitor_record
          this.dialysis_order =
              dialysis_order == null ? {id: ''} : dialysis_order
          this.operators = operators
          this.$refs.stat_order.setAdvices(this.doctor_advices)
          this.$refs.monitoring.setRecords(this.monitor_records)

          this.title = patient.name

          dialysisGlobalConfig().then(rs => {
            var res = rs.data
            if (res.state == 1) {
              // console.log(res)
              // this.$refs.detail_menu.setGlobalConfig(res.data)
              this.admin_users = res.data.admin_users
              this.devices = res.data.devices
              this.device_numbers = res.data.device_numbers

              var device_map = {}
              for (let index = 0; index < this.devices.length; index++) {
                const device = this.devices[index]
                device_map[device.id] = device
              }
              this.device_map = device_map

              var admin_map = {}
              for (let index = 0; index < this.admin_users.length; index++) {
                const admin = this.admin_users[index]
                admin_map[admin.id] = admin
              }
              this.admin_user_map = admin_map

              var device_number_map = {}
              for (let index = 0; index < this.device_numbers.length; index++) {
                const device_number = this.device_numbers[index]
                device_number_map[device_number.id] = device_number
              }
              this.device_number_map = device_number_map
            }
            this.loading = false
          })
        } else {
          this.$toast({
            message: resp.msg
          })
          this.loading = false
        }
      })
    },
    requestLongAdvice () {
      var dateStr = parseTime(this.date, '{y}-{m}-{d}')

      var params = {
        id: this.patient_id
      }
      GetRemindLongAdvice(params).then(rs => {
        var resp = rs.data
        if (resp.state == 1) {
          var status = parseInt(resp.data.status)
          this.status = status

          switch (status) {
            case 2:
              var totalAdvice = resp.data.advices
              var longAdvicesTwo = resp.data.advices_two
              var waitUploadAdvices = []
              for (let i = 0; i < totalAdvice.length; i++) {
                totalAdvice[i]['isCheck'] = 1
              }

              for (let i = 0; i < totalAdvice.length; i++) {
                for (let a = 0; a < longAdvicesTwo.length; a++) {
                  if (totalAdvice[i].template_id == longAdvicesTwo[a].template_id && totalAdvice[i].frequency_type == longAdvicesTwo[a].frequency_type) {
                    totalAdvice[i]['isCheck'] = 0
                  }
                }
              }

              for (let i = 0; i < totalAdvice.length; i++) {
                if (totalAdvice[i].isCheck == 1) {
                  waitUploadAdvices.push(totalAdvice[i])
                }
              }

              this.is_open = resp.data.is_open_remind
              this.longAdvices = totalAdvice
              this.waitUploadAdvices = waitUploadAdvices

              break
          }
        } else {

        }
      })
    },
    getNowFormatDate () {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },
    newAdviceGroupObject: function () {
      return Object.assign(
        {},
        {
          group_no: 0,
          // advice_doctor: 0,
          // start_time: 0,
          advices: []
          // exec_staff: 0,
          // exec_time: 0,
          // checker: 0,
        }
      )
    },
    adviceFunc: function () {

    },
    prescriptionFunc: function (val, advices) {
      this.prescription = val
      this.requestDialysisRecord()
      // if (advices.length > 0){
      //
      //   // if (advices.length > 0) {
      //   //   var group = this.newAdviceGroupObject()
      //   //   var initGroupBlock = function (group, advice) {
      //   //     group.group_no = advice.groupno
      //   //     // group.start_time = advice.start_time
      //   //     // group.advice_doctor = advice.advice_doctor
      //   //     // group.exec_staff = advice.execution_staff
      //   //     // group.exec_time = advice.execution_time
      //   //     // group.checker = advice.checker
      //   //   }
      //   //   for (let index = 0; index < advices.length; index++) {
      //   //     const advice = advices[index]
      //   //     if (advice.groupno == 0) {
      //   //       // 老版本的医嘱没有分组的概念，所以这一个 if 是解决这个问题的，将每个无分组的医嘱各自归为一组
      //   //       if (advice.parent_id > 0) {
      //   //         if (this.advice_groups.length > 0) {
      //   //           var parent_group = this.advice_groups[
      //   //           this.advice_groups.length - 1
      //   //             ]
      //   //           if (parent_group.advices.length > 0) {
      //   //             if (parent_group.advices[0].id == advice.parent_id) {
      //   //               parent_group.advices.push(advice)
      //   //             }
      //   //           }
      //   //         }
      //   //         continue
      //   //       } else {
      //   //         if (group.group_no > 0) {
      //   //           this.advice_groups.push(group)
      //   //           group = this.newAdviceGroupObject()
      //   //         }
      //   //
      //   //         initGroupBlock(group, advice)
      //   //         group.advices.push(advice)
      //   //         this.advice_groups.push(group)
      //   //         group = this.newAdviceGroupObject()
      //   //         continue
      //   //       }
      //   //     }
      //   //
      //   //     if (group.group_no > 0 && group.group_no != advice.groupno) {
      //   //       this.advice_groups.push(group)
      //   //       group = this.newAdviceGroupObject()
      //   //     }
      //   //     if (group.group_no == 0) {
      //   //       initGroupBlock(group, advice)
      //   //     }
      //   //     if (group.group_no == advice.groupno) {
      //   //       group.advices.push(advice)
      //   //     }
      //   //   }
      //   //   if (group.group_no > 0) {
      //   //     // 上述的算法会导致最后一组没有加到advice_groups，这里要手动加上
      //   //     this.advice_groups.push(group)
      //   //   }
      //   //
      //   // }
      //
      //
      // }
    },

    longSolutionFunc: function (val) {
      this.solution = val
      // this.requestDialysisRecord()

      // if (advices.length > 0){
      //
      //   if (advices.length > 0) {
      //     var group = this.newAdviceGroupObject()
      //     var initGroupBlock = function (group, advice) {
      //       group.group_no = advice.groupno
      //       // group.start_time = advice.start_time
      //       // group.advice_doctor = advice.advice_doctor
      //       // group.exec_staff = advice.execution_staff
      //       // group.exec_time = advice.execution_time
      //       // group.checker = advice.checker
      //     }
      //     for (let index = 0; index < advices.length; index++) {
      //       const advice = advices[index]
      //       if (advice.groupno == 0) {
      //         // 老版本的医嘱没有分组的概念，所以这一个 if 是解决这个问题的，将每个无分组的医嘱各自归为一组
      //         if (advice.parent_id > 0) {
      //           if (this.advice_groups.length > 0) {
      //             var parent_group = this.advice_groups[
      //             this.advice_groups.length - 1
      //               ]
      //             if (parent_group.advices.length > 0) {
      //               if (parent_group.advices[0].id == advice.parent_id) {
      //                 parent_group.advices.push(advice)
      //               }
      //             }
      //           }
      //           continue
      //         } else {
      //           if (group.group_no > 0) {
      //             this.advice_groups.push(group)
      //             group = this.newAdviceGroupObject()
      //           }
      //
      //           initGroupBlock(group, advice)
      //           group.advices.push(advice)
      //           this.advice_groups.push(group)
      //           group = this.newAdviceGroupObject()
      //           continue
      //         }
      //       }
      //
      //       if (group.group_no > 0 && group.group_no != advice.groupno) {
      //         this.advice_groups.push(group)
      //         group = this.newAdviceGroupObject()
      //       }
      //       if (group.group_no == 0) {
      //         initGroupBlock(group, advice)
      //       }
      //       if (group.group_no == advice.groupno) {
      //         group.advices.push(advice)
      //       }
      //     }
      //     if (group.group_no > 0) {
      //       // 上述的算法会导致最后一组没有加到advice_groups，这里要手动加上
      //       this.advice_groups.push(group)
      //     }
      //
      //   }
      //
      //
      // }
    },

    closePrescriptionDialog: function () {
      this.closeDialog(1)
      // this.scrollToView('prescription')
    },

    closeAcceptsAssessment: function () {
      this.closeDialog(2)
      // this.scrollToView('accepts_assessment')
    },

    closeAssessmentBefore: function () {
      this.closeDialog(3)
      // this.scrollToView('assessment_before')
    },

    update_evaluation: function (evaluation) {
      this.predialysis_evaluation = evaluation
      this.closeAssessmentBefore()
      this.requestDialysisRecord()
    },

    closeStatOrder: function () {
      this.closeDialog(4)
      // this.scrollToView('stat_order')
    },

    closeDialysisComputer: function (dialysis_order) {
      this.closeDialog(0)
      this.dialysis_order = dialysis_order
      this.requestDialysisRecord()
      // this.scrollToView('dialysis_computer')
    },
    closeDialysisComputerclose: function (dialysis_order) {
      this.closeDialog(0)
      // this.dialysis_order = dialysis_order
      // this.scrollToView('dialysis_computer')
    },

    closeDoubleCheck: function () {
      this.closeDialog(5)
      // this.scrollToView('double_check')
    },

    closeMonitoring: function () {
      this.closeDialog(6)
      // this.scrollToView('monitoring')
    },

    closeDialysisOff: function (assessment_after_dislysis) {
      this.closeDialog(7)
      if (assessment_after_dislysis != undefined) {
        this.assessment_after_dislysis = assessment_after_dislysis
      }
    },
    closeDialysisOffclose: function () {
      this.closeDialog(7)
      // this.scrollToView('dialysis_off')
    },

    closeAssessmentAfter: function (assessment_after_dislysis) {
      this.closeDialog(8)
      // this.scrollToView('assessment_after')
      if (assessment_after_dislysis != undefined) {
        this.assessment_after_dislysis = assessment_after_dislysis
      }
    },updateTreatmentOf:function(val){
      this.closeDialog(9)
      this.treatment_summary = val


    },

    closeTreatmentOf: function () {
      this.closeDialog(9)
      // this.scrollToView('treatment_of')
    },

    scrollToView: function (id) {
      document.body.scrollTop =
          document.querySelector('#' + id).offsetTop - 100
      document.documentElement.scrollTop =
          document.querySelector('#' + id).offsetTop - 100
    },

    handleScroll () {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      if (this.scrollTop > 50) {
        this.goTopShow = true
      } else {
        this.goTopShow = false
      }
    },

    goTop () {
      let timer = null,
        _that = this
      cancelAnimationFrame(timer)
      timer = requestAnimationFrame(function fn () {
        if (_that.scrollTop > 0) {
          _that.scrollTop -= 50
          document.body.scrollTop = document.documentElement.scrollTop =
              _that.scrollTop
          timer = requestAnimationFrame(fn)
        } else {
          cancelAnimationFrame(timer)
          _that.goTopShow = false
        }
      })
    },

    destroyed () {
      window.removeEventListener('scroll', this.handleScroll)
    },

    getUnReadNum () {
      let doctorAdvice = []
      for (let y = 0; y < this.doctor_advices.length; y++) {
        if (this.doctor_advices[y].execution_state == 2) {
          doctorAdvice.push(this.doctor_advices[y])
        }
      }
      const sorted = this.groupBy(doctorAdvice, function (item) {
        return [item.groupno]
      })

      return sorted.length
    },

    groupBy (array, f) {
      const groups = {}
      array.forEach(function (o) {
        const group = JSON.stringify(f(o))
        groups[group] = groups[group] || []
        groups[group].push(o)
      })
      return Object.keys(groups).map(function (group) {
        return groups[group]
      })
    },

    getDeviceNumber () {
      if (this.dialysis_order.id && this.dialysis_order.DeviceNumber && this.dialysis_order.DeviceNumber.number.length > 0) {
        return this.dialysis_order.DeviceNumber.number
      } else {
        if (this.schedual.device_number == null) {
          return ''
        } else {
          return this.schedual.device_number.number
        }
      }
    },

    dateDiff (firstDate, secondDate) {
      var firstDate = new Date(firstDate)
      var secondDate = new Date(secondDate)
      var diff = Math.abs(firstDate.getTime() - secondDate.getTime())
      var result = parseInt(diff / (1000 * 60 * 60 * 24))
      return result
    }
  }
}
</script>



<style style="stylesheet/scss" lang="scss" scoped>
  .today_panel {
  height: calc(100% - 63px);
  }

  .mainContent {
  position: relative;
  .grid {
  padding: 0.1rem 0 0.25rem 0;
  margin: 0.2rem 0 0 0;
  background: #fff;
  @media only screen and (min-width: 768px) {
    margin: 0.5rem 0 0 0;
    padding: 0.1rem 0 0.45rem 0;
  }
  .list {
  ul {
  @include display-flex;
  @include align-items-center;
  @include text-align;
  @include justify-content-around;
  li {
  font-size: 0.24rem;
  color: #5d6b7a;
  margin-top: 0.35rem;
  p {
  line-height: 0.6rem;
  color: #34495e;
  font-size: 0.4rem;
  }
  img {
  width: 1.2rem;
  height: 1.2rem;
  }
  }
  }
  }
  }
  }
  .el-button.is-circle {
  padding: 18px !important;
  .el-icon-arrow-up {
  font-size: 20px !important;
  }
  }
  .redpoint {
  display: inline-block;
  height: 20px;
  width: 20px;
  line-height: 18px;
  text-align: center;
  font-size: 0.45rem;
  border-radius: 20px;
  color: #fff;
  background: #f56c6c;
  position: absolute;
  border: 1px solid #fff;
  top: -8px;
  right: -8px;
  @media only screen and (min-width: 768px) {
  height: 30px;
  width: 30px;
  line-height: 28px;
  }
  }
  .goTop {
  z-index: 999;
  }
</style>
<style lang="scss">
.el-table::before {
  z-index: 0;
}
</style>
