<template>
  <div>
    <div class="Dialog" v-show="index==0" style="width: 11.8rem;">
      <div class="DialogTit">
        <span class="iconfont" @click="$emit('orderDialog')">&#xe6e9;</span>
        <h1 class="name">临时医嘱</h1>
        <span class="success">&nbsp;</span>
      </div>
      <div style="background:#fff;font-size:0.45rem;padding-left:10px;padding-top:10px;">上机时间：{{getTime(dialysis_order.start_time)}}</div>
      <div class="yzNav" style="width:100%;position: absolute;z-index:99;bottom:0;border-top:1px solid #e5e5e5">
        <span
          style="margin-left:60px;width:18%;"
          @click="openLast(1)"
          v-if="his_is_open != 1"
        >上一方</span>
        <span
          style="margin-right:60px;width:18%;"
          @click="openNext(2)"
          v-if="his_is_open != 1"
        >下一方</span>
      </div>

      <div class="yzNav" style="width:100%;">
        <span
          v-if="his_is_open != 1"
          @click="openNewAdvice"
          :class="{ forbid: is_has_create != true }"
        >新增</span>
        <span
          v-if="isShowExce"
          @click="execAdvice"
          :class="{ forbid: (current_advice&& current_advice.parent_id > 0) || is_has_exce != true }"
        >执行</span>

        <span
          id="fontSize"
          v-if="isShowMofifyExce"
          @click="modifyExecAdvice"
          :class="{ forbid: (current_advice&& current_advice.parent_id > 0) || is_has_modify_exce != true }"
        >修改执行</span>

        <span
          v-if="template_id != 6"
          @click="checkAdvice"
          :class="{ forbid: (current_advice&& current_advice.parent_id > 0) || is_has_check != true }"
        >核对</span>

        <span
          v-if="his_is_open != 1"
          id="fontSize"
          @click="openNewChild"
          :class="{ forbid: current_advice == null || current_advice.parent_id > 0 ||  currentAdvices.length != 1 || is_has_create != true }"
        >添加子药</span>

        <span

          v-if="currentSubAdvices.length <= 0 || his_is_open != 1"
          @click="modifyAdviceAction"
          :class="{ forbid: current_group_index < 0 ||  currentAdvices.length != 1  || current_select_object== 2 || (is_has_modify != true && is_has_modify_other != true) }"
        >修改</span>

        <span
          v-if="currentSubAdvices.length <= 0 || his_is_open != 1"
          @click="deleteAdviceAction"
          :class="{ forbid: current_group_index < 0 || currentAdvices.length <= 0 || (is_has_del != true && is_has_del_other != true)  }"
        >删除</span>

        <span id="fontSize" v-if="currentSubAdvices.length > 0" @click="modifySubdviceAction">修改子医嘱</span>
        <span id="fontSize" v-if="currentSubAdvices.length > 0" @click="deleteSubAdviceAction">删除子医嘱</span>
      </div>
      <div class="DialogContent choose" id="dialogTop" style="height:6.5rem;padding-bottom:1.74rem">

        <div class="content clearfix">

          <div class="orderTable">

            <table class="table">
              <tr @click="cancelAdviceSelect">
                <th width="8%">开嘱医生</th>
                <th width="12%">开始时间</th>
                <th width="52%">医嘱内容</th>
                <th width="12%">执行时间</th>
                <th width="8%">执行护士</th>
                <th v-if="template_id != 6" width="8%">核对人员</th>
              </tr>
              <template v-for="(group, group_index) in advice_groups">
                <tr
                  v-for="(advice, advice_index) in group.advices"
                  :key="advice.id"
                  :class="{ 'row-class-active': current_group_index == group_index && current_advice_index < 0 }"
                >
                  <td
                    v-if="advice_index == 0"
                    :rowspan="group.advices.length"
                    @click="selectGroupAdviceAction(group_index, -1, null,group)"
                  >
                    <span v-if="advice.parent_id==0">{{getXuserName(advice.advice_doctor)}}</span>
                    <span v-else></span>
                  </td>

                  <td
                    v-if="advice_index == 0"
                    :rowspan="group.advices.length"
                    @click="selectGroupAdviceAction(group_index, -1, null,group)"
                  >
                    <span>{{uParseTime(advice.start_time, '{m}-{d} {h}:{i}')}}</span>
                  </td>

                  <td
                    :class="{ 'advice_content': advice.parent_id == 0, 'subadvice_content': advice.parent_id > 0, 'td-active':current_group_index == group_index  && advice.is_selected == 1 }"
                    @click="selectAdviceAction(group_index, advice_index, advice)"
                  >
                    <div class="txt">
                      <span>{{advice.advice_name }}</span>
                      <span v-if="advice.advice_desc">({{ advice.advice_desc }}{{advice.drug_spec_unit}})</span>
                      <span v-if="advice.prescribing_number">&nbsp;&nbsp;{{advice.prescribing_number}}{{advice.prescribing_number_unit}}</span>
                      <span v-if="advice.single_dose && template_id == 6">{{advice.single_dose}}{{advice.single_dose_unit}}</span>
                      <span v-if="advice.single_dose && template_id != 6">单次用量{{advice.single_dose}}{{advice.single_dose_unit}}</span>

                      <span v-if="advice.parent_id == 0">{{advice.delivery_way}}</span>
                      <span v-if="advice.parent_id == 0">{{advice.execution_frequency}}</span>
                      <span
                        v-if="advice.parent_id == 0 && advice.remark.length > 0"
                      >({{advice.remark}})</span>
                    </div>
                  </td>

                  <td
                    :class="{'td-active':current_group_index == group_index  && advice.is_selected == 1}"
                    @click="selectAdviceAction(group_index,advice_index, advice)"
                  >{{uParseTime(advice.execution_time, '{m}-{d} {h}:{i}')}}
                  </td>

                  <td
                    :class="{'td-active':current_group_index == group_index  && advice.is_selected == 1}"
                    @click="selectAdviceAction(group_index,advice_index, advice)"

                  > {{getXuserName(advice.execution_staff)}}
                  </td>
                  <td v-if="template_id != 6"
                      :class="{'td-active':current_group_index == group_index  && advice.is_selected == 1}"
                      @click="selectAdviceAction(group_index,advice_index, advice)"
                  >{{getXuserName(advice.checker)}}
                  </td>
                </tr>
              </template>
            </table>
          </div>
        </div>
      </div>
    </div>

    <div class="Dialog" style="width: 11.8rem;" v-show="isLastOrNextVisible">
      <div class="DialogTit">
        <div class="back" @click="backAction">
          <span class="iconfont">&#xe720;</span>返回
        </div>
        <h1 class="name">新增医嘱</h1>
        <span class="success" @click="comfirmAction" v-if="other_doctor_advices.length > 0">设为本次临嘱</span>
        <span class="success"     v-else="other_doctor_advices.length > 0"></span>

      </div>

      <div class="yzNav" style="width:100%;position: fixed;z-index:99;bottom:0;border-top:1px solid #e5e5e5">
        <span
          style="margin-left:60px;width:18%;"
          @click="openLast(3)"
        >上一方</span>
        <span
          style="margin-right:60px;width:18%;"
          @click="openNext(4)"
        >下一方</span>
      </div>

      <div class="content clearfix backgroundColor">
        <div id="newDialogContent" class="DialogContent choose" style="height: 6.2rem;padding-bottom:1.74rem">
          <div style="overflow: hidden;display:flex;align-items: center;padding:0 10px;">
            <p style="width:3.5rem;font-size:0.45rem">开始时间</p>
            <el-input
              style="font-size:0.45rem !important;"
              class="typeInput"
              :value="start_time_str"
              readonly
              @focus="selectStartTimeAction"
            ></el-input>
          </div>
          <div style="padding:10px;font-size:0.45rem" v-if="getContent()">
            {{getContent()}}
          </div>
          <div style='width:100%;overflow-x:auto;'>
            <table class="table">
              <tr>
                <th width="30%">医嘱内容</th>
                <th width="20%">药品规格</th>
                <th width="10%">开药数量</th>
                <th width="10%">单次用量</th>
                <th width="15%">给药途径</th>
                <th width="15%">执行频率</th>
              </tr>
              <template v-for="(advice, advice_index) in other_doctor_advices"  :key="advice_index">
                <tr>
                  <td
                    style="text-align: left;padding-left:5px;padding-right:5px;"
                  >{{ advice.advice_name }}
                  </td>
                  <td v-if="advice.advice_desc">{{ advice.advice_desc }}{{ advice.drug_spec_unit }}</td>
                  <td v-if="advice.prescribing_number">
                    {{ advice.prescribing_number
                    }}{{ advice.prescribing_number_unit }}
                  </td>
                  <td v-else></td>
                  <td
                    v-if="advice.single_dose"
                  >{{ advice.single_dose }} {{ advice.single_dose_unit }}
                  </td>
                  <td v-else></td>
                  <td>{{ advice.delivery_way }}</td>
                  <td>{{ advice.execution_frequency }}</td>
                </tr>

                <tr
                  v-for="(subdrug, subdrug_index) in advice.children"
                  :key="advice_index + '_' + subdrug_index"

                >
                  <td
                    style="text-align: left;padding-left:5px;padding-right:5px;"
                  >{{ subdrug.advice_name }}
                  </td>
                  <td>{{ subdrug.advice_desc }} {{ subdrug.drug_spec_unit }}</td>
                  <td>
                    <span v-if="subdrug.prescribing_number">
                      {{ subdrug.prescribing_number
                      }}{{ subdrug.prescribing_number_unit }}
                    </span>
                  </td>
                  <td>
                    <span v-if="subdrug.single_dose">
                      {{ subdrug.single_dose }}
                      {{ subdrug.single_dose_unit }}
                    </span>
                  </td>
                  <!--<td v-if="subdrug.single_dose">{{ subdrug.single_dose }} {{ subdrug.single_dose_unit }}</td>-->
                  <td></td>
                  <td></td>
                </tr>
              </template>
            </table>
          </div>
        </div>
      </div>
    </div>

    <add-new-order-dialog
      v-show="index==1&&isShowDialog"
      @back-action="index = 0"
      :patient_id="patient.id"
      :drug_spec_unit_options="unitsOption"
      :delivery_way_options="deliveryWayOptions"
      :execution_frequency_options="executionFrequencyOptions"
      :single_dose_unit_options="unitsOption"
      :prescribing_number_unit_options="unitsOption"
      :advice_templates="adviceTemplates"
      :all_drug="all_drug"
      :medicals="medicals"
      :base_drug_list="base_drug_list"
      :base_drug_config="base_drug_config"
      :private_drug_config="private_drug_config"

      @did-create-advices="didCreateAdvices"
    ></add-new-order-dialog>

    <sub-order-form
      ref="subdrug_form"
      @back="index = 0"
      @did-create-subdrug="didAddSubdrug"
      :single_dose_unit_options="unitsOption"
      :prescribing_number_unit_options="unitsOption"
      :drug_spec_unit_options="unitsOption"
      :all_drug="all_drug"
      :medicals="medicals"
      :base_drug_list="base_drug_list"
      :base_drug_config="base_drug_config"
      :private_drug_config="private_drug_config"

    >
    </sub-order-form>
    <sub-modify-order-form
      ref="sub_modify_advice_form"
      @back="index = 0"
      @did-modify="didModifyAdvice"
      :drug_spec_unit_options="unitsOption"
      :delivery_way_options="deliveryWayOptions"
      :execution_frequency_options="executionFrequencyOptions"
      :single_dose_unit_options="unitsOption"
      :prescribing_number_unit_options="unitsOption"
      :all_drug="all_drug"
      :medicals="medicals"
      :base_drug_list="base_drug_list"
      :base_drug_config="base_drug_config"
      :private_drug_config="private_drug_config"

    ></sub-modify-order-form>

    <modify-advice-form
      ref="modify_advice_form"
      @back="index = 0"
      @did-modify="didModifyAdvice"
      :drug_spec_unit_options="unitsOption"
      :delivery_way_options="deliveryWayOptions"
      :execution_frequency_options="executionFrequencyOptions"
      :single_dose_unit_options="unitsOption"
      :prescribing_number_unit_options="unitsOption"
      :all_drug="all_drug"
      :medicals="medicals"
      :base_drug_list="base_drug_list"
      :base_drug_config="base_drug_config"
      :private_drug_config="private_drug_config"
    ></modify-advice-form>

    <modify-advice-group-dialog
      ref="modify_advice_group"
      @back="index = 0"
      :patient_id="patient.id"
      :delivery_way_options="deliveryWayOptions"
      :execution_frequency_options="executionFrequencyOptions"
      :single_dose_unit_options="unitsOption"
      :drug_spec_unit_options="unitsOption"
      :prescribing_number_unit_options="unitsOption"
      :advice_templates="adviceTemplates"
      @did-create-advices="didCreateAdvices"
    ></modify-advice-group-dialog>

    <mt-datetime-picker
      ref="exec_time"
      type="datetime"
      @confirm="handleExecTime"
      v-model="nowExecTime"
    ></mt-datetime-picker>

    <mt-datetime-picker
      ref="mofify_exec_time"
      type="datetime"
      @confirm="handleModifyExecTime"
      v-model="nowExecTime"
    ></mt-datetime-picker>

    <mt-datetime-picker
      ref="start_time_picker"
      type="datetime"
      @confirm="didSelectStartTime"
      v-model="start_time"
    ></mt-datetime-picker>
    
      <van-popup
        v-model="infor_visibility"
        class="advicePopup"
        get-container="#today_panel"
      >
        <infor-sub-menu
        :visibility="infor_visibility"
        v-on:menu-cancle-three="menuCancleFour"
        v-on:menu-comfirm-three="menuComfirmFour"
        >
      </infor-sub-menu>
      </van-popup>
  </div>
