<template>
    <div class="popup-content" style="min-height:320px;">
        <h2 class="title">
            <span class="line"></span>
            <p>{{title}}</p> 
            <span class="line"></span>
        </h2>
        <div class="content" v-show="index==0" >
            <div class="yzNav" style="width:80%">
                <span @click="openNewAdvice">新增医嘱</span>
                <span @click="deleteAdvice">删除医嘱</span>
                <span @click="execAdvice">执行医嘱</span>
                <span @click="openNewChild">添加子药</span>
            </div>
            <table  class="table"  >
                <tr @click="selectRow(-1, null)" >
                    <th width="10.5%">开嘱医生</th>
                    <th width="15.6%">开始时间</th>
                    <th width="26.6%">医嘱内容</th>
                    <th width="16%">执行时间</th>
                    <th width="10%">执行护士</th>
                    <th width="10%">核对人员</th>
                </tr>
                <tr v-for="(advice,index) in adviceList" :key="index" :value="advice.advice_name" @click="selectRow(index, advice)" :class="index==currentIndex?rowClass:''">
                    <td>
                      <span v-if="advice.parent_id==0">{{getXuserName(advice.advice_doctor)}}</span>
                      <span v-else></span>
                    </td>
                    <td>
                      <span v-if="advice.parent_id==0">{{ uParseTime(advice.start_time, "{y}-{m}-{d} {h}:{i}")}}</span>
                      <span v-else></span>
                    </td>
                    <td>
                      <span >{{advice.advice_name }}</span>
                      <span >{{advice.advice_desc}}</span>
                      <span v-if="advice.single_dose">{{advice.single_dose}}{{advice.single_dose_unit}}</span>
                      <span v-if="advice.prescribing_number">{{advice.prescribing_number}}{{advice.prescribing_number_unit}}</span>
                      <span >{{advice.delivery_way}}</span>
                      <span >{{advice.execution_frequency}}</span>
                      
                    </td>
                    <td><span v-if="advice.execution_time!=0" >{{ uParseTime(advice.execution_time, "{y}-{m}-{d} {h}:{i}")}}</span>
                    </td>
                    <td><span v-if="advice.parent_id==0" >{{getXuserName(advice.execution_staff)}}</span>
                    </td>
                    <td></td>
                </tr>
            </table>
       </div>

        <div class="content" v-show="index==1">
            <div >


                <div class="cell">
                            <label>医嘱类型</label>
                            <input type="text" class="inputBox" disabled value="临时">
                </div>
                <div class="cell">
                            <label>开嘱时间</label>
                            <input type="text" class="inputBox"  v-model="adviceForm.created_time" readonly>
                </div>
                <div class="cell">
                            <label>开始时间</label>
                            <input type="text" class="inputBox"  v-model="adviceForm.start_time" readonly @click="chooseTime">
                </div>

              <div class="cell">
                <label>开嘱医生</label>
                <span>{{ doctor }}</span>

              </div>

              <!--<div class="cell width">-->
                <!--<label>开嘱医生：</label>-->
                <!--<span>{{doctor}}</span>-->
              <!--</div>-->
              <!---->

                <div class="cell">
                            <label>医嘱内容</label>
                            <el-select v-model="adviceForm.advice_name" @change="changeAdviceName" filterable placeholder="请选择(输入可搜索)"  >
                              <el-option
                              v-for="item in drugOptions"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id"
                              >
                              <span >{{ item.name }}</span>
                              <span >{{ item.spec }}</span>
                              </el-option>
                          </el-select>
                </div>
                
                <div class="cell">
                            <label>给药途径</label>
                            <el-select v-model="adviceForm.delivery_way" :disabled="adviceForm.parent_id==0?false:true" filterable placeholder="请选择(输入可搜索)" >
                                <el-option
                                v-for="item in deliveryWayOptions"
                                :key="item.id"
                                :label="item.name "
                                :value="item.name">
                                </el-option>
                            </el-select>
                </div>
                <div class="cell">
                            <label>执行频率</label>
                            <el-select v-model="adviceForm.execution_frequency" :disabled="adviceForm.parent_id==0?false:true" filterable placeholder="请选择(输入可搜索)" >
                                <el-option
                                v-for="item in executionFrequencyOptions"
                                :key="item.id"
                                :label="item.name "
                                :value="item.name">
                                </el-option>
                            </el-select>
                </div>
                
                <div class="cell">
                            <label>医嘱描述</label>
                            <input type="text" class="inputBox" v-model="adviceForm.advice_desc">
                </div>
                  <div class="cell">
                            <label>单次用量</label>
                            <input type="text" class="inputBox" style="width:62.5%" v-model="adviceForm.single_dose" >
                            <input type="text" class="inputBox" style="width:35%" v-model="adviceForm.single_dose_unit" >
                </div>
                <div class="cell">
                            <label>开药数量</label>
                            <input type="text" class="inputBox" style="width:62.5%" v-model="adviceForm.prescribing_number" >
                            <input type="text" class="inputBox" style="width:35%" v-model="adviceForm.prescribing_number_unit" >
                </div>


                <div class="cell width center">
                  <button class="smt-danger" @click="index=0">返回</button>                      
                  <button @click="submitNewAdvice">提交</button>                      
                </div>
            </div>
       </div>
       <mt-datetime-picker
        ref="picker"
        type="datetime"
        @confirm="handleConfirm">
      </mt-datetime-picker>
      
       <mt-datetime-picker
        ref="exec_time"
        type="datetime"
        @confirm="handleExecTime">
      </mt-datetime-picker>

    </div>
