<template>
  <div class="fixedTop">
    <div class="choice" >
      <ul>
        <li>
          日期查询：
          <div class @click="selectStartSearchTime">
            {{startSearchTimeShow}}
            <span class="iconfont">&#xe74a;</span>
          </div>
          <span class="line"></span>
          <div class @click="selectEndSearchTime">
            {{endSearchTimeShow}}
            <span class="iconfont">&#xe74a;</span>
          </div>
        </li>

        <el-popover placement="bottom" trigger="click">
          <li slot="reference">
            {{adviceNameShow}}
            <span class="iconfont">&#xe74a;</span>
          </li>
          <div class="popover-demo-content">
            <ul>
              <li
                v-for="onet in adviceTypes"
                :class="onet.id == queryParams.advice_type?'tick':''"
                :key="onet.id"
                @click="selectType(onet.id,onet.show)"
              >{{onet.name}}</li>
            </ul>
          </div>
        </el-popover>

        <el-popover placement="bottom" trigger="click">
          <li slot="reference">
            {{stopNameShow}}
            <span class="iconfont">&#xe74a;</span>
          </li>
          <div class="popover-demo-content">
            <ul>
              <li
                v-for="onet in stopTypes"
                :class="onet.id == queryParams.stop_state?'tick':''"
                :key="onet.id"
                @click="selectStopType(onet.id, onet.show)"
              >{{onet.name}}</li>
            </ul>
          </div>
        </el-popover>
      </ul>
    </div>

    <div class="tableSearch">
      <ul>
        <li>
          <span class="iconfont">&#xe741;</span>
          <input
            type="search"
            class="search"
            v-model="queryParams.keywords"
            @change="searchKey()"
            placeholder="搜索"
          >
        </li>
      </ul>
    </div>
    <div style="width:100%;overflow:hildden;overflow-x:auto;" class="AdviceTable">
      <table class="table" style>
        <tr>
          <!-- <th width="150px">序号</th> -->
          <th width="177px">期效</th>

          <th width="334px">开始时间</th>
          <th width="415px">医嘱内容</th>
          <th width="220px">规格</th>
          <th width="164px">开药数量</th>
          <th width="164px">单次用量</th>
          <th width="286px">给药途径</th>
          <th width="177px">执行频率</th>
          <th width="177px">执行时间</th>
          <th width="177px">执行护士</th>

          <th width="177px">开嘱医生</th>
          <th width="177px">开嘱时间</th>
          <th width="177px">校对护士</th>
          <th width="177px">校对时间</th>

          <!-- <th width="200px">备注</th> -->
          <th width="177px">停止时间</th>
          <th width="177px">停止原因</th>
          <th width="177px">停嘱医生</th>
          <th width="700px">操作</th>
        </tr>
        <template v-for="(group, group_index) in advice_groups">
          <tr v-for="(advice, advice_index) in group.advices" :key="advice.id">

            <!--<td v-if="advice.patient_id > 0" :rowspan="group.advices.length">-->
              <!--<span></span>-->
            <!--</td>-->

            <td v-if="advice_index == 0" :rowspan="group.advices.length">
              <span v-if="advice.advice_type == 1">长嘱</span>
              <span v-if="advice.advice_type == 2">临嘱</span>
              <span v-if="advice.advice_type == 3">临嘱</span>

            </td>

            <td v-if="advice_index == 0" :rowspan="group.advices.length">{{ parseTime(advice.start_time, "{m}-{d} {h}:{i}") }}</td>
            <td :class="{ 'advice_name': advice.parent_id == 0, 'subdrug_name': advice.parent_id > 0 }">{{ advice.advice_name }}</td>
            <td>{{ advice.advice_desc }}</td>
            <td ><span v-if="advice.prescribing_number">{{ advice.prescribing_number }}{{ advice.prescribing_number_unit }}</span></td>
            <td ><span v-if="advice.single_dose">{{ advice.single_dose }} {{ advice.single_dose_unit }}</span></td>
            <td>{{ advice.parent_id == 0 ? advice.delivery_way : "" }}</td>
            <td>{{ advice.parent_id == 0 ? advice.execution_frequency : "" }}</td>

            <td v-if="advice_index == 0" :rowspan="group.advices.length">{{ parseTime(advice.execution_time, "{m}-{d} {h}:{i}") }}</td>
            <td  v-if="advice_index == 0" :rowspan="group.advices.length">
              <span v-if="advice.stop_state == 1 && advice.parent_id == 0">{{ tranDoctor(advice.execution_staff) }}</span>
            </td>



            <td v-if="advice_index == 0" :rowspan="group.advices.length">
              <span v-if="advice.stop_state == 1 && advice.parent_id == 0">{{ tranDoctor(advice.advice_doctor) }}</span>
            </td>
            <td v-if="advice_index == 0" :rowspan="group.advices.length">{{ parseTime(advice.created_time, "{m}-{d} {h}:{i}") }}</td>

            <td v-if="advice_index == 0" :rowspan="group.advices.length">
              <span v-if="advice.stop_state == 1 && advice.parent_id == 0">{{ tranDoctor(advice.checker) }}</span>
            </td>
            <td v-if="advice_index == 0" :rowspan="group.advices.length">{{ parseTime(advice.check_time, "{m}-{d} {h}:{i}") }}</td>

            <!-- <td>{{ advice.remark }}</td> -->
            <td v-if="advice_index == 0" :rowspan="group.advices.length">{{ advice.stop_state == 1 && advice.parent_id == 0 ? parseTime(advice.stop_time, "{y}-{m}-{d} {h}:{i}") : "" }}</td>
            <td v-if="advice_index == 0" :rowspan="group.advices.length">
              <span v-if="advice.stop_state == 1 && advice.parent_id == 0">{{ advice.stop_reason }}</span>
            </td>
            <td  v-if="advice_index == 0" :rowspan="group.advices.length">
              <span v-if="advice.stop_state == 1 && advice.parent_id == 0">{{ tranDoctor(advice.stop_doctor) }}</span>
            </td>

            <td class="advice_name">
              <span class="xg" @click="modifyAdviceAction(group_index, advice_index)">
                <span class="iconfont">&#xe6f7;</span>修改医嘱
              </span>
              <span class="xg" v-if="advice.parent_id == 0 && advice.stop_state != 1" @click="stopAdviceAction(group_index, advice_index)">
                <span class="iconfont">&#xe64c;</span>停止医嘱
              </span>
              <span class="sc" @click="deleteAdviceAction(group_index, advice_index)">
                <span class="iconfont">&#xe6f8;</span>删除医嘱
              </span>
              <span class="xg" v-if="advice.parent_id == 0 && advice.stop_state != 1" @click="addSubdrugAction(group_index, advice_index)">
                <span class="iconfont">&#xe604;</span>添加子药
              </span>
            </td>
          </tr>
        </template>
        <!-- <tr v-for="(item,index) in tableDate" :key="index" :value="item.value">
          <td>{{setAdviceNo(index, item)}}</td>
          <td>{{item.start_time_show}}</td>
          <td>{{item.advice_name}}</td>
          <td>{{item.drug_spec}} {{ item.drug_spec_unit }}</td>
          <td>{{item.single_dose}} {{item.single_dose_unit }}</td>
          <td>
            <span v-if="item.parent_id==0">{{item.delivery_way}}</span>
          </td>
          <td>
            <span v-if="item.parent_id==0">{{item.execution_frequency}}</span>
          </td>
          <td>{{tranDoctor(item.advice_doctor)}}</td>
          <td>{{item.advice_affirm}}</td>
          <td>{{item.remark}}</td>
          <td>{{item.stop_time_show}}</td>
          <td>
            <span v-if="item.parent_id==0">{{item.stop_reason}}</span>
          </td>
          <td>
            <span v-if="item.stop_state==1&&item.parent_id==0">{{tranDoctor(item.stop_doctor)}}</span>
          </td>
          <td>
            <span class="xg" @click="openEdit(index, item)">
              <span class="iconfont">&#xe6f7;</span>修改医嘱
            </span>
            <span class="xg" @click="openStop(index, item)">
              <span class="iconfont">&#xe64c;</span>停止医嘱
            </span>
            <span class="sc" @click="deleteAdvice(index, item)">
              <span class="iconfont">&#xe6f8;</span>删除医嘱
            </span>
            <span class="xg" @click="openNewChild(index, item)">
              <span class="iconfont">&#xe604;</span>添加医嘱
            </span>
          </td>
        </tr> -->
      </table>
      <!--<div class="NoData" v-show="tableDate.length == 0"><img src="@/assets/login/data.jpg" alt=""></div>-->
      <div class="NoData" v-show="advice_groups.length == 0">
        <img style="margin-top: 50px; margin-bottom: 50px" src="@/assets/login/data.jpg" alt>
      </div>
    </div>
    <mt-datetime-picker
      ref="start_date_picker"
      type="date"
      @confirm="handleStartDateConfirm"
      v-model="start_time"
    ></mt-datetime-picker>

    <mt-datetime-picker
      ref="end_date_picker"
      type="date"
      @confirm="handleEndDateConfirm"
      v-model="end_time"
    ></mt-datetime-picker>

    <van-popup title="医嘱" v-model="showPopup" :overlay="true" :close-on-click-overlay="false">
      <advice-form
        ref="subdrug_form"
        @back="showPopup = false"
        @did-create-subdrug="didAddSubdrug"
        :single_dose_unit_options="unitsOption"
        :prescribing_number_unit_options="unitsOption"
      ></advice-form>
      
      <modify-advice-form
        ref="modify_advice_form"
        @back="showPopup = false"
        @did-modify="didModifyAdvice"
        :delivery_way_options="deliveryWayOptions"
        :execution_frequency_options="executionFrequencyOptions"
        :single_dose_unit_options="unitsOption"
        :prescribing_number_unit_options="unitsOption"
      ></modify-advice-form>

      <!-- <div class="Dialog" v-show="showForm">
        <div class="DialogTit">
          <div class="back" @click="popupDidHide()">
            <span class="iconfont">&#xe720;</span>返回
          </div>
          <h1 class="name">{{formTitle}}</h1>
          <span class="success" v-if="adviceForm.id>0" @click="submitEditAdvice">完成</span>
          <span class="success" v-else @click="submitNewAdvice">完成</span>
        </div>
        <div class="DialogContent choose advice-top" id="advice-top">
          <div class="content clearfix">
            <div>
              <div class="cell">
                <label>医嘱类型</label>
                <el-input ref="advice_type" :value="adviceForm.advice_type==1?'长期':'临时'" disabled></el-input>
              </div>
              <div class="cell">
                <label>医嘱时间</label>
                <el-input v-model="adviceForm.advice_date" readonly></el-input>
              </div>
              <div class="cell">
                <label>开始时间</label>
                <el-input v-model="adviceForm.start_time" readonly @focus="chooseTime"></el-input>
              </div>
              <div class="cell">
                <label>医嘱名称</label>
                <el-input
                  v-model="adviceForm.advice_name"
                  readonly
                  @focus="showSubMenu('advice_name')"
                ></el-input>
              </div>
              <div class="cell">
                <label>给药途径</label>

                <el-input
                  v-model="adviceForm.delivery_way"
                  readonly
                  @focus="showSubMenu('delivery_way')"
                  :disabled="adviceForm.parent_id==0?false:true"
                ></el-input>
              </div>
              <div class="cell">
                <label>执行频率</label>

                <el-input
                  v-model="adviceForm.execution_frequency"
                  readonly
                  @focus="showSubMenu('execution_frequency')"
                  :disabled="adviceForm.parent_id==0?false:true"
                ></el-input>
              </div>
              <div class="cell">
                <label>医嘱描述</label>
                <el-input v-model="adviceForm.advice_desc"></el-input>
              </div>
              <div class="cell">
                <label>单次用量</label>
                <input
                  type="number"
                  class="inputBox"
                  style="width:60%"
                  v-model="adviceForm.single_dose"
                >
                <input
                  type="text"
                  readonly
                  class="inputBox"
                  style="width:35%"
                  v-model="adviceForm.single_dose_unit"
                  @focus="showSubMenu('single_dose_unit')"
                >
              </div>
              <div class="cell">
                <label>开药数量</label>
                <input
                  type="number"
                  class="inputBox"
                  style="width:60%"
                  v-model="adviceForm.prescribing_number"
                >
                <input
                  type="text"
                  readonly
                  class="inputBox"
                  style="width:35%"
                  v-model="adviceForm.prescribing_number_unit"
                  @focus="showSubMenu('prescribing_number_unit')"
                >
              </div>
              <div class="cell width">
                <label>开嘱医生：</label>
                <span>{{doctor}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <mt-datetime-picker ref="picker" type="datetime" @confirm="handleConfirm" v-model="nowTime"></mt-datetime-picker>
      <check-box-sub-menu
        :visibility="visibility"
        v-on:menu-cancle="menuCancle"
        v-on:menu-comfirm="menuComfirm"
        :propsForm="propForm"
      ></check-box-sub-menu> -->
    </van-popup>
    <van-popup title="停止医嘱" v-model="stopPopup" :overlay="true" :close-on-click-overlay="false">
      <div class="Dialog" v-show="showForm">
        <div class="DialogTit">
          <div class="back" @click="popupDidHide()">
            <span class="iconfont">&#xe720;</span>返回
          </div>
          <h1 class="name">停止医嘱</h1>
          <span class="success" @click="submitStopAdvice">完成</span>
        </div>
        <div class="DialogContent choose advice-top" id="advice-stop">
          <div class="content clearfix">
            <div>
              <div class="cell width">
                <label>停止时间</label>
                <el-input v-model="stopForm.stop_time" readonly @focus="chooseStopTime"></el-input>
              </div>

              <div class="cell width">
                <label>停止原因</label>
                <el-input v-model="stopForm.stop_reason" type="textarea"></el-input>
              </div>
              <div class="cell width">
                <label>当前医生：</label>
                <span>{{doctor}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <mt-datetime-picker
        ref="stoptime"
        type="datetime"
        @confirm="handleStopConfirm"
        v-model="nowTime"
      ></mt-datetime-picker>
    </van-popup>
  </div>
</template>

<script>
import { Toast, Dialog } from "vant";
import { GetDoctorAdvices } from "@/api/patient";
import { parseTime } from "@/utils";
import { fetchAllAdminUsers } from "@/api/doctor";
import CheckBoxSubMenu from "../dialog/subMenu/checkBoxSubMenu";
import {
  getAdviceConfig,
  CreateDoctorAdvice,
  EditDoctorAdvice,
  DeleteDoctorAdviceNew,
  ExecDoctorAdvice,
  CheckDoctorAdvice,
  StopDoctorAdvice
} from "@/api/advice";
import { getDataConfig } from "@/utils/data";
import AdviceForm from "@/pages/main/dialog/new_order/order_form";
import ModifyAdviceForm from "@/pages/main/dialog/modify_order/modify_order_form";

let allno = 1;
let adviceno = 1;

export default {
  name: "AdviceTable",
  components: {
    CheckBoxSubMenu,
    AdviceForm,
    ModifyAdviceForm,
  },
  data() {
    return {
      doctor_id: 0,
      formTitle: "修改医嘱",
      startSearchTimeShow: "选择日期",
      endSearchTimeShow: "选择日期",

      start_time: new Date(),
      end_time: new Date(),
      nowTime: new Date(),

      adviceNameShow: "医嘱类型",
      stopNameShow: "显示范围",
      adviceTypes: [
        { id: 0, name: "全部", show: "医嘱类型" },
        { id: 1, name: "长期", show: "长期" },
        { id: 3, name: "临时", show: "临时" }
      ],

      stopTypes: [
        { id: 0, name: "全部", show: "未停止" },
        { id: 2, name: "未停止", show: "未停止" },
        { id: 1, name: "已停止", show: "已停止" }
      ],
      tableDate: [],
      advice_groups: [],
      queryParams: {
        id: 0,
        advice_type: 0,
        stop_state: 0,
        start_time: "",
        end_time: "",
        keywords: "",
        need_doctor: 1
      },
      adminUserOptions: {},
      showPopup: false,
      showForm: true,
      adviceForm: {
        id: 0,
        advice_type: 3,
        advice_date: "",
        start_time: "",
        advice_name: "",
        advice_desc: "",
        single_dose: "",
        single_dose_unit: "",
        prescribing_number: "",
        prescribing_number_unit: "",
        delivery_way: "",
        execution_frequency: "",
        advice_doctor: "",
        remark: "",
        parent_id: 0
      },
      currentIndex: -1,
      doctor: "",
      visibility: false,
      propForm: {
        title: "",
        list: [],
        optionList: [],
        isMultiple: 2,
        result: [], //选中的值
        type: 1, //用来区分不同子菜单，方便对返回值进行赋值
        selectId: 0
      },
      deliveryWayOptions: [],
      deliveryWayOjb: {},
      executionFrequencyOptions: [],
      executionFrequencyObj: {},
      adviceTemplates: [],
      adviceTemplateMaps: {},
      unitsOption: [],
      unitsObj: [],
      stopPopup: false,

      stopForm: {
        id: 0,
        stop_time: "",
        stop_reason: "",
        group_index: -1,
        advice_index: -1,
      },
      record_date: "",
      patient_id: 0,

      new_subdrug_context: {
        group_index: -1,
        advice_index: -1,
      },
      modify_advice_context: {
        group_index: -1,
        advice_index: -1,
      },
    };
  },
  methods: {
    // openNewChild(index, item) {
    //   if (item.stop_state == 1 || item.execution_state == 1) {
    //     Toast("医嘱已停止或执行，不能添加子医嘱");
    //     return false;
    //   }
    //   this.adviceForm = {
    //     id: 0,
    //     advice_type: 2,
    //     advice_date: parseTime(item.advice_date, "{y}-{m}-{d}"),
    //     start_time: parseTime(item.start_time, "{y}-{m}-{d} {h}:{i}:00"),
    //     advice_name: "",
    //     advice_desc: "",
    //     single_dose: "",
    //     single_dose_unit: "",
    //     prescribing_number: "",
    //     prescribing_number_unit: "",
    //     delivery_way: item.delivery_way,
    //     execution_frequency: item.execution_frequency,
    //     advice_doctor: "",
    //     remark: "",
    //     parent_id: item.id
    //   };
    //   this.formTitle = "添加子药";
    //   this.showPopup = true;
    // },
    deleteAdviceAction: function(group_index, advice_index) {
      Dialog.confirm({
        title: "医嘱删除",
        message: "确认删除这条医嘱吗?"
      }).then(() => {
        Toast.loading({ forbidClick: true, duration: 0 });
        var group_no = 0
        var advice_id = this.advice_groups[group_index].advices[advice_index].id
        DeleteDoctorAdviceNew(group_no, advice_id).then(rs => {
          if (rs.data.state == 1) {
            var group = this.advice_groups[group_index]
            var advice = group.advices[advice_index];
            if (advice.parent_id > 0) {
              group.advices.splice(advice_index, 1);
            } else {
              var child_count = 0;
              for (
                let index = advice_index + 1;
                index < group.advices.length;
                index++
              ) {
                const adv = group.advices[index];
                if (adv.parent_id == advice.id) {
                  child_count++;
                }
              }
              group.advices.splice(
                advice_index,
                child_count + 1
              );
            }
            if (group.advices.length == 0) {
              this.advice_groups.splice(group_index, 1);
            }
            Toast.success("删除成功")

          } else {
            Toast.fail(rs.data.msg);
          }
        }).catch(err => {
          Toast.fail(err);
        })
      })
    },
    deleteResetData(index, row) {
      if (row.parent_id > 0) {
        this.tableDate.splice(index, 1);
      } else {
        var spliceIndex = -1;
        var splitNums = 0;
        for (var kndex in this.tableDate) {
          if (this.tableDate[kndex].id == row.id) {
            spliceIndex = kndex;
            splitNums++;
          } else if (this.tableDate[kndex].parent_id == row.id) {
            splitNums++;
          }
        }
        this.tableDate.splice(spliceIndex, splitNums);
      }
    },
    // openStop(index, item) {
    //   if (item.stop_state == 1) {
    //     Toast("医嘱已停止");
    //     return false;
    //   }
    //   this.stopForm.id = item.parent_id > 0 ? item.parent_id : item.id;
    //   this.stopForm.stop_time = "";
    //   this.stopForm.stop_reason = "";

    //   this.currentIndex = index;
    //   this.stopPopup = true;
    // },
    stopAdviceAction: function(group_index, advice_index) {
      var group = this.advice_groups[group_index]
      var advice = group.advices[advice_index]
      if (advice.stop_state == 1) {
        Toast("医嘱已停止");
        return
      }

      this.stopForm.id = advice.parent_id > 0 ? advice.parent_id : advice.id;
      this.stopForm.stop_time = "";
      this.stopForm.stop_reason = "";
      this.stopForm.group_index = group_index;
      this.stopForm.advice_index = advice_index;

      this.stopPopup = true;
    },
    submitStopAdvice() {
      if (this.stopForm.stop_time.length == 0) {
        Toast("请选择停止时间");
        return false;
      }
      if (this.stopForm.stop_reason.length == 0) {
        Toast("请填写停止原因");
        return false;
      }
      Toast.loading({ forbidClick: true, duration: 0 });
      StopDoctorAdvice(this.stopForm.id, {
        id: this.stopForm.id,
        stop_time: this.stopForm.stop_time,
        stop_reason: this.stopForm.stop_reason,
      }).then(response => {
        if (response.data.state == 0) {
          Toast.fail(response.data.msg);
          return false;
        } else {
          Toast.success("医嘱停止成功");

          var group_index = this.stopForm.group_index
          var advice_index = this.stopForm.advice_index
          var group = this.advice_groups[group_index]
          var advice = group.advices[advice_index]
          for (let index = advice_index; index < group.advices.length; index++) {
            const adv = group.advices[index];
            if (adv.id == advice.id || adv.parent_id == advice.id) {
              adv.stop_state = 1;
              adv.stop_doctor = response.data.data.advice.stop_doctor;
              adv.stop_reason = response.data.data.advice.stop_reason;
              adv.stop_time = response.data.data.advice.stop_time;
            }
          }
          this.popupDidHide();
          return false;
        }
      });
    },
    parseTime: function(time, layout) {
      if(time == 0){
        return ""
      }
      return parseTime(time, layout)
    },
    openEdit(index, item) {
      if (item.advice_type == 1) {
        Toast("长期医嘱不能修改");
        return false;
      }

      if (item.stop_state == 1 || item.execution_state == 1) {
        Toast("医嘱已停止或执行，不能修改");
        return false;
      }

      if (item.advice_doctor != this.doctor_id) {
        Toast("不能修改非本人添加的医嘱");
        return false;
      }

      this.currentIndex = index;
      for (var key in this.adviceForm) {
        this.adviceForm[key] = item[key];
      }
      this.adviceForm.advice_date = parseTime(
        this.adviceForm.advice_date,
        "{m}-{d}"
      );
      this.adviceForm.start_time = parseTime(
        this.adviceForm.start_time,
        "{m}-{d} {h}:{i}:00"
      );

      this.formTitle = "修改医嘱";
      this.showPopup = true;
    },
    popupDidHide() {
      this.showPopup = false;
      this.showForm = true;
      this.visibility = false;
      this.stopPopup = false;
    },
    modifyAdviceAction: function(group_index, advice_index) {
      var group = this.advice_groups[group_index]
      var advice = group.advices[advice_index]
      if (advice.advice_type == 1) {
        Toast("长期医嘱不能修改");
        return;
      }

      if (advice.stop_state == 1 || advice.execution_state == 1) {
        Toast("医嘱已停止或执行，不能修改");
        return;
      }

      if (advice.advice_doctor != this.doctor_id) {
        Toast("不能修改非本人添加的医嘱");
        return;
      }

      this.modify_advice_context.group_index = group_index
      this.modify_advice_context.advice_index = advice_index

      this.showPopup = true;
      this.$nextTick(() => {
        this.$refs.modify_advice_form.showWithModify({
          id: advice.id,
          parent_id: advice.parent_id,
          title: advice.advice_name,
          advice_desc: advice.advice_desc,
          // 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
        })
      })
    },
    didModifyAdvice: function(advice) {
      Toast.loading({ forbidClick: true, duration: 0 });
      EditDoctorAdvice(advice.id, {
        advice_name: advice.title,
        advice_desc: advice.advice_desc,
        // 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
      }).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.modify_advice_context.group_index
          var advice_index = this.modify_advice_context.advice_index
          var group = this.advice_groups[group_index]
          var advice = group.advices[advice_index]

          advice.advice_name = resp_advice.advice_name
          advice.advice_desc = resp_advice.advice_desc
          // advice.drug_spec = resp_advice.drug_spec
          // 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

          // 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.drug_spec = resp_advice.drug_spec
          //     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
          //   }
          // }

          this.$refs.modify_advice_form.dismiss()
          this.modify_advice_context.group_index = -1
          this.modify_advice_context.advice_index = -1
          this.popupDidHide();
          return false;
        }
      })
    },
    submitEditAdvice() {
      if (this.adviceForm.advice_name.length == 0) {
        Toast("请填写医嘱名称");
        return;
      }
      if (this.adviceForm.start_time.length == 0) {
        Toast("请选择开始时间");
        return;
      }
      Toast.loading({ forbidClick: true, duration: 0 });
      EditDoctorAdvice(this.adviceForm.id, this.adviceForm).then(response => {
        if (response.data.state == 0) {
          Toast.fail(response.data.msg);
          return false;
        } else {
          Toast.success("修改成功");

          for (var key in response.data.data.advice) {
            this.tableDate[this.currentIndex][key] =
              response.data.data.advice[key];
          }

          if (this.adviceForm.parent_id > 0) {
            this.tableDate[this.currentIndex].start_time_show = "";
          } else {
            this.tableDate[this.currentIndex].start_time_show = parseTime(
              response.data.data.advice.start_time,
              "{m}-{d} {h}:{i}"
            );
          }

          this.currentIndex = -1;
          this.popupDidHide();
          return false;
        }
      });
    },
    addSubdrugAction: function(group_index, advice_index) {
      var group = this.advice_groups[group_index]
      var advice = group.advices[advice_index]
      this.showPopup = true;
      this.new_subdrug_context.group_index = group_index
      this.new_subdrug_context.advice_index = advice_index

      this.$nextTick(() => {
        this.$refs.subdrug_form.showWithNewSubDrug(
          advice.id,
          parseTime(advice.record_date, "{y}-{m}-{d}"),
          parseTime(advice.start_time, "{y}-{m}-{d} {h}:{i}"),
          advice.delivery_way,
          advice.execution_frequency
        );
      })
    },
    didAddSubdrug: function(subdrug) {
      Toast.loading({ forbidClick: true, duration: 0 });
      CreateDoctorAdvice(this.patient_id, {
        parent_id: subdrug.parent_id,
        advice_type: 3,
        advice_date: subdrug.record_time,
        start_time: subdrug.start_time,
        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,
      }).then(rs => {
        if (rs.data.state == 0) {
          Toast.fail(rs.data.msg);
        } else {
          Toast.success("添加成功");
          var resp_advice = rs.data.data.advice;
          var group_index = this.new_subdrug_context.group_index
          var advice_index = this.new_subdrug_context.advice_index
          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.$refs.subdrug_form.dismiss();
          this.new_subdrug_context.group_index = -1
          this.new_subdrug_context.advice_index = -1
          this.popupDidHide();
        }
      }).catch(err => {
        Toast.fail(err);
      })
    },
    // submitNewAdvice() {
    //   if (this.adviceForm.advice_name.length == 0) {
    //     Toast("请填写医嘱名称");
    //     return;
    //   }
    //   if (this.adviceForm.start_time.length == 0) {
    //     Toast("请选择开始时间");
    //     return;
    //   }
    //   Toast.loading({ forbidClick: true, duration: 0 });
    //   CreateDoctorAdvice(this.patient_id, this.adviceForm).then(response => {
    //     if (response.data.state == 0) {
    //       Toast.fail(response.data.msg);
    //       return false;
    //     } else {
    //       Toast.success("添加成功");
    //       if (this.adviceForm.parent_id > 0) {
    //         var spliceIndex = -1;
    //         for (let index = this.tableDate.length - 1; ; index--) {
    //           if (
    //             this.tableDate[index].parent_id === this.adviceForm.parent_id
    //           ) {
    //             spliceIndex = index;
    //             break;
    //           } else if (
    //             this.tableDate[index].id === this.adviceForm.parent_id
    //           ) {
    //             spliceIndex = index;
    //             break;
    //           }
    //         }
    //         if (spliceIndex > -1) {
    //           spliceIndex += 1;
    //           if (spliceIndex === this.tableDate.length) {
    //             this.tableDate.push(response.data.data.advice);
    //           } else {
    //             var swapData = this.tableDate.splice(spliceIndex);
    //             this.tableDate.push(response.data.data.advice);
    //             for (var index in swapData) {
    //               this.tableDate.push(swapData[index]); // = this.doctor_advices.concat(swapData);
    //             }

    //             // this.tableDate = this.tableDate.concat(swapData);
    //           }
    //         }
    //       } else {
    //         this.tableDate.unshift(response.data.data.advice);
    //       }
    //       this.currentIndex = -1;
    //       this.popupDidHide();
    //       return false;
    //     }
    //   });
    // },
    chooseTime() {
      this.$refs.picker.open();
    },
    chooseStopTime() {
      this.$refs.stoptime.open();
    },

    selectAdviceName(key) {
      if (key in this.adviceTemplateMaps) {
        this.adviceForm.advice_name = this.adviceTemplateMaps[key].advice_name;
        this.adviceForm.advice_desc = this.adviceTemplateMaps[key].advice_desc;
        this.adviceForm.single_dose_unit = this.adviceTemplateMaps[
          key
        ].single_dose_unit;
        this.adviceForm.prescribing_number_unit = this.adviceTemplateMaps[
          key
        ].prescribing_number_unit;
        this.adviceForm.single_dose =
          this.adviceTemplateMaps[key].single_dose + "";
        this.adviceForm.prescribing_number =
          this.adviceTemplateMaps[key].prescribing_number + "";
        this.adviceForm.delivery_way = this.adviceTemplateMaps[
          key
        ].delivery_way;
        this.adviceForm.execution_frequency = this.adviceTemplateMaps[
          key
        ].execution_frequency;
      }
    },
    menuCancle: function() {
      this.visibility = false;
      this.showForm = true;
    },
    menuComfirm: function(val) {
      this.visibility = false;
      this.showForm = true;

      switch (val.type) {
        case 1:
          if (val.selectId in this.adviceTemplateMaps) {
            this.selectAdviceName(val.selectId);
            this.adviceForm.template_id = val.selectId;
          }
          break;
        case 2:
          if (val.selectId in this.deliveryWayOjb) {
            this.adviceForm.jjtj_id = val.selectId;
            this.adviceForm.delivery_way = this.deliveryWayOjb[
              val.selectId
            ].name;
          }
          break;
        case 3:
          if (val.selectId in this.executionFrequencyObj) {
            this.adviceForm.zxpl_id = val.selectId;
            this.adviceForm.execution_frequency = this.executionFrequencyObj[
              val.selectId
            ].name;
          }
          break;
        case 4:
          if (val.selectId in this.unitsObj) {
            this.adviceForm.sdu_id = val.selectId;
            this.adviceForm.single_dose_unit = this.unitsObj[val.selectId].name;
          }
          break;
        case 5:
          if (val.selectId in this.unitsObj) {
            this.adviceForm.pnu_id = val.selectId;
            this.adviceForm.prescribing_number_unit = this.unitsObj[
              val.selectId
            ].name;
          }
          break;
      }
    },
    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;

          var dl = this.deliveryWayOptions.length;
          for (let index = 0; index < dl; index++) {
            this.deliveryWayOjb[
              this.deliveryWayOptions[index].id
            ] = this.deliveryWayOptions[index];
          }
          var el = this.executionFrequencyOptions.length;
          for (let index = 0; index < el; index++) {
            this.executionFrequencyObj[
              this.executionFrequencyOptions[index].id
            ] = this.executionFrequencyOptions[index];
          }

          this.adviceTemplates =
            response.data.data.advice_templates === null
              ? []
              : response.data.data.advice_templates;
          // var templateLen = this.adviceTemplates.length;
          // for (let index = 0; index < templateLen; index++) {
          //   var item = this.adviceTemplates[index];
          //   item["name"] = item.advice_name;
          //   this.$set(
          //     this.adviceTemplateMaps,
          //     this.adviceTemplates[index].id,
          //     item
          //   );
          // }
        }
      });
    },

    handleConfirm(time) {
      this.adviceForm.start_time = this.handleTime(time);
    },
    handleStopConfirm(time) {
      this.stopForm.stop_time = this.handleTime(time);
    },
    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";
    },
    setAdviceNo(index, item) {
      var itemNo = "";
      if (index == 0) {
        adviceno = 1;
        adviceno++;
        return "1";
      } else {
        if (item.parent_id > 0) {
          return "";
        } else {
          itemNo = "" + adviceno;
          adviceno++;
          return itemNo;
        }
      }
    },

    showSubMenu: function(val) {
      switch (val) {
        case "advice_name":
          this.propForm.type = 1;
          this.showForm = false;
          this.propForm.title = "选择";
          this.visibility = true;
          this.propForm.list = [];
          this.propForm.optionList = this.adviceTemplateMaps;
          this.propForm.isMultiple = 1;
          this.propForm.selectId = this.adviceForm.template_id;
          break;
        case "delivery_way":
          this.propForm.type = 2;
          this.showForm = false;
          this.propForm.title = "选择";
          this.visibility = true;
          this.propForm.list = [];
          this.propForm.optionList = this.deliveryWayOptions;
          this.propForm.isMultiple = 1;
          this.propForm.selectId = this.adviceForm.jjtj_id;
          break;
        case "execution_frequency":
          this.propForm.type = 3;
          this.showForm = false;
          this.propForm.title = "选择";
          this.visibility = true;
          this.propForm.list = [];
          this.propForm.optionList = this.executionFrequencyOptions;
          this.propForm.isMultiple = 1;
          this.propForm.selectId = this.adviceForm.zxpl_id;
          break;
        case "single_dose_unit":
          this.propForm.type = 4;
          this.showForm = false;
          this.propForm.title = "选择";
          this.visibility = true;
          this.propForm.list = [];
          this.propForm.optionList = this.unitsOption;
          this.propForm.isMultiple = 1;
          this.propForm.selectId = this.adviceForm.sdu_id;
          break;

        case "prescribing_number_unit":
          this.propForm.type = 5;
          this.showForm = false;
          this.propForm.title = "选择";
          this.visibility = true;
          this.propForm.list = [];
          this.propForm.optionList = this.unitsOption;
          this.propForm.isMultiple = 1;
          this.propForm.selectId = this.adviceForm.pnu_id;
          break;
      }
    },
    handleStartDateConfirm: function(val) {
      this.queryParams.start_time = parseTime(
        this.start_time / 1000,
        "{y}-{m}-{d}"
      );
      this.startSearchTimeShow = this.queryParams.start_time;
      this.onLoad();
    },
    handleEndDateConfirm: function(val) {
      this.queryParams.end_time = parseTime(
        this.end_time / 1000,
        "{y}-{m}-{d}"
      );
      this.endSearchTimeShow = this.queryParams.end_time;
      this.onLoad();
    },
    selectStartSearchTime: function() {
      this.$refs.start_date_picker.open();
    },
    selectEndSearchTime: function() {
      this.$refs.end_date_picker.open();
    },
    tranDoctor(id) {
      if (id in this.adminUserOptions) {
        return this.adminUserOptions[id].name;
      } else {
        return "未知";
      }
    },
    selectType(id, showName) {
      this.queryParams.advice_type = id;
      this.adviceNameShow = showName;
      this.onLoad();
    },
    selectStopType(id, showName) {
      this.queryParams.stop_state = id;
      this.stopNameShow = showName;
      this.onLoad();
    },
    searchKey() {
      this.onLoad();
    },
    fetchAllAdminUsers() {
      fetchAllAdminUsers().then(response => {
        if (response.data.state == 1) {
          var ul = response.data.data.users.length;
          for (let index = 0; index < ul; index++) {
            this.adminUserOptions[response.data.data.users[index].id] =
              response.data.data.users[index];
          }
        }
      });
    },
    onLoad() {
      this.tableDate = [];
      allno = 1;
      // 异步更新数据
      GetDoctorAdvices(this.queryParams).then(response => {
        if (response.data.state == 1) {
          if (this.queryParams.need_doctor == 1) {
            var ul = response.data.data.users.length;
            for (let index = 0; index < ul; index++) {
              this.adminUserOptions[response.data.data.users[index].id] =
                response.data.data.users[index];
            }
            this.queryParams.need_doctor = 0;
          }

          var resp_advices = response.data.data.advices
          if (resp_advices.length > 0) {
            var newGroupObject = function() {
              return Object.assign({}, {
                group_no: 0,
                advices: [],
              })
            }
            var initGroupBlock = function(group, advice) {
              group.group_no = advice.groupno
            }

            var advice_groups = []
            var group = newGroupObject()
            for (let index = 0; index < resp_advices.length; index++) {
              const advice = resp_advices[index];
              if (advice.groupno == 0) { // 老版本的医嘱
                if (advice.parent_id > 0) {
                  if (advice_groups.length > 0) {
                    var parent_group = advice_groups[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) {
                    advice_groups.push(group)
                    group = newGroupObject()
                  }
                    
                  initGroupBlock(group, advice)
                  group.advices.push(advice)
                  advice_groups.push(group)
                  group = newGroupObject()
                  continue
                }

              } else {
                if (group.group_no > 0 && group.group_no != advice.groupno) {
                  advice_groups.push(group)
                  group = newGroupObject()
                }
                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，这里要手动加上
              advice_groups.push(group)
            }
            this.advice_groups = advice_groups
          } else {
            this.advice_groups = []
          }
          // var sl = response.data.data.advices.length;
          // for (let index = 0; index < sl; index++) {
          //   var advice = response.data.data.advices[index];
          //   if (advice.parent_id == 0) {
          //     advice.no = allno;
          //     advice.start_time_show = parseTime(
          //       advice.start_time,
          //       "{y}-{m}-{d} {h}:{i}"
          //     );

          //     allno++;
          //   } else {
          //     advice.start_time_show = "";
          //     advice.no = "";
          //   }
          //   if (advice.stop_state == 1 && advice.parent_id == 0) {
          //     advice.stop_time_show = parseTime(
          //       advice.stop_time,
          //       "{y}-{m}-{d} {h}:{i}"
          //     );
          //   } else {
          //     advice.stop_time_show = "";
          //   }

          //   this.tableDate.push(advice);
          // }
        }
      });
    }
  },

  created() {
    allno = 1;
    adviceno = 1;
    // this.fetchAllAdminUsers();
    this.queryParams.id = this.$route.query.patient_id;
    this.doctor = this.$store.getters.user.user.user_name;
    this.doctor_id = this.$store.getters.user.user.id;
    this.patient_id = this.$route.query.patient_id;

    var date = new Date();
    date.setMonth(date.getMonth() - 1);

    // var year = date.getFullYear();
    // var month = date.getMonth();
    // var day = date.getDate();
    // if (month < 10) {
    //   month = "0" + month;
    // }
    // if (day < 10) {
    //   day = "0" + day;
    // }
    // var nowDate = year + "-" + month + "-" + day;
    this.start_time = date;

    this.startSearchTimeShow = parseTime(
      this.start_time.getTime(),
      "{y}-{m}-{d}"
    );
    this.endSearchTimeShow = parseTime(new Date().getTime(), "{y}-{m}-{d}");

    this.queryParams.start_time = this.startSearchTimeShow;
    this.onLoad();

    this.getAdviceConfig();

    this.unitsOption = getDataConfig("hemodialysis", "units");
    for (var index in this.unitsOption) {
      this.unitsObj[this.unitsOption[index].id] = this.unitsOption[index];
    }
  },
};
</script>