</template>

<script>
import {Dialog, Toast} from 'vant'
import {GetAllDrug} from '@/api/drug/drug'

import {
  batchCreateAdvices,
  CheckDoctorAdvice,
  CreateDoctorAdvice,
  DeleteDoctorAdviceNew,
  DeleteSubDoctorAdvice,
  EditDoctorAdvice,
  ExecDoctorAdvice,
  getAdviceConfig,
  GetLastOrNextDoctorAdvice,
  ModifyExecDoctorAdvice
} from '@/api/advice'
import { saveMobileInformation } from '@/api/dialysis'
import {uParseTime} from '@/utils/tools'
import CheckBoxSubMenu from './subMenu/checkBoxSubMenu'
import {getDataConfig} from '@/utils/data'
import AddNewOrderDialog from './new_order/AddNewOrders'
import AdviceForm from './new_order/order_form'
import ModifyAdviceForm from './modify_order/modify_order_form'
import ModifyAdviceGroupDialog from './modify_order/ModifyAdviceGroup'
import InforSubMenu from "../dialog/subMenu/InforSubMenu"
import request from '@/utils/request'
import {parseTime} from '@/utils'
import SubOrderForm from './new_order/sub_order_form'
import SubModifyOrderForm from './modify_order/sub_modify_order_form'

