<template>
  <div v-loading="loading">
    <div class="Dialog" style="width: 11.8rem;" v-show="show_dialog_key == 0">
      <div class="DialogTit">
        <div class="back" @click="backAction">
          <span class="iconfont">&#xe720;</span>返回
        </div>
        <h1 class="name">新增医嘱</h1>
        <span class="success" @click="comfirmAction">保存</span>
      </div>
      <div class="yzNav" style="width:100%;">
        <span class="newSpan" @click="addOrderByTemplateAction">选择模板</span>
        <span class="newSpan" @click="addNewOrderAction">新增内容</span>
        <span class="newSpan" @click="modifyOrderAction">修改内容</span>
        <span class="newSpan" @click="deleteOrderAction">删除内容</span>
      </div>
      <div class="content clearfix backgroundColor">
        <div style="overflow: hidden;">
          <div class="cell" style="margin-top: 0;">
            <label>医嘱类型</label>
            <el-input
              class="typeInput"
              ref="advice_type"
              value="临时"
              disabled
            ></el-input>
          </div>
          <div class="cell" style="margin-top: 0;">
            <label>开始时间</label>
            <el-input
              class="typeInput"
              :value="start_time_str"
              readonly
              @focus="selectStartTimeAction"
            ></el-input>
          </div>
        </div>
        <div style="overflow: hidden;margin-top: 15px">
          <div class="cell" style="margin-top: 0;">
            <label>开嘱医生: {{ $store.getters.user.user.user_name }}</label>
          </div>
          <div class="cell" style="margin-top: 0;">
            <label>开嘱时间 {{ record_date_str }}</label>
          </div>
        </div>
        <div
          id="newDialogContent"
          class="DialogContent choose"
          style="height: 6.2rem;"
        >
          <div class="newAddTable">
            <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 advices">
                <tr
                  :key="advice_index"
                  @click="clickAdviceAction(advice_index)"
                  :class="{
                    'row-class-active':
                      advice_index == selecting_advice_index &&
                      selecting_subdrug_index < 0
                  }"
                >
                  <td
                    style="text-align: left; padding-left: 5px; padding-right: 5px;"
                  >
                    {{ advice.title }}
                  </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.subdrugs"
                  :key="advice_index + '_' + subdrug_index"
                  @click="clickSubdrugAction(advice_index, subdrug_index)"
                  :class="{
                    'row-class-active':
                      advice_index == selecting_advice_index &&
                      subdrug_index == selecting_subdrug_index
                  }"
                >
                  <td
                    style="text-align: left; padding-right: 5px; padding-left: 25px;"
                  >
                    {{ subdrug.title }}
                  </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>

    <!-- <single-option-dialog
      :visibility="show_dialog_key == 1"
      title="医嘱模板"
      @did-selected="didSelectOrderTemplate"
      @back="show_dialog_key = 0"
      :options="advice_templates"
      option_key="id"
      option_label_key="name"
    ></single-option-dialog>-->

    <advice-template
      :visibility="show_dialog_key == 1"
      @back="show_dialog_key = 0"
      @finish="didSelectTemplateAdvice"
      :templates="advice_templates"
    ></advice-template>

    <order-form-dialog
      ref="order_form"
      @back="show_dialog_key = 0"
      @did-create-new="didAddNewOrder"
      @did-modify="didModifyOrder"
      :drug_spec_unit_options="drug_spec_unit_options"
      :delivery_way_options="delivery_way_options"
      :execution_frequency_options="execution_frequency_options"
      :single_dose_unit_options="single_dose_unit_options"
      :prescribing_number_unit_options="prescribing_number_unit_options"
    ></order-form-dialog>

    <mt-datetime-picker
      ref="start_time_picker"
      type="datetime"
      @confirm="didSelectStartTime"
      v-model="start_time"
    ></mt-datetime-picker>
  </div>
</template>