<style style="stylesheet/scss" lang="scss"  scoped>
.fixedTop{
  padding-top:52px; 
  background: #fff;
  min-height: calc(100vh - 200px);
.choice {
  border-bottom: 1px #e5e5e5 solid;
  
  ul {
    @include display-flex;
    @include align-items-center;
    @include text-align;
    @include justify-content-between;
    width: 70%;
    margin: 0 auto;
    font-size: 0.32rem;
    color: $pgh-color;
    li {
      @include display-flex;
      @include align-items-center;
      @include text-align;
      @include justify-content-between;
      padding: 0.3rem 0;
    
      .iconfont {
        margin: 0 0.1rem;
      }
      .line {
        background: #a8b3ba;
        width: 0.2rem;
        height: 1px;
        margin: 0 0.2rem;
        display: inline-block;
      }
    }
  }
}
.tableSearch {
  width: 100%;
  margin: 0 auto;
  padding: 0.24rem 0;
  background: #f6f8f9;
  ul {
    width: 50%;
    background: #fff;
    margin: 0 auto;
    border-radius: 30px;
    li {
      @include display-flex;
      @include align-items-center;
      @include text-align;
      padding-left: 15px;
      .iconfont{
        font-size: 0.42rem;
      }
      input {
        border: none;
        border-radius: 30px;
        padding: 0.15rem;
        width: 100%;
        color: $pgh-color;
      }
    }
  }
}

.content {
  .cell {
    float: left;
    width: 3.42rem;
    // width: 100%;
    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;
  }
  .row-class-active > td {
    background: #badcff;
  }
}
.table {
  tr {
    td {
      padding-left: 5px;
      padding-right: 5px;
    }
    .advice_name {
      text-align: left;
    }
    .subdrug_name {
      text-align: left;
      padding-left: 25px;
    }
  }
}
.AdviceTable{
  padding-top:0; 
  background: #fff;
  min-height: calc(100vh - 230px);
}
}

</style>