export default {
  name: 'OrdersDialog',
  components: {
    SubModifyOrderForm,
    SubOrderForm,
    CheckBoxSubMenu,
    AddNewOrderDialog,
    AdviceForm,
    ModifyAdviceForm,
    ModifyAdviceGroupDialog,
    InforSubMenu
  },
  props: {
    advice_groups: {
      type: Array,
      default: () => {
        return []
      }
    },
    patient_prop: {
      type: Object
    },
    advice_list_prop: {
      type: Array
    },
    admin_users_prop: {
      type: Array
    },
    dialysis_order: {
      type: Object
    },
    his_is_open:{
      type: Number,
      default: () => {
        return 0
      }
    }
  },
  data () {
    return {
      start_time: '',
      request_record_date: '',
      isLastOrNextVisible: false,
      other_doctor_advices: [],
      sch: null,
      group_no: 0,
      is_has_create: true,
      is_has_exce: true,
      is_has_check: true,
      is_has_modify_exce: true,
      is_has_modify: true,
      is_has_modify_other: true,
      is_has_del: true,
      is_has_del_other: true,
      isShowDialog: true,
      template_id: 0,
      isShowExce: true,
      isShowMofifyExce: false,
      title: '临时医嘱',
      index: 0,
      doctor: '',
      adviceTemplates: [],
      drugOptions: {},
      deliveryWayOptions: [],
      executionFrequencyOptions: [],
      unitsOption: [],
      unitsObj: [],
      record_date: '',
      nowExecTime: new Date(),
      patient: {
        id: 0
      },
      admin_users: [],
      adviceList: [],
      parent_id: 0,
      current_select_object: -1,
      current_group_index: -1,
      current_advice_index: -1,
      current_advice: null,
      currentAdviceIdsStr: '',
      currentAdvices: [],
      currentSubAdvices: [],
      private_drug_config: null,
      base_drug_config: null,
      base_drug_list: [],
      all_drug: [],
      medicals: [],
      infor_visibility:false,
    }
  },
  created () {
    this.getPermission()
    this.template_id = this.$store.getters.user.template_info.template_id
    var date = this.$route.query && this.$route.query.date
    date *= 1000
    var newDate = new Date(date)

    var otherDate = new Date()

    var y = newDate.getFullYear()
    var m = newDate.getMonth() + 1
    var d = newDate.getDate()

    var h = otherDate.getHours()
    var mm = otherDate.getMinutes()

    if (isNaN(y) || isNaN(m) || isNaN(d)) {
      newDate = new Date()
      y = newDate.getFullYear()
      m = newDate.getMonth() + 1
      d = newDate.getDate()
    }
    this.record_date =
        y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d)
    this.request_record_date = this.record_date
    this.patient = this.patient_prop
    this.adviceList = this.advice_list_prop
    this.admin_users = this.admin_users_prop
    this.doctor = this.$store.getters.user.user.user_name
    this.getAdviceConfig()

    this.unitsOption = getDataConfig('hemodialysis', 'units')
    for (var index in this.unitsOption) {
      this.unitsObj[this.unitsOption[index].id] = this.unitsOption[index]
    }

    var start_time = y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' +
        (h < 10 ? '0' + h : h) + ':' + (mm < 10 ? '0' + mm : mm) + ':00'
    this.start_time = start_time
    this.start_time_str = start_time

    var patient_id = this.$route.query.patient_id
    this.GetAllDrug(patient_id)
  },
  watch: {
    advice_groups: function () {
    },
    currentAdvices: function (currentAdvices) {
      if (currentAdvices.length == 0) {
        this.isShowExce = true
        this.isShowMofifyExce = false
      } else {
        let a = 0
        for (let i = 0; i < currentAdvices.length; i++) {
          if (currentAdvices[i].execution_state == 1) {
            a = a + 1
          }
        }

        if (a == currentAdvices.length) {
          this.isShowExce = false
          this.isShowMofifyExce = true
        } else {
          this.isShowExce = true
          this.isShowMofifyExce = false
        }
      }
    }
  },

  methods: {
    GetAllDrug (id) {
      const params = {
        patient_id: id
      }
      GetAllDrug(params).then(response => {
        if (response.data.state == 1) {
          this.all_drug = []
          var medicalList = response.data.data.private_drug_list
          var base_drug_list = response.data.data.base_drug_list
          var base_drug_cofig = response.data.data.base_drug_config
          var private_drug_cofig = response.data.data.private_drug_config

          if (private_drug_cofig != null && private_drug_cofig.drug_start == 1) {
            for (let i = 0; i < medicalList.length; i++) {
              if (medicalList[i].drug_specs != null) {
                for (let a = 0; a < medicalList[i].drug_specs.length; a++) {
                  medicalList[i].drug_specs[a]['type'] = 2
                }
              }
              let obj = {
                drug_name: '',
                drug_desc: '',
                delivery_way: '',
                execution_frequency: '',
                single_dose: '',
                single_dose_unit: '',
                prescribing_number: '',
                prescribing_number_unit: '',
                type_id: '',
                type: '',
                custom_id: '',
                drug_specs: []
              }

              medicalList[i].drug_name = medicalList[i].drug_name + '(自备药)'
              obj.drug_name = medicalList[i].drug_name
              obj.delivery_way = medicalList[i].delivery_way
              obj.execution_frequency = medicalList[i].execution_frequency
              obj.single_dose = medicalList[i].single_dose
              obj.prescribing_number = medicalList[i].prescribing_number
              obj.type_id = medicalList[i].id
              obj.type = 2
              obj.drug_specs = medicalList[i].drug_specs
              this.all_drug.push(obj)
            }
          }

          for (let i = 0; i < base_drug_list.length; i++) {
            if (base_drug_list[i].drug_specs != null) {
              for (let a = 0; a < base_drug_list[i].drug_specs.length; a++) {
                base_drug_list[i].drug_specs[a]['type'] = 1
              }
            }
            let obj = {
              drug_name: '',
              drug_desc: '',
              delivery_way: '',
              execution_frequency: '',
              single_dose: '',
              single_dose_unit: '',
              prescribing_number: '',
              prescribing_number_unit: '',
              type_id: '',
              type: '',
              custom_id: '',
              drug_specs: []
            }

            obj.drug_name = base_drug_list[i].drug_name
            obj.delivery_way = base_drug_list[i].delivery_way
            obj.execution_frequency = base_drug_list[i].execution_frequency
            obj.single_dose = base_drug_list[i].single_dose
            obj.prescribing_number = base_drug_list[i].prescribing_number
            obj.type_id = base_drug_list[i].id
            obj.type = 1
            obj.drug_specs = base_drug_list[i].drug_specs
            this.all_drug.push(obj)
          }
        }

        this.medicals = medicalList
        this.base_drug_list = base_drug_list
        this.private_drug_config = private_drug_cofig
        this.base_drug_cofig = base_drug_cofig
      })
    },

    getContent: function () {
      if (this.sch != null) {
        var date = uParseTime(this.sch.schedule_date, '{y}-{m}-{d}')
        var week = ''
        var sch_type = ''

        switch (this.sch.schedule_week) {
          case 1:
            week = '周一'
            break
          case 2:
            week = '周二'

            break
          case 3:
            week = '周三'

            break
          case 4:
            week = '周四'

            break
          case 5:
            week = '周五'

            break
          case 6:
            week = '周六'

            break
          case 7:
            week = '周日'
            break
        }
        switch (this.sch.schedule_type) {
          case 1:
            sch_type = '上午'
            break
          case 2:
            sch_type = '下午'

            break
          case 3:
            sch_type = '晚上'

            break
        }
        return date + '(' + week + '/' + sch_type + ')'
      } else {
        return ''
      }
    },
    didSelectStartTime: function (time) {
      this.start_time_str = parseTime(time, '{y}-{m}-{d} {h}:{i}') + ':00'
    },
    selectStartTimeAction: function () {
      this.$refs.start_time_picker.open()
    },
    comfirmAction: function () {
      var data = {}
      data.advice_type = 2
      data.advice_date = this.record_date
      data.start_time = this.start_time_str
      var adviceJSONs = []
      for (let index = 0; index < this.other_doctor_advices.length; index++) {
        const advice = this.other_doctor_advices[index]
        var json = {
          advice_name: advice.advice_name,
          advice_desc: advice.advice_desc,
          drug_spec: String(advice.drug_spec),
          drug_spec_unit: advice.drug_spec_unit,
          single_dose: String(advice.single_dose),
          single_dose_unit: advice.single_dose_unit,
          prescribing_number: String(advice.prescribing_number),
          prescribing_number_unit: advice.prescribing_number_unit,
          delivery_way: advice.delivery_way,
          execution_frequency: advice.execution_frequency,
          remark: advice.remark,
          subdrugs: [],
          drug_id: advice.drug_id,
          way: advice.way,
          drug_name_id: advice.drug_name_id

        }
        for (let s_i = 0; s_i < advice.children.length; s_i++) {
          const subdrug = advice.children[s_i]
          json.subdrugs.push({
            advice_name: subdrug.advice_name,
            advice_desc: subdrug.advice_desc,
            drug_spec: String(subdrug.drug_spec),
            drug_spec_unit: subdrug.drug_spec_unit,
            single_dose: String(subdrug.single_dose),
            single_dose_unit: subdrug.single_dose_unit,
            prescribing_number: String(subdrug.prescribing_number),
            prescribing_number_unit: subdrug.prescribing_number_unit,
            drug_id: advice.drug_id,
            way: advice.way,
            drug_name_id: advice.drug_name_id
          })
        }
        adviceJSONs.push(json)
      }

      data.adviceNames = adviceJSONs
      this.loading = true
      let mode = '1'
      var is_child = 1
      batchCreateAdvices(this.patient.id, 0, data, mode, is_child)
        .then(rs => {
          this.loading = false
          var resp = rs.data
          if (resp.state == 1) {
            // 返回数组，清空数据，隐藏弹框
            this.isLastOrNextVisible = false
            this.index = 0
            this.didCreateAdvices(resp.data.advices)
            var t = this
            setTimeout(function () {
              t.advices.splice(0, t.advices.length)
              t.show_dialog_key = 0
              t.selecting_advice_index = -1
            }, 500)
          } else {
            Toast.fail(resp.msg)
            if(resp.code == 600000008){
                this.infor_visibility = true
             }
          }
        })
        .catch(err => {
          this.loading = false
          Toast.fail(err)
        })
    },

    backAction: function () {
      this.isLastOrNextVisible = false
      this.index = 0
    },

    GetLastOrNextDoctorAdvice (params) {
      GetLastOrNextDoctorAdvice(params).then(response => {
        if (response.data.state == 1) {
          this.other_doctor_advices = []
          var doctor_advices = response.data.data.advices
          this.other_doctor_advices = doctor_advices
          this.request_record_date = uParseTime(this.other_doctor_advices[0].record_date, '{y}-{m}-{d}')
          this.sch = response.data.data.schedule
        } else {
          Toast.fail(response.data.msg)
        }
      })
    },
    openLast (val) {
      this.index = 10

      if (val == 1) {
        this.request_record_date = this.record_date
        this.isLastOrNextVisible = true
        let params = {
          patient_id: this.patient.id,
          record_time: this.request_record_date,
          type: 1
        }

        this.GetLastOrNextDoctorAdvice(params)
      } else if (val == 3) {
        let params = {
          patient_id: this.patient.id,

          record_time: this.request_record_date,
          type: 1
        }

        this.GetLastOrNextDoctorAdvice(params)
      }
    },
    openNext (val) {
      if (val == 2) {
        this.isLastOrNextVisible = true
        this.index = 10
        this.request_record_date = this.record_date

        let params = {
          patient_id: this.patient.id,

          record_time: this.request_record_date,
          type: 2
        }

        this.GetLastOrNextDoctorAdvice(params)
      } else if (val == 4) {
        let params = {
          patient_id: this.patient.id,

          record_time: this.request_record_date,
          type: 2
        }
        this.GetLastOrNextDoctorAdvice(params)
      }
    },
    modifyExecAdvice: function () {
      if (this.is_has_modify_exce == false) {
        Toast.fail('你没有修改执行医嘱的权限')
        return false
      }

      if(this.currentAdvices[0].origin == 2){
        Toast.fail('所选医嘱属于his医嘱无法修改执行的医嘱')
        return false
      }

      this.nowExecTime = new Date(this.currentAdvices[0].execution_time * 1000)
      this.$refs.mofify_exec_time.open()
    },
    didCreateAdvices: function (advices) {
      if (advices.length == 0) {
        return
      }
      for (let i = 0; i < advices.length; i++) {
        advices[i]['is_selected'] = 0
      }

      var new_group = Object.assign(
        {},
        {
          group_no: 0,
          start_time: 0,
          advices: []
        }
      )
      new_group.group_no = advices[0].groupno
      new_group.start_time = advices[0].start_time
      new_group.advices.push(...advices)

      var insertIndex = -1
      for (let index = 0; index < this.advice_groups.length; index++) {
        const group = this.advice_groups[index]
        group['origin'] = 1
        if (group.start_time < new_group.start_time) {
          insertIndex = index
          break
        }
      }

      if (insertIndex < 0) {
        this.advice_groups.push(new_group)
      } else {
        this.advice_groups.splice(insertIndex, 0, new_group)
      }
      this.index = 0
      this.advice_groups.sort((a, b) => a.start_time - b.start_time)
    },
    didModifyAdvice: function (advice) {
      let mode = '2'
      if (
        advice.doctor_advice != this.$store.getters.user.admin.id &&
          advice.doctor_advice > 0
      ) {
        mode = '3'
      }
      Toast.loading({forbidClick: true, duration: 0})
      EditDoctorAdvice(
        advice.id,
        {
          advice_name: advice.title,
          advice_desc: advice.advice_desc,
          remark: advice.remark,
          start_time: advice.start_time,
          drug_spec: String(advice.drug_spec),
          drug_spec_unit: advice.drug_spec_unit,
          delivery_way: advice.delivery_way,
          execution_frequency: advice.execution_frequency,
          single_dose: String(advice.single_dose),
          single_dose_unit: advice.single_dose_unit,
          prescribing_number: String(advice.prescribing_number),
          prescribing_number_unit: advice.prescribing_number_unit,
          way: advice.way,
          drug_id: advice.drug_id,
          drug_name_id: advice.drug_name_id
        },
        mode
      )
        .then(rs => {
          if (rs.data.state == 1) {
            var resp_advice = rs.data.data.advice
            if (!rs.data.data.isChange) {
              var group = this.advice_groups[this.current_group_index]
              for (let index = 0; index < group.advices.length; index++) {
                const advice = group.advices[index]
                if (advice.id == resp_advice.id) {
                  advice.advice_name = resp_advice.advice_name
                  advice.advice_desc = resp_advice.advice_desc
                  advice.remark = resp_advice.remark
                  advice.start_time = resp_advice.start_time
                  advice.drug_spec = resp_advice.drug_spec
                  advice.drug_id = resp_advice.drug_id
                  advice.way = resp_advice.way
                  advice.drug_name_id = resp_advice.drug_name_id;
                  (advice.drug_spec_unit = resp_advice.drug_spec_unit),
                  (advice.delivery_way = resp_advice.delivery_way),
                  (advice.execution_frequency =
                        resp_advice.execution_frequency),
                  (advice.single_dose = resp_advice.single_dose),
                  (advice.single_dose_unit = resp_advice.single_dose_unit),
                  (advice.prescribing_number =
                        resp_advice.prescribing_number),
                  (advice.prescribing_number_unit =
                        resp_advice.prescribing_number_unit)
                  break
                }
              }
            } else {
              // var group = this.advice_groups[this.current_group_index]
              // 先删除旧数据，再插入新数据
              var adviceArr = this.advice_groups[this.current_group_index]
                .advices
              for (let y = resp_advice.length - 1; y >= 0; y--) {
                for (let i = adviceArr.length - 1; i >= 0; i--) {
                  if (
                    adviceArr[i].id == resp_advice[y].id ||
                      adviceArr[i].parent_id == resp_advice[y].id
                  ) {
                    adviceArr.splice(i, 1)
                  }
                }
              }
              var newAdvice = {}
              newAdvice['advices'] = resp_advice
              newAdvice['group_no'] = resp_advice[0].groupno
              this.advice_groups.push(newAdvice)
            }

            this.currentAdvices = []
            this.currentSubAdvices = []
            for (let i = 0; i < this.advice_groups.length; i++) {
              for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
                var advices = this.advice_groups[i].advices[y]
                advices.is_selected = 0
              }
            }

            this.$refs.modify_advice_form.dismiss()
            this.$refs.sub_modify_advice_form.dismiss()

            Toast.clear()
            this.index = 0
          } else {
            Toast.fail(rs.data.msg)
          }
        })
        .catch(err => {
          Toast.fail(err)
        })
    },
    uParseTime (time, format) {
      if (time == 0) {
        return ''
      }
      return uParseTime(time, format)
    },
    getXuserName (id) {
      if (id <= 0) {
        return ''
      }
      var name = ''
      if (
        this.admin_users == null ||
          typeof this.admin_users.length === 'undefined'
      ) {
        return name
      }
      var leng = this.admin_users.length
      if (leng == 0) {
        return name
      }
      for (let index = 0; index < leng; index++) {
        if (this.admin_users[index].id == id) {
          name = this.admin_users[index].name
          break
        }
      }
      return name
    },
    didAddSubdrug: function (subdrug) {
      Toast.loading({forbidClick: true, duration: 0})
      let mode = '1'
      var is_child = 2
      batchCreateAdvices(
        this.patient.id,
        subdrug.group_no,
        {
          parent_id: subdrug.parent_id,
          advice_type: 2,
          advice_date: subdrug.record_time,
          start_time: subdrug.start_time + ':00',
          advice_name: subdrug.title,
          advice_desc: subdrug.advice_desc,
          drug_spec: String(subdrug.drug_spec),
          drug_spec_unit: subdrug.drug_spec_unit,
          single_dose: String(subdrug.single_dose),
          single_dose_unit: subdrug.single_dose_unit,
          prescribing_number: String(subdrug.prescribing_number),
          prescribing_number_unit: subdrug.prescribing_number_unit,
          way: subdrug.way,
          drug_id: subdrug.drug_id,
          drug_name_id: subdrug.drug_name_id

          // delivery_way: subdrug.delivery_way,
          // execution_frequency: subdrug.execution_frequency
        },
        mode,
        is_child
      )
        .then(response => {
          if (response.data.state == 0) {
            Toast.fail(response.data.msg)
            return false
          } else {
            Toast.success('添加成功')
            var resp_advice = response.data.data.advice
            var group_index = this.current_group_index

            var adviceArr = this.advice_groups[this.current_group_index]
              .advices
            for (let i = 0; i < adviceArr.length; i++) {
              if (
                adviceArr[i].id == this.currentAdvices[0].id &&
                  adviceArr[i].is_selected == 1
              ) {
                var advice_index = i
              }
            }

            var group = this.advice_groups[group_index]

            var insert_index = -1
            var last_child_index = -1
            for (
              let index = advice_index + 1;
              index < group.advices.length;
              index++
            ) {
              const advice = group.advices[index]
              if (resp_advice.parent_id != advice.parent_id) {
                insert_index = index
                break
              } else {
                last_child_index = index
              }
            }
            if (insert_index < 0) {
              if (last_child_index < 0) {
                group.advices.splice(advice_index + 1, 0, resp_advice)
              } else {
                group.advices.splice(last_child_index + 1, 0, resp_advice)
              }
            } else {
              group.advices.splice(insert_index, 0, resp_advice)
            }

            this.cancelAdviceSelect()
            this.$refs.subdrug_form.dismiss()
            this.index = 0
            // this.$emit("new_create", response.data.data.advice);

            this.currentAdvices = []
            this.currentSubAdvices = []
            for (let i = 0; i < this.advice_groups.length; i++) {
              for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
                var advices = this.advice_groups[i].advices[y]
                advices.is_selected = 0
              }
            }

            return false
          }
        })
        .catch(err => {
          Toast.fail(err)
        })
    },
    getAdviceConfig () {
      getAdviceConfig().then(response => {
        if (response.data.state == 1) {
          this.deliveryWayOptions =
              response.data.data.drugways === null
                ? []
                : response.data.data.drugways
          this.executionFrequencyOptions =
              response.data.data.efs === null ? [] : response.data.data.efs

          this.adviceTemplates =
              response.data.data.advice_templates === null
                ? []
                : response.data.data.advice_templates
        }
      })
    },
    handleModifyExecTime (time) {
      var exceTime = this.handleTime(time)
      var currentAdviceIdArr = []
      var exceParams = null
      for (let i = 0; i < this.currentAdvices.length; i++) {
        if (this.currentAdvices[i].execution_state == 1) {
          currentAdviceIdArr.push(this.currentAdvices[i].id)
        }
      }
      this.currentAdviceIdsStr = currentAdviceIdArr.join(',')
      if (this.current_select_object == 1) {
        exceParams = {
          groupno: 0,
          advice_id: this.currentAdviceIdsStr,
          execution_time: exceTime
        }
      } else {
        var group = this.advice_groups[this.current_group_index]
        exceParams = {
          groupno: group.group_no <= 0 ? 0 : group.group_no,
          advice_id: group.group_no <= 0 ? group.advices[0].id : 0,
          execution_time: exceTime
        }
      }
      exceParams['mode'] = 8
      ModifyExecDoctorAdvice(exceParams)
        .then(response => {
          if (response.data.state == 0) {
            Toast.fail(response.data.msg)
            return false
          } else {
            Toast.success('修改成功！')
            var advice = response.data.data.advice
            if (this.current_select_object == 1) {
              var ids = this.currentAdviceIdsStr.split(',')
              var adviceArr = this.advice_groups[this.current_group_index]
                .advices
              for (let i = 0; i < adviceArr.length; i++) {
                for (let a = 0; a < ids.length; a++) {
                  if (
                    (adviceArr[i].execution_state == 1 &&
                        adviceArr[i].id == ids[a]) ||
                      (adviceArr[i].execution_state == 1 &&
                        adviceArr[i].parent_id == ids[a])
                  ) {
                    adviceArr[i].execution_time = advice.execution_time
                  }
                }
              }
            } else {
              for (let index = 0; index < group.advices.length; index++) {
                const adv = group.advices[index]
                if (adv.execution_state == 1) {
                  adv.execution_time = advice.execution_time
                }
              }
            }
          }
        })
        .catch(err => {
          Toast.fail(err)
          return false
        })
    },
    handleExecTime (time) {
      var exceTime = this.handleTime(time)
      var exceParams = null

      if(this.advice_groups[this.current_group_index].advices[0].origin == 2){
        var group = this.advice_groups[this.current_group_index]
        exceParams = {
          origin: 2,
          groupno: 0,
          advice_id: group.advices[0].id,
          execution_time: exceTime
        }
        exceParams['mode'] = '6'
      }else{

        if (this.current_select_object == 1) {
          exceParams = {
            origin: 1,
            groupno: 0,
            advice_id: this.currentAdviceIdsStr,
            execution_time: exceTime
          }
        } else {
          var group = this.advice_groups[this.current_group_index]
          exceParams = {
            origin: 1,

            groupno: group.group_no <= 0 ? 0 : group.group_no,
            advice_id: group.group_no <= 0 ? group.advices[0].id : 0,
            execution_time: exceTime
          }
        }
        Toast.loading({forbidClick: true, duration: 0})
        exceParams['mode'] = '6'
      }


      ExecDoctorAdvice(exceParams).then(response => {
         if (response.data.state == 0) {
            Toast.fail(response.data.msg)
            return false
          } else {
            Toast.success('执行成功！')
            var advice = response.data.data.advice
            if (this.current_select_object == 1) {
              var ids = this.currentAdviceIdsStr.split(',')
              var adviceArr = this.advice_groups[this.current_group_index]
                .advices
              for (let i = 0; i < adviceArr.length; i++) {
                for (let a = 0; a < ids.length; a++) {
                  if (
                    (adviceArr[i].execution_state == 2 &&
                        adviceArr[i].id == ids[a]) ||
                      (adviceArr[i].execution_state == 2 &&
                        adviceArr[i].parent_id == ids[a])
                ) {
                  adviceArr[i].execution_staff = advice.execution_staff
                  adviceArr[i].execution_time = advice.execution_time
                  adviceArr[i].execution_state = advice.execution_state
                }
              }
            }
          } else {
            for (let index = 0; index < group.advices.length; index++) {
              const adv = group.advices[index]
              if (adv.execution_state == 2) {
                adv.execution_staff = advice.execution_staff
                adv.execution_time = advice.execution_time
                adv.execution_state = advice.execution_state
              }
            }
          }
        }
      })
        .catch(err => {
          Toast.fail(err)
          return false
        })
    },
    handleTime (time) {
      var year = time.getFullYear()
      var month = time.getMonth() + 1
      var day = time.getDate()
      var hour = time.getHours()
      var minute = time.getMinutes()
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      if (hour < 10) {
        hour = '0' + hour
      }
      if (minute < 10) {
        minute = '0' + minute
      }
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':00'
    },
    deleteSubAdviceAction: function () {
      if (this.currentSubAdvices.length <= 0) {
        return
      }
      Dialog.confirm({
        title: '删除医嘱',
        message: '确认删除医嘱吗?'
      }).then(() => {
        Toast.loading({forbidClick: true, duration: 0})
        let is_sub = 1
        let mode = '4'
        if (
          this.currentSubAdvices[0].advice_doctor !=
            this.$store.getters.user.admin.id &&
            this.currentSubAdvices[0].advice_doctor > 0
        ) {
          mode = '5'
        }

        DeleteDoctorAdviceNew(0, this.currentSubAdvices[0].id, mode, is_sub)
          .then(rs => {
            if (rs.data.state == 1) {
              Toast.success('删除成功')
              var adviceArr = this.advice_groups[this.current_group_index]
                .advices
              for (let i = adviceArr.length - 1; i >= 0; i--) {
                if (adviceArr[i].id == this.currentSubAdvices[0].id) {
                  adviceArr.splice(i, 1)
                }
              }
              this.currentSubAdvices = []
              this.currentAdvices = []
              for (let i = 0; i < this.advice_groups.length; i++) {
                for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
                  var advices = this.advice_groups[i].advices[y]
                  advices.is_selected = 0
                }
              }
            } else {
              Toast.fail(rs.data.msg)
            }
          })
          .catch(err => {
            Toast.fail(err)
          })
      })
    },
    deleteAdviceAction: function () {
      if(this.currentAdvices[0].origin == 2){
        Toast.fail('所选医嘱属于his医嘱无法删除医嘱')
        return false
      }
      if (this.current_select_object == 1) {
        if (this.currentAdvices.length <= 0) {
          return
        }
        var isShow = true
        for (let i = 0; i < this.currentAdvices.length; i++) {
          if (this.currentAdvices[i].execution_state == 1) {
            isShow = false
          }
        }

        if (this.base_drug_cofig != null && this.base_drug_cofig.is_open == 1 && !isShow) {
          Toast.fail('所选医嘱已执行，无法删除')
          return
        }

        if (this.private_drug_config != null && this.private_drug_config.drug_start == 1 && !isShow) {
          Toast.fail('所选医嘱已执行，无法删除')
          return
        }

        Dialog.confirm({
          title: '删除医嘱',
          message: '确认删除医嘱吗?'
        }).then(() => {
          Toast.loading({forbidClick: true, duration: 0})
          var group_no = 0
          var advice_id = this.currentAdvices.join(',')
          var ids = []
          for (let i = 0; i < this.currentAdvices.length; i++) {
            ids.push(this.currentAdvices[i].id)
          }
          advice_id = ids.join(',')

          let mode = '4'
          if (
            this.currentAdvices[0].advice_doctor !=
              this.$store.getters.user.admin.id &&
              this.currentAdvices[0].advice_doctor > 0
          ) {
            mode = '5'
          }
          if (
            this.currentAdvices[0].advice_doctor !=
              this.$store.getters.user.admin.id
          ) {
          }
          let is_sub = 2
          DeleteDoctorAdviceNew(group_no, advice_id, mode, is_sub)
            .then(rs => {
              if (rs.data.state == 1) {
                Toast.success('删除成功')
                var adviceArr = this.advice_groups[this.current_group_index]
                  .advices

                for (let y = ids.length - 1; y >= 0; y--) {
                  for (let i = adviceArr.length - 1; i >= 0; i--) {
                    if (
                      adviceArr[i].id == ids[y] ||
                        adviceArr[i].parent_id == ids[y]
                    ) {
                      adviceArr.splice(i, 1)
                    }
                  }
                }
                this.currentSubAdvices = []
                this.currentAdvices = []
                for (let i = 0; i < this.advice_groups.length; i++) {
                  for (
                    let y = 0;
                    y < this.advice_groups[i].advices.length;
                    y++
                  ) {
                    var advices = this.advice_groups[i].advices[y]
                    advices.is_selected = 0
                  }
                }
              } else {
                Toast.fail(rs.data.msg)
              }
            })
            .catch(err => {
              Toast.fail(err)
            })
        })
      } else {
        if (this.current_group_index < 0) {
          return
        }
        var group = this.advice_groups[this.current_group_index]

        Dialog.confirm({
          title: '删除医嘱',
          message: '确认删除这组医嘱吗?'
        }).then(() => {
          Toast.loading({forbidClick: true, duration: 0})
          var group_no = group.group_no <= 0 ? 0 : group.group_no
          var advice_id = 0
          if (group.group_no <= 0) {
            advice_id = group.advices[0].id
          } else if (this.current_advice != null) {
            group_no = 0
            advice_id = this.current_advice.id
          }

          let mode = '4'
          if (
            group.advices[0].advice_doctor !=
              this.$store.getters.user.admin.id &&
              group.advices[0].advice_doctor > 0
          ) {
            mode = '5'
          }
          let is_sub = 2
          DeleteDoctorAdviceNew(group_no, advice_id, mode, is_sub)
            .then(rs => {
              if (rs.data.state == 1) {
                Toast.success('删除成功')
                // if (group.group_no <= 0) {
                //   this.advice_groups.splice(this.current_group_index, 1);
                // } else {
                if (this.current_advice_index >= 0) {
                  // if (group.advices.length <= 1) {
                  //   this.advice_groups.splice(this.current_group_index, 1);
                  // } else {
                  var advice = group.advices[this.current_advice_index]
                  if (advice.parent_id > 0) {
                    group.advices.splice(this.current_advice_index, 1)
                  } else {
                    var child_count = 0
                    for (
                      let index = this.current_advice_index + 1;
                      index < group.advices.length;
                      index++
                    ) {
                      const adv = group.advices[index]
                      if (adv.parent_id == advice.id) {
                        child_count++
                      }
                    }
                    group.advices.splice(
                      this.current_advice_index,
                      child_count + 1
                    )
                  }
                  if (group.advices.length == 0) {
                    this.advice_groups.splice(this.current_group_index, 1)
                  }
                  // }
                } else {
                  this.advice_groups.splice(this.current_group_index, 1)
                }
                // }
                this.cancelAdviceSelect()
              } else {
                Toast.fail(rs.data.msg)
              }
            })
            .catch(err => {
              Toast.fail(err)
            })
        })
      }
    },
    checkAdvice () {
      if (this.is_has_check == false) {
        Toast.fail('你没有核对医嘱的权限')
        return false
      }

      if (this.currentAdvices.length <= 0) {
        return
      }

      if (this.current_select_object == 1) {
        var isCheck = true
        var adviceArr = this.advice_groups[this.current_group_index].advices
        for (let i = 0; i < adviceArr.length; i++) {
          if (adviceArr[i].check_state == 0 && adviceArr[i].is_selected == 1) {
            isCheck = false
          }
        }
        if (isCheck) {
          Toast.fail('所选医嘱已核对')
          return false
        }

        for (let i = 0; i < adviceArr.length; i++) {
          if (
            adviceArr[i].is_selected == 1 &&
              adviceArr[i].execution_staff > 0 &&
              adviceArr[i].execution_staff == this.$store.getters.user.admin.id
          ) {
            Toast.fail('核对与执行不能是同一人')
            return false
          }
        }

        var currentAdviceIdArr = []
        for (let i = 0; i < adviceArr.length; i++) {
          if (adviceArr[i].is_selected == 1) {
            currentAdviceIdArr.push(adviceArr[i].id)
          }
        }

        if (currentAdviceIdArr.length <= 0) {
          Toast.fail('请选择想要核对的医嘱')
          return false
        }

        this.currentAdviceIdsStr = currentAdviceIdArr.join(',')
        if (this.currentAdviceIdsStr == '') {
          Toast.fail('请选择想要核对的医嘱')
          return false
        }
      }
      else {
        if (!(this.current_group_index >= 0 && this.current_advice_index < 0)) {
          return
        }
        var isCheck = true
        var group_top_advice = this.advice_groups[this.current_group_index]
          .advices[0]

        var adviceArr = this.advice_groups[this.current_group_index].advices
        var advice = null
        for (let i = 0; i < adviceArr.length; i++) {
          if (adviceArr[i].check_state == 0) {
            isCheck = false
          }
        }

        if (isCheck) {
          Toast.fail('所选医嘱已核对')
          return false
        }

        for (let i = 0; i < adviceArr.length; i++) {
          if (
            adviceArr[i].is_selected == 1 &&
              adviceArr[i].execution_staff > 0 &&
              adviceArr[i].execution_staff == this.$store.getters.user.admin.id
          ) {
            Toast.fail('核对与执行不能是同一人')
            return false
          }
        }

        // if (
        //   group_top_advice.execution_staff > 0 &&
        //   group_top_advice.execution_staff == this.$store.getters.user.user.id
        // ) {
        //   Toast.fail('核对与执行不能是同一人')
        //   return false
        // }
      }

      Dialog.confirm({
        title: '医嘱核对',
        message: '确认提交核对?'
      }).then(() => {
        var params = null
        Toast.loading({forbidClick: true, duration: 0})
        if(this.advice_groups[this.current_group_index].advices[0].origin == 2) {
          params = {
            origin:2,
            advice_id: this.advice_groups[this.current_group_index].advices[0].id
          }
        }else{
          if (this.current_select_object == 1) {
            params = {
              origin:1,
              groupno: 0,
              advice_id: this.currentAdviceIdsStr
            }
          } else {
            var group = this.advice_groups[this.current_group_index]
            params = {
              origin:1,
              groupno: group.group_no <= 0 ? 0 : group.group_no,
              advice_id: group.group_no <= 0 ? group.advices[0].id : 0
            }
          }

        }

        params['mode'] = '7'
        CheckDoctorAdvice(params)
          .then(response => {
            if (response.data.state == 0) {
              Toast.fail('你没有权限核对医嘱！')
              return false
            } else {
              Toast.success('核对成功！')

              var advice = response.data.data.advice
              if (this.current_select_object == 1) {
                var ids = this.currentAdviceIdsStr.split(',')

                var adviceArr = this.advice_groups[this.current_group_index]
                  .advices
                for (let i = 0; i < adviceArr.length; i++) {
                  for (let a = 0; a < ids.length; a++) {
                    if (
                      (adviceArr[i].check_state == 0 &&
                          adviceArr[i].id == ids[a]) ||
                        (adviceArr[i].check_state == 0 &&
                          adviceArr[i].parent_id == ids[a])
                    ) {
                      adviceArr[i].checker = advice.checker
                      adviceArr[i].check_time = advice.check_time
                      adviceArr[i].check_state = advice.check_state
                    }
                  }
                }
              } else {
                for (let index = 0; index < group.advices.length; index++) {
                  const adv = group.advices[index]
                  adv.checker = advice.checker
                  adv.check_time = advice.check_time
                  adv.check_state = advice.check_state
                }
              }
            }
          })
          .catch(err => {
            Toast.fail(err)
          })
      })
      // .catch(err => {
      //   Toast.fail(err);
      // });
    },
    execAdvice () {
      if (this.is_has_exce == false) {
        Toast.fail('你没有执行医嘱的权限')
        return false
      }

      if (this.currentAdvices.length <= 0) {
        return
      }
      if (this.current_select_object == 1) {
        var isExecution = true
        var adviceArr = this.advice_groups[this.current_group_index].advices
        for (let i = 0; i < adviceArr.length; i++) {
          if (
            adviceArr[i].execution_state == 2 &&
              adviceArr[i].is_selected == 1
          ) {
            isExecution = false
          }
        }
        if (isExecution) {
          Toast.fail('所选医嘱已停止或执行')
          return false
        }

        for (let i = 0; i < adviceArr.length; i++) {
          if (
            adviceArr[i].is_selected == 1 &&
              adviceArr[i].checker > 0 &&
              adviceArr[i].checker == this.$store.getters.user.admin.id
          ) {
            Toast.fail('核对与执行不能是同一人')
            return false
          }
        }
        var currentAdviceIdArr = []
        for (let i = 0; i < adviceArr.length; i++) {
          if (adviceArr[i].is_selected == 1) {
            currentAdviceIdArr.push(adviceArr[i].id)
          }
        }
        this.currentAdviceIdsStr = currentAdviceIdArr.join(',')
        this.nowExecTime = new Date(adviceArr[0].start_time * 1000)
      } else {
        if (!(this.current_group_index >= 0 && this.current_advice_index < 0)) {
          return
        }
        var isExecution = true
        var group_top_advice = this.advice_groups[this.current_group_index]
          .advices[0]

        var adviceArr = this.advice_groups[this.current_group_index].advices
        for (let i = 0; i < adviceArr.length; i++) {
          if (
            adviceArr[i].is_selected == 1 &&
              adviceArr[i].execution_state == 2
          ) {
            isExecution = false
          }
        }
        if (isExecution) {
          Toast.fail('所选医嘱已停止或执行')
          return false
        }

        for (let i = 0; i < adviceArr.length; i++) {
          if (
            adviceArr[i].is_selected == 1 &&
              adviceArr[i].checker > 0 &&
              adviceArr[i].checker == this.$store.getters.user.admin.id
          ) {
            Toast.fail('核对与执行不能是同一人')
            return false
          }
        }

        this.nowExecTime = new Date(group_top_advice.start_time * 1000)
      }
      this.$refs.exec_time.open()
    },
    openNewChild () {
      if(this.current_advice.origin== 2){
        Toast.fail('所选医嘱属于his医嘱无法添加子药')
        return false
      }
      if (this.current_advice == null) {
        return
      }

      if (this.currentAdvices.length == 0) {
        return false
      }
      this.current_advice = this.currentAdvices[0]
      this.group_no = this.current_advice.groupno

      if (
        this.current_advice.stop_state == 1 ||
          this.current_advice.execution_state == 1 ||
          this.current_advice.check_state == 1
      ) {
        Toast.fail('所选医嘱已停止或执行或核对')
        return false
      }

      this.index = 2
      var start_time = uParseTime(
        this.current_advice.start_time,
        '{y}-{m}-{d} {h}:{i}'
      )
      this.$refs.subdrug_form.showWithNewSubDrug(
        this.current_advice.id,
        this.record_date,
        start_time,
        this.current_advice.delivery_way,
        this.current_advice.execution_frequency,
        this.group_no
      )
    },
    openNewAdvice () {

      if (this.is_has_create == false) {
        Toast.fail('你没有新增医嘱权限')
        return false
      }

      this.currentAdvices = []
      this.currentSubAdvices = []
      for (let i = 0; i < this.advice_groups.length; i++) {
        for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
          var advices = this.advice_groups[i].advices[y]
          advices.is_selected = 0
        }
      }

      this.index = 1
      this.current_group_index = -1
      this.current_advice_index = -1
      this.current_advice = null
    },
    modifySubdviceAction: function () {
      if (this.currentSubAdvices.length <= 0) {
        return
      }

      var advice = this.currentSubAdvices[0]

      if (this.base_drug_cofig != null && this.base_drug_cofig.is_open == 1 && advice.execution_state == 1) {
        Toast.fail('医嘱已执行，无法修改')
        return
      }

      if (this.private_drug_config != null && this.private_drug_config.drug_start == 1 && advice.execution_state == 1) {
        Toast.fail('医嘱已执行，无法修改')
        return
      }

      if (this.current_advice_index >= 0) {
        this.index = 3
        var advice = this.currentSubAdvices[0]
        this.$refs.sub_modify_advice_form.showWithModify({
          id: advice.id,
          parent_id: advice.parent_id,
          title: advice.advice_name,
          advice_desc: advice.advice_desc,
          advice_doctor: advice.advice_doctor,
          remark: advice.remark,
          drug_spec: advice.drug_spec,
          drug_spec_unit: advice.drug_spec_unit,
          delivery_way: advice.delivery_way,
          execution_frequency: advice.execution_frequency,
          single_dose: advice.single_dose,
          single_dose_unit: advice.single_dose_unit,
          prescribing_number: advice.prescribing_number,
          prescribing_number_unit: advice.prescribing_number_unit

        })
      }
    },
    modifyAdviceAction: function () {
      // if(this.is_has_modify == false){
      //   Toast.fail('你没有修改医嘱权限')
      //   return false
      // }
      // if(this.is_has_modify_other == false){
      //   Toast.fail('你没有修改他人医嘱权限')
      //   return false
      // }
      var group = this.advice_groups[this.current_group_index]

      var advice = this.currentAdvices[0]

      if (advice.origin == 2){
        Toast.fail('所选医嘱属于his医嘱无法修改医嘱')
        return false
      }

      if (this.currentAdvices.length != 1 || this.current_select_object == 2) {
        return
      }
      if (this.current_group_index < 0) {
        return
      }
      var group = this.advice_groups[this.current_group_index]

      var advice = this.currentAdvices[0]

      if (this.base_drug_cofig != null && this.base_drug_cofig.is_open == 1 && advice.execution_state == 1) {
        Toast.fail('医嘱已执行，无法修改')
        return
      }

      if (this.private_drug_config != null && this.private_drug_config.drug_start == 1 && advice.execution_state == 1) {
        Toast.fail('医嘱已执行，无法修改')
        return
      }

      if (this.current_advice_index >= 0) {
        this.index = 3
        var advice = this.currentAdvices[0]
        this.$refs.modify_advice_form.showWithModify({
          id: advice.id,
          parent_id: advice.parent_id,
          title: advice.advice_name,
          advice_desc: advice.advice_desc,
          advice_doctor: advice.advice_doctor,
          remark: advice.remark,
          start_time: advice.start_time,
          drug_spec: advice.drug_spec,
          drug_spec_unit: advice.drug_spec_unit,
          delivery_way: advice.delivery_way,
          execution_frequency: advice.execution_frequency,
          single_dose: advice.single_dose,
          single_dose_unit: advice.single_dose_unit,
          prescribing_number: advice.prescribing_number,
          prescribing_number_unit: advice.prescribing_number_unit,
          drug_id: advice.drug_id,
          way: advice.way,
          drug_name_id: advice.drug_name_id
        })
      } else {
        if (group.group_no <= 0) {
          this.index = 3
          var advice = group.advices[0]
          this.$refs.modify_advice_form.showWithModify({
            id: advice.id,
            parent_id: advice.parent_id,
            title: advice.advice_name,
            advice_desc: advice.advice_desc,
            remark: advice.remark,
            drug_spec: advice.drug_spec,
            drug_spec_unit: advice.drug_spec_unit,
            delivery_way: advice.delivery_way,
            execution_frequency: advice.execution_frequency,
            single_dose: advice.single_dose,
            single_dose_unit: advice.single_dose_unit,
            prescribing_number: advice.prescribing_number,
            prescribing_number_unit: advice.prescribing_number_unit,
            drug_id: advice.drug_id,
            way: advice.way,
            drug_name_id: advice.drug_name_id
          })
        } else {
          // this.index = 4
          // this.$refs.modify_advice_group.show(group.group_no, group.advices)
        }
      }
    },

    cancelAdviceSelect: function () {

      this.current_group_index = -1
      this.current_advice_index = -1
      this.current_advice = null
    },
    selectAdviceAction: function (group_index, advice_index, advice) {

      if (
        (this.current_group_index != -1 &&
            this.current_group_index != group_index) ||
          advice.parent_id > 0
      ) {
        // 选择其他组，将原来的组选择状态清除
        this.currentAdvices = []
        this.currentSubAdvices = []
        for (let i = 0; i < this.advice_groups.length; i++) {
          for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
            var advices = this.advice_groups[i].advices[y]
            advices.is_selected = 0
          }
        }
      }

      for (let i = 0; i < this.advice_groups.length; i++) {
        // 选择子医嘱，将已经选择的医嘱选择状态清除
        for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
          var advices = this.advice_groups[i].advices[y]
          if (advices.parent_id > 0) {
            advices.is_selected = 0
          }
        }
      }

      for (let i = 0; i < this.advice_groups.length; i++) {
        // 设置选择状态
        for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
          var advices = this.advice_groups[i].advices[y]
          if (advices.id == advice.id) {
            if (advice.is_selected == 1) {
              advice.is_selected = 0
              for (let a = this.currentAdvices.length - 1; a >= 0; a--) {
                if (this.currentAdvices[a].id == advice.id) {
                  this.currentAdvices.splice(a, 1)
                }
              }
            } else {
              advice.is_selected = 1
              if (advice.parent_id == 0) {
                this.currentAdvices.push(advice)
              }
            }
          }
        }
      }

      if (advice.parent_id == 0) {
        this.currentSubAdvices = []
      } else {
        this.currentSubAdvices.push(advice)
      }

      this.current_select_object = 1 // 单条医嘱
      this.current_group_index = group_index
      this.current_advice_index = advice_index
      this.current_advice = advice
    },
    selectGroupAdviceAction: function (
      group_index,
      advice_index,
      advice,
      group
    ) {
      if (
        this.current_group_index != -1 &&
          this.current_group_index != group_index
      ) {
        // 选择其他组，将原来的组选择状态清除
        this.currentAdvices = []
        this.currentSubAdvices = []
        for (let i = 0; i < this.advice_groups.length; i++) {
          for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
            var advices = this.advice_groups[i].advices[y]
            advices.is_selected = 0
          }
        }
      }

      for (let i = 0; i < this.advice_groups.length; i++) {
        // 选择子医嘱，将已经选择的医嘱选择状态清除
        for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
          var advices = this.advice_groups[i].advices[y]
          if (advices.parent_id > 0) {
            advices.is_selected = 0
          }
        }
      }
      this.currentAdvices = []
      for (let i = 0; i < this.advice_groups.length; i++) {
        for (let y = 0; y < this.advice_groups[i].advices.length; y++) {
          var advices = this.advice_groups[i].advices[y]
          if (advices.groupno == group.group_no) {
            advices.is_selected = 1
            this.currentAdvices.push(advices)
          }
        }
      }
      this.current_select_object = 2 // 单组医嘱
      this.current_group_index = group_index
      this.current_advice_index = advice_index
      this.current_advice = advice
    },
    getPermission () {
      request
        .get('/m/api/permission/get', {
          params: {
            create_url: '/m/api/advice/creategroup?mode=1',
            modify_url: '/m/api/advice/edit?mode=2',
            modify_other_url: '/m/api/advice/edit?mode=3',
            del_url: '/m/api/newadvice/delete?mode=4',
            del_other_url: '/m/api/newadvice/delete?mode=5',
            exce_url: '/m/api/advice/exec?mode=6',
            check_url: '/m/api/advice/check?mode=7',
            modify_exce_url: '/m/api/advice/exec/modify?mode=8',
            module: 4
          }
        })
        .then(res => {

          if (res.data.state == 0) {
            this.hasPermission = false
          } else if (res.data.state == 1) {
            this.is_has_create = res.data.data.is_has_create
            this.is_has_exce = res.data.data.is_has_exce
            this.is_has_check = res.data.data.is_has_check
            this.is_has_modify = res.data.data.is_has_modify
            this.is_has_modify_other = res.data.data.is_has_modify_other
            this.is_has_modify_exce = res.data.data.is_has_modify_exce
            this.is_has_del = res.data.data.is_has_del
            this.is_has_del_other = res.data.data.is_has_del_other
          }
        })
    },
    getTime (time) {
      return parseTime(time, '{h}:{i}')
    },
    menuComfirmFour:function(start_time,remark){
       var params = {
         patient_id:this.$route.query.patient_id,
         record_date:this.$route.query.date,
         start_time:start_time,
         module:4,
         remark:remark,
       }
      
      saveMobileInformation(params).then(response=>{
        if(response.data.state == 1){
           this.infor_visibility = false
           Toast.success('申请成功')
        }
      })
    },
    menuCancleFour:function(){
     this.infor_visibility = false
    
    },
  }
}
</script>