<script>
import SingleOptionDialog from "./single_option_dialog";
import OrderFormDialog from "./order_form";
import AdviceTemplate from "./select_advice_template_dialog";
import { Toast, Dialog } from "vant";
import { parseTime } from "@/utils";
import { batchCreateAdvices } from "@/api/advice";
import { setTimeout } from "timers";

export default {
  name: "AddNewOrdersDialogContent",
  components: {
    SingleOptionDialog,
    OrderFormDialog,
    AdviceTemplate
  },
  props: {
    group_no: {
      // 新增的医嘱所属分组，不传则默认创建新分组
      type: Number,
      default: 0
    },
    patient_id: {
      type: Number,
      default: 0
    },
    advice_templates: {
      type: Array,
      default: function() {
        return [];
      }
    },
    drug_spec_unit_options: {
      type: Array,
      default: function() {
        return [];
      }
    },
    delivery_way_options: {
      type: Array,
      default: function() {
        return [];
      }
    },
    execution_frequency_options: {
      type: Array,
      default: function() {
        return [];
      }
    },
    single_dose_unit_options: {
      type: Array,
      default: function() {
        return [];
      }
    },
    prescribing_number_unit_options: {
      type: Array,
      default: function() {
        return [];
      }
    }
  },
  data() {
    return {
      show_dialog_key: 0,
      loading: false,

      record_date_str: "",
      start_time: new Date(),
      start_time_str: "",

      selecting_advice_index: -1,
      selecting_subdrug_index: -1,
      advices: []
    };
  },
  mounted() {
    this.record_date_str = parseTime(new Date(), "{y}-{m}-{d}");
    this.start_time_str =
      parseTime(this.start_time, "{y}-{m}-{d} {h}:{i}") + ":00";
  },
  methods: {
    backAction: function() {
      this.$emit("back-action");
    },
    addOrderByTemplateAction: function() {
      this.show_dialog_key = 1;
      this.selecting_advice_index = -1;
    },
    addNewOrderAction: function() {
      this.show_dialog_key = 2;
      this.$refs.order_form.showWithNew();
      this.selecting_advice_index = -1;
    },
    clickAdviceAction: function(advice_index) {
      this.selecting_advice_index = advice_index;
      this.selecting_subdrug_index = -1;
    },
    clickSubdrugAction: function(advice_index, subdrug_index) {
      this.selecting_advice_index = advice_index;
      this.selecting_subdrug_index = subdrug_index;
    },
    modifyOrderAction: function() {
      if (this.selecting_advice_index >= 0) {
        if (this.selecting_subdrug_index < 0) {
          this.show_dialog_key = 2;
          this.$refs.order_form.showWithEdit(
            this.advices[this.selecting_advice_index]
          );
        } else {
          this.show_dialog_key = 2;
          this.$refs.order_form.showWithEdit(
            this.advices[this.selecting_advice_index].subdrugs[
              this.selecting_subdrug_index
            ]
          );
        }
      } else {
        Toast.fail("请先选择医嘱内容");
      }
    },
    deleteOrderAction: function() {
      Dialog.confirm({
        title: "删除医嘱",
        message: "确认删除医嘱吗?"
      }).then(() => {
        if (this.selecting_advice_index >= 0) {
          if (this.selecting_subdrug_index < 0) {
            this.advices.splice(this.selecting_advice_index, 1);
            this.selecting_advice_index = -1;
          } else {
            var advice = this.advices[this.selecting_advice_index];
            advice.subdrugs.splice(this.selecting_subdrug_index, 1);
            this.selecting_advice_index = -1;
            this.selecting_subdrug_index = -1;
          }
        } else {
          Toast.fail("请先选择医嘱内容");
        }
      });
    },
    selectStartTimeAction: function() {
      this.$refs.start_time_picker.open();
    },
    comfirmAction: function() {
      if (this.advices.length == 0) {
        Toast.fail("请创建医嘱");
        return;
      }

      var data = {};
      data.advice_type = 2;
      data.advice_date = this.record_date_str;
      data.start_time = this.start_time_str;
      var adviceJSONs = [];
      for (let index = 0; index < this.advices.length; index++) {
        const advice = this.advices[index];
        var json = {
          advice_name: advice.title,
          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: []
        };
        for (let s_i = 0; s_i < advice.subdrugs.length; s_i++) {
          const subdrug = advice.subdrugs[s_i];
          json.subdrugs.push({
            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
          });
        }
        adviceJSONs.push(json);
      }

      data.adviceNames = adviceJSONs;
      // console.log(adviceJSONs)

      this.loading = true;
      batchCreateAdvices(this.patient_id, this.group_no, data)
        .then(rs => {
          this.loading = false;
          var resp = rs.data;
          if (resp.state == 1) {
            // 返回数组，清空数据，隐藏弹框
            this.$emit("did-create-advices", 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);
          }
        })
        .catch(err => {
          this.loading = false;
          Toast.fail(err);
        });
      // batchCreateAdvices()
    },

    didSelectStartTime: function(time) {
      this.start_time_str = parseTime(time, "{y}-{m}-{d} {h}:{i}") + ":00";
      console.log(".");
    },
    didSelectTemplateAdvice: function(resp_advices) {
      this.show_dialog_key = 0;
      var advices = [];
      for (let index = 0; index < resp_advices.length; index++) {
        const adv = resp_advices[index];
        if (adv.parent_id == 0) {
          advices.push({
            id: adv.id,
            title: adv.advice_name,
            advice_desc: adv.advice_desc,
            drug_spec: adv.drug_spec,
            drug_spec_unit: adv.drug_spec_unit,
            delivery_way: adv.delivery_way,
            execution_frequency: adv.execution_frequency,
            single_dose: adv.single_dose,
            single_dose_unit: adv.single_dose_unit,
            prescribing_number: adv.prescribing_number,
            prescribing_number_unit: adv.prescribing_number_unit,
            subdrugs: []
          });
        }
      }
      for (let r_a_i = 0; r_a_i < resp_advices.length; r_a_i++) {
        const resp_adv = resp_advices[r_a_i];
        if (resp_adv.parent_id > 0) {
          for (let p_i = 0; p_i < advices.length; p_i++) {
            const p_adv = advices[p_i];
            if (p_adv.id == resp_adv.parent_id) {
              var subdrug = {
                id: resp_adv.id,
                title: resp_adv.advice_name,
                advice_desc: resp_adv.advice_desc,
                drug_spec: resp_adv.drug_spec,
                drug_spec_unit: resp_adv.drug_spec_unit,
                delivery_way: resp_adv.delivery_way,
                execution_frequency: resp_adv.execution_frequency,
                single_dose: resp_adv.single_dose,
                single_dose_unit: resp_adv.single_dose_unit,
                prescribing_number: resp_adv.prescribing_number,
                prescribing_number_unit: resp_adv.prescribing_number_unit
              };
              p_adv.subdrugs.push(subdrug);
              break;
            }
          }
        }
      }
      this.advices.push(...advices);
    },
    // didSelectOrderTemplate: function(index) {
    //   this.show_dialog_key = 0;
    //   var template = this.advice_templates[index];
    //   var advices = [];
    //   for (
    //     let index = 0;
    //     index < template.DoctorAdviceTemplate.length;
    //     index++
    //   ) {
    //     const temp = template.DoctorAdviceTemplate[index];
    //     if (temp.parent_id == 0) {
    //       var advice = {
    //         id: temp.id,
    //         title: temp.advice_name,
    //         advice_desc: temp.advice_desc,
    //         // drug_spec: temp.drug_spec,
    //         // drug_spec_unit: temp.drug_spec_unit,
    //         delivery_way: temp.delivery_way,
    //         execution_frequency: temp.execution_frequency,
    //         single_dose: temp.single_dose,
    //         single_dose_unit: temp.single_dose_unit,
    //         prescribing_number: temp.prescribing_number,
    //         prescribing_number_unit: temp.prescribing_number_unit,
    //         subdrugs: []
    //       };
    //       advices.push(advice);
    //     }
    //   }
    //   for (
    //     let temp_i = 0;
    //     temp_i < template.DoctorAdviceTemplate.length;
    //     temp_i++
    //   ) {
    //     const temp = template.DoctorAdviceTemplate[temp_i];
    //     if (temp.parent_id > 0) {
    //       for (let p_i = 0; p_i < advices.length; p_i++) {
    //         const advice = advices[p_i];
    //         if (advice.id == temp.parent_id) {
    //           var subdrug = {
    //             id: temp.id,
    //             title: temp.advice_name,
    //             advice_desc: temp.advice_desc,
    //             // drug_spec: temp.drug_spec,
    //             // drug_spec_unit: temp.drug_spec_unit,
    //             delivery_way: temp.delivery_way,
    //             execution_frequency: temp.execution_frequency,
    //             single_dose: temp.single_dose,
    //             single_dose_unit: temp.single_dose_unit,
    //             prescribing_number: temp.prescribing_number,
    //             prescribing_number_unit: temp.prescribing_number_unit
    //           };
    //           advice.subdrugs.push(subdrug);
    //           break;
    //         }
    //       }
    //     }
    //   }
    //   this.advices.push(...advices);
    // },
    didAddNewOrder: function(order) {
      this.$refs.order_form.dismiss();
      this.show_dialog_key = 0;
      order.id = 0;
      order.subdrugs = [];
      this.advices.push(order);
    },
    didModifyOrder: function(order) {
      this.$refs.order_form.dismiss();
      this.show_dialog_key = 0;
      if (this.selecting_advice_index >= 0) {
        var advice = this.advices[this.selecting_advice_index];
        if (this.selecting_subdrug_index < 0) {
          advice.title = order.title;
          advice.advice_desc = order.advice_desc;
          // advice.drug_spec = order.drug_spec;
          advice.drug_spec_unit = order.drug_spec_unit;
          advice.delivery_way = order.delivery_way;
          advice.execution_frequency = order.execution_frequency;
          advice.single_dose = order.single_dose;
          advice.single_dose_unit = order.single_dose_unit;
          advice.prescribing_number = order.prescribing_number;
          advice.prescribing_number_unit = order.prescribing_number_unit;
          advice.remark = order.remark;
        } else {
          var subdrug = advice.subdrugs[this.selecting_subdrug_index];
          subdrug.title = order.title;
          subdrug.advice_desc = order.advice_desc;
          // subdrug.drug_spec = order.drug_spec;
          subdrug.drug_spec_unit = order.drug_spec_unit;
          subdrug.single_dose = order.single_dose;
          subdrug.single_dose_unit = order.single_dose_unit;
          subdrug.prescribing_number = order.prescribing_number;
          subdrug.prescribing_number_unit = order.prescribing_number_unit;
        }
      }
    }
  }
};
</script>

<style style="stylesheet/scss" lang="scss" scoped>
#newDialogContent {
  @media only screen and (max-width: 415px) {
    height: 8.8rem !important;
  }
  @media only screen and (min-width: 768px) {
    height: 7.8rem !important;
  }
}
.backgroundColor {
  background: #fff;
}
.newAddTable {
  width: 100%;
  // overflow: auto;
}
.table {
  width: 1200px;
  overflow-x: scroll;
  // margin-top: 0rem;
  @media only screen and (max-width: 767px) {
    width: 1000px;
  }
  tr {
    th {
      background: $main-color;
      color: #fff;
      height: 1.2rem;
      line-height: 1.2rem;
    }
    td {
      line-height: 1.2rem;
    }
  }
}
.content {
  .cell {
    float: left;
    width: 4.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;
  }
}
.newSpan {
  padding: 0 0.3rem;
}
</style>
<style lang="scss">
.newAddTable {
  .table tr td {
    padding: 0;
  }
}
.typeInput {
  .el-input__inner {
    @media only screen and (min-width: 768px) {
      height: 60px;
      line-height: 60px;
    }
  }
}
</style>