</template>


<script>
import { Dialog,DatetimePicker,Toast  } from 'vant';
import { getAdviceConfig,CreateDoctorAdvice,DeleteDoctorAdvice,ExecDoctorAdvice } from "@/api/advice";
import {uParseTime} from "@/utils/tools";

export default {
  name: "MedicalOrder",
 
  data() {
    return {
      rowClass:'row-class-active',
      currentIndex:-1,
      currentRow:null,
      title: "临时医嘱",
      index:0,
      doctor:'',
      drugOptions:{},
      deliveryWayOptions:[],
      executionFrequencyOptions:[],
      record_date:'',
      patient:{
        id:0
      },
      admin_users:[],
      adviceForm:{
        id:0,
        advice_type:2,
        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,
      },
      adviceList: [],
      parent_id : 0,
    };
  },
  methods:{
    selectRow(index, row) {
      this.currentIndex = index;
      this.currentRow = row;
    }, 
    uParseTime(time, format){
      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;
    },
    submitNewAdvice(){
      CreateDoctorAdvice(this.patient.id, this.adviceForm).then(response=>{
          if (response.data.state==0) {
              Toast(response.data.msg);
              return false;
          }else {
              Toast('添加成功');
              if (this.adviceForm.parent_id > 0) {
                  var spliceIndex = -1;
                  for (let index = this.adviceList.length-1; ; index--) {
                      if(this.adviceList[index].parent_id ===  this.adviceForm.parent_id) {
                          spliceIndex = index;
                          break;
                      }else if (this.adviceList[index].id === this.adviceForm.parent_id) {
                          spliceIndex = index;
                          break; 
                      }
                  }
                  if (spliceIndex > -1) {
                      spliceIndex += 1;
                      if (spliceIndex === this.adviceList.length) {
                          this.adviceList.push(response.data.data.advice);
                      }else {
                          var swapData = this.adviceList.splice(spliceIndex);
                          this.adviceList.push(response.data.data.advice);
                          this.adviceList = this.adviceList.concat(swapData);
                      }
                  } 
              }else {
                  this.adviceList.unshift(response.data.data.advice);
              }
              this.currentIndex = -1;
              this.currentRow = null;
              this.index = 0;
              this.$emit("new_create", response.data.data.advice);
              return false;
          }
      });
    },
    chooseTime(){
      this.$refs.picker.open();
    },
    changeAdviceName(change){
        this.adviceForm.advice_name = this.drugOptions[change].name;
        this.adviceForm.advice_desc = this.drugOptions[change].spec;
        this.adviceForm.single_dose_unit = this.drugOptions[change].spec_unit;
        this.adviceForm.prescribing_number_unit = this.drugOptions[change].form_unit;
    },
    getAdviceConfig() {
        getAdviceConfig().then(response => {
            if (response.data.state == 1) {
                this.deliveryWayOptions = response.data.data.drugways;
                this.executionFrequencyOptions = response.data.data.efs;

                var druglist = {};
                var durglength = response.data.data.drugs.length;
                for (let index = 0; index < durglength; index++) {
                    druglist[response.data.data.drugs[index].id] = response.data.data.drugs[index];
                }
                this.drugOptions = druglist;
            }
        });
    },
    handleConfirm(time){
      this.adviceForm.start_time =this.handleTime(time);
    },

    handleExecTime(time) {
      var exceTime = this.handleTime(time);
      var exceParams = {
        id: this.currentRow.id,
        patient: this.patient.id,
        parent_id: this.currentRow.parent_id,
        execution_time: exceTime,
      };

      ExecDoctorAdvice(exceParams).then(response=>{
        if (response.data.state == 0) {
          Toast('执行失败！');
          return false
        }else {
          Toast('执行成功！');
          var exid = exceParams.id
          if (exceParams.parent_id>0) {
            exid = exceParams.parent_id;
          }
          var alen = this.adviceList.length;
          for (let index = 0; index < alen; index++) {
            if (this.adviceList[index].id== exid) {
              console.log(exid,this.adviceList[index].id,response.data.data.advice);
              this.adviceList[index].execution_state = 1;
              this.adviceList[index].execution_staff = response.data.data.advice.execution_staff;
              this.adviceList[index].execution_time = 	Math.round(time.getTime()/1000);
              this.adviceList[index].checker = response.data.data.advice.checker;
              this.$emit('execution', this.adviceList[index]);
              break;
            }
          }
          
          
          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";
    },
    deleteAdvice(){
      if (this.currentIndex < 0 || this.currentRow == null) {
        Toast('请先选择要删除的医嘱！');
        return false;
      }
      Dialog.confirm({
        title: '医嘱删除',
        message: '确认删除些条医嘱?'
      }).then(() => {
        DeleteDoctorAdvice(this.currentRow.id).then(response=>{
            if(response.data.state==0) {
                Toast(response.data.msg);
                return false;
            }else {
                Toast("医嘱已经删除");
                this.deleteResetData(this.currentIndex, this.currentRow);
                this.$emit('delete', this.adviceList[this.currentIndex]);
                this.currentIndex = -1;
                this.currentRow = null;
                
            }
        });
      }).catch(() => {
        // on cancel
      });
    },
    deleteResetData(index, row) {
        if (row.parent_id>0) {
            this.adviceList.splice(index,1);
        }else {
            var resetTableData = this.adviceList;
            this.adviceList = [];
            var that = this;
            var rslen = resetTableData.length;
            for (let i = 0; i < rslen; i++) {
              if (resetTableData[i].id != row.id && resetTableData[i].parent_id != row.id) {
                    that.adviceList.push(resetTableData[i]);
              }
            }
        }
    },
    execAdvice(){
      if (this.currentIndex < 0 || this.currentRow == null) {
        Toast('请先选择要执行的医嘱！');
        return false;
      }
      this.$refs.exec_time.open();
    },
    openNewChild(){
      if (this.currentIndex < 0 || this.currentRow == null) {
        Toast('请先选择要添加子药的医嘱！');
        return false;
      }

      this.index = 1;
      
      this.adviceForm={
        id:0,
        advice_type:2,
        advice_date:this.record_date,
        start_time:uParseTime(this.currentRow.start_time, "{y}-{m}-{d} {h}:{i}"),
        advice_name:"",
        advice_desc:"",
        single_dose:"",
        single_dose_unit:"",
        prescribing_number:"",
        prescribing_number_unit:"",
        delivery_way:this.currentRow.delivery_way,
        execution_frequency:this.currentRow.execution_frequency,
        advice_doctor:"",
        remark:"",
        parent_id:this.currentRow.id,
      }
    },
    openNewAdvice(){
      this.index=1;
      this.currentIndex = -1;
      this.currentRow = null;
      this.adviceForm={
        id:0,
        advice_type:2,
        advice_date:this.record_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,
      }
     
    }
  }, 
  props: {
    patient_prop: {
      type: Object,
    },
    advice_list_prop: {
      type: Array,
    },
    admin_users_prop:{
      type:Array,
    }
   
  },
  created(){
    var date = this.$route.query && this.$route.query.date;
    date *= 1000;
    var newDate = new Date(date);

    var y = newDate.getFullYear();
    var m = newDate.getMonth() + 1;
    var d = newDate.getDate();
    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.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.adviceForm.advice_date = this.record_date;
    this.getAdviceConfig();

    
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.smt-danger {
  color: #000 !important;
    background-color: #fff !important;
    border: 1px solid #000;
}

.table {
  width: 100%;
  overflow: hidden;
  font-size: 0.3rem;
  text-align: center;
  border: $border-color;
  background: $text-color;
  padding: 0 0 0.28rem 0;
  
  tr {
    padding: 0;
    margin: 0;
    padding: 0.1rem 0;
    th {
      background: $main-color;
      border: none;
      color: #fff;
      padding: 0;
      margin: 0;
      height: 0.88rem;
      line-height: 0.88rem;
      font-weight: normal;
    }
   
  }
  .row-class-active>td{
    background: #badcff;
  }
}
</style>