<style style="stylesheet/scss" lang="scss" scoped>
  #dialogTop {
  @media only screen and (max-width: 415px) {
  height: 13.8rem !important;
  }
  }
  .DialogContent {
  .content {
  .yzNav {
  position: fixed;
  top: 0.16rem;
  }
  }
  }
  .orderTable {
  width: 100%;
  }
  .table {
  width: 1200px;
  @media only screen and (max-width: 415px) {
  width: 850px;
  }
  @media only screen and (min-width: 415px) and (max-width: 767px) {
  width: 1000px;
  }
  tr {
  th {
  background: $main-color;
  color: #fff;
  height: 1.2rem;
  line-height: 1.2rem;
  }
  td {
  line-height: 0.6rem;
  .txt {
  // float: left;
  padding: 0 10px 0 10px;
  // width: 75%;
  text-align: left;
  }
  .ico {
  float: right;
  width: 60px;
  text-align: right;
  padding-right: 3px;
  }
  .iconfont {
  font-size: 20px;
  padding: 0 2px;
  color: #7b8a97;
  }
  .handle {
  color: #409eff;
  // padding: 0 7px;
  }
  }
  .advice_content {
  // background: #eff6fc;
  }
  .subadvice_content {
  // background: #fafcfe;
  padding-left: 20px;
  }
  .td-active {
  background: #badcff !important;
  }
  }
  .row-class-active {
  td {
  background: #badcff;
  }
  }
  }
  .content {
  .cell {
  float: left;
  width: 3.42rem;
  margin: 0.35rem 0.3rem 0 0.4rem;
  label {
  display: block;
  height: 0.55rem;
  line-height: 0.55rem;
  color: $pgh-color;
  }
  select {
  width: 100%;
  padding: 0.2rem 0;
  border: 1px $border-color solid;
  border-radius: 2px;
  padding-left: 5px;
  }

  .inputBox {
  border: 1px $border-color solid;
  border-radius: 2px;
  padding: 0.18rem 0;
  padding-left: 5px;
  }

  .textarea {
  width: 100%;
  height: 1.22rem;
  border: 1px $border-color solid;
  border-radius: 2px;
  padding-left: 5px;
  }
  }
  .width {
  width: 90%;
  @include box-sizing;
  margin-top: 1rem;
  label {
  display: inline-block;
  }
  button {
  background: $main-color;
  color: #fff;
  border-radius: 6px;
  width: 3rem;
  height: 0.9rem;
  line-height: 0.9rem;
  text-align: center;
  margin: 0 0.1rem 0.6rem 0.1rem;
  border: 1px $main-color solid;
  &.smt-danger {
  background: #fff;
  color: $main-color;
  }
  }
  }
  .center {
  text-align: center;
  }
  }
  .yzNav {
  display: flex;
  flex-wrap: wrap;
  span {
  width: 15%;
  @media only screen and (max-width: 415px) {
  padding: 0;
  }
  // @media only screen and (min-width: 666px) and (max-width: 737px) {
  // width: 16% !important;
  // }
  }
  }
  #fontSize {
  font-size: 0.34rem;
  }
  .typeInput {
  .el-input__inner {
  @media only screen and (min-width: 768px) {
  height: 60px;
  line-height: 60px;
  }
  }
  }

  .content {
  .cell {
  float: left;
  width: 6.5rem;
  margin: 0.35rem 0.3rem 0 0.4rem;
  label {
  display: block;
  height: 0.6rem;
  line-height: 0.6rem;
  color: $pgh-color;
  font-size: 0.45rem;
  margin-bottom: 0.2rem;
  }
  select {
  width: 100%;
  padding: 0.2rem 0;
  border: 1px $border-color solid;
  border-radius: 2px;
  padding-left: 5px;
  }

  .inputBox {
  border: 1px $border-color solid;
  border-radius: 2px;
  padding: 0.18rem 0;
  padding-left: 5px;
  }

  .textarea {
  width: 100%;
  height: 1.22rem;
  border: 1px $border-color solid;
  border-radius: 2px;
  padding-left: 5px;
  }
  }

  .doctor-name {
  line-height: 0.7rem;
  font-size: 0.35rem;
  margin-left: 0.4rem;
  }

  .row-class-active > td {
  background: #badcff !important;
  }
  }
</style>
