<template>
  <div>
    <div class="Dialog" v-show="index==0" style="width: 18rem;">
      <div class="DialogTit" @click="$emit('orderDialog')">
        <span class="iconfont">&#xe6e9;</span>
        <h1 class="name">临时医嘱</h1>
        <span class="success">&nbsp;</span>
      </div>
      <div class="yzNav" style="width:100%;">
        <span @click="openNewAdvice">新增医嘱</span>
        <span
          @click="execAdvice"
          :class="{ forbid: (current_advice&& current_advice.parent_id > 0) }"
        >执行医嘱</span>
        <span
          @click="checkAdvice"
          :class="{ forbid: (current_advice&& current_advice.parent_id > 0) }"
        >医嘱核对</span>
        <span
          @click="openNewChild"
          :class="{ forbid: current_advice == null || current_advice.parent_id > 0 ||  currentAdvices.length != 1}"
        >添加子药</span>
        <span v-if="currentSubAdvices.length <= 0" @click="modifyAdviceAction"
              :class="{ forbid: current_group_index < 0 ||  currentAdvices.length != 1 }">修改医嘱</span>
        <span v-if="currentSubAdvices.length <= 0" @click="deleteAdviceAction"
              :class="{ forbid: current_group_index < 0 || currentAdvices.length <= 0  }">删除医嘱</span>

        <span v-if="currentSubAdvices.length > 0" @click="modifySubdviceAction">修改子医嘱</span>
        <span v-if="currentSubAdvices.length > 0" @click="deleteSubAdviceAction">删除子医嘱</span>

      </div>
      <div class="DialogContent choose" id="dialogTop" style="height:6.5rem;">
        <div class="content clearfix">

          <table class="table">
            <tr @click="cancelAdviceSelect">
              <th width="8%">开嘱医生</th>
              <th width="10%">开始时间</th>
              <th width="40%">医嘱内容</th>
              <th width="10%">执行时间</th>
              <th width="10%">执行护士</th>
              <th width="10%">核对人员</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.drug_spec > 0"
                    >{{ advice.drug_spec }}{{ advice.drug_spec_unit }}</span> -->
                    <span>{{ advice.advice_desc }}</span>
                    <span v-if="advice.prescribing_number">{{advice.prescribing_number}}{{advice.prescribing_number_unit}}</span>
                    <span v-if="advice.single_dose"
                    >单次用量{{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
                  :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>

    <add-new-order-dialog
      v-show="index==1&&isShowDialog"
      @back-action="index = 0"
      :patient_id="patient.id"
      :delivery_way_options="deliveryWayOptions"
      :execution_frequency_options="executionFrequencyOptions"
      :single_dose_unit_options="unitsOption"
      :prescribing_number_unit_options="unitsOption"
      :advice_templates="adviceTemplates"
      @did-create-advices="didCreateAdvices"
    ></add-new-order-dialog>

    <advice-form
      ref="subdrug_form"
      @back="index = 0"
      @did-create-subdrug="didAddSubdrug"
      :single_dose_unit_options="unitsOption"
      :prescribing_number_unit_options="unitsOption"
    ></advice-form>

    <modify-advice-form
      ref="modify_advice_form"
      @back="index = 0"
      @did-modify="didModifyAdvice"
      :delivery_way_options="deliveryWayOptions"
      :execution_frequency_options="executionFrequencyOptions"
      :single_dose_unit_options="unitsOption"
      :prescribing_number_unit_options="unitsOption"
    ></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"
      :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>
  </div>
</template>

<script>
  import {Dialog, Toast} from 'vant'
  import {
    CheckDoctorAdvice,
    CreateDoctorAdvice,
    DeleteDoctorAdviceNew,
    DeleteSubDoctorAdvice,
    EditDoctorAdvice,
    ExecDoctorAdvice,
    getAdviceConfig
  } from '@/api/advice'
  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'

  export default {
    name: 'OrdersDialog',
    components: {
      CheckBoxSubMenu,
      AddNewOrderDialog,
      AdviceForm,
      ModifyAdviceForm,
      ModifyAdviceGroupDialog,

    },
    props: {
      advice_groups: {
        type: Array,
        default: () => {
          return []
        }
      },
      patient_prop: {
        type: Object
      },
      advice_list_prop: {
        type: Array
      },
      admin_users_prop: {
        type: Array
      }
    },
    data () {
      return {
        isShowDialog: true,

        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: [],

      }
    },
    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.getAdviceConfig()

      this.unitsOption = getDataConfig('hemodialysis', 'units')
      for (var index in this.unitsOption) {
        this.unitsObj[this.unitsOption[index].id] = this.unitsOption[index]
      }
    },
    watch: {
      'advice_groups': function () {
        console.log(this.advice_groups)

      }

    },

    methods: {
      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]
          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
      },
      didModifyAdvice: function (advice) {
        Toast.loading({forbidClick: true, duration: 0})
        EditDoctorAdvice(advice.id, {
          advice_name: advice.title,
          advice_desc: advice.advice_desc,
          remark: advice.remark,
          // 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(rs => {
            if (rs.data.state == 1) {
              var resp_advice = rs.data.data.advice

              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.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.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()
              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})
        CreateDoctorAdvice(this.patient.id, {
          parent_id: subdrug.parent_id,
          advice_type: 2,
          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
          // delivery_way: subdrug.delivery_way,
          // execution_frequency: subdrug.execution_frequency
        })
          .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
          }
        })
      },
      handleExecTime (time) {
        var exceTime = this.handleTime(time)
        var exceParams = null
        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
          }
        }
        Toast.loading({forbidClick: true, duration: 0})
        ExecDoctorAdvice(exceParams)
          .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].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})
          DeleteSubDoctorAdvice(this.currentSubAdvices[0].id)
            .then(rs => {
              if (rs.data.state == 1) {
                Toast.success('删除成功')
                var adviceArr = this.advice_groups[this.current_group_index].advices
                console.log(adviceArr)
                console.log(this.currentSubAdvices[0].id)
                for (let i = adviceArr.length - 1; i >= 0; i--) {
                  console.log(adviceArr[i].id)
                  if (adviceArr[i].id == this.currentSubAdvices[0].id) {
                    console.log('delete')
                    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.current_select_object == 1) {
          if (this.currentAdvices.length <= 0) {
            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(',')

            DeleteDoctorAdviceNew(group_no, advice_id)
              .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
            }

            DeleteDoctorAdviceNew(group_no, advice_id)
              .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.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.user.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(',')

        } 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.user.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.current_select_object == 1) {
            params = {
              groupno: 0,
              advice_id: this.currentAdviceIdsStr
            }
          } else {
            var group = this.advice_groups[this.current_group_index]
            params = {
              groupno: group.group_no <= 0 ? 0 : group.group_no,
              advice_id: group.group_no <= 0 ? group.advices[0].id : 0
            }
          }

          CheckDoctorAdvice(params)
            .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].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.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.user.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(',')
          console.log(this.currentAdviceIdsStr)
          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.user.id) {
              Toast.fail('核对与执行不能是同一人')
              return false
            }
          }

          this.nowExecTime = new Date(group_top_advice.start_time * 1000)
        }
        this.$refs.exec_time.open()
      },
      openNewChild () {
        if (this.currentAdvices.length == 0) {
          return false
        }
        this.current_advice = this.currentAdvices[0]

        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
        )
        return
      },
      openNewAdvice () {

        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
        }

        if (this.current_advice_index >= 0) {
          this.index = 3
          var advice = this.currentSubAdvices[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
          })
        }

      },
      modifyAdviceAction: function () {
        if (this.current_group_index < 0) {
          return
        }
        var group = this.advice_groups[this.current_group_index]

        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,
            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
          })
        } 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
            })
          } 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
            }
          }
        }

        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
      }
    }
  }
</script>

<style style="stylesheet/scss" lang="scss" scoped>
  .DialogContent{
  .content{
  .yzNav{
  position: fixed;
  top: 0.16rem;
  }
  }
  }
  .table {
  width: 100%;
  tr {
  th {
  background: $main-color;
  color: #fff;
  height: 0.88rem;
  line-height: 0.88rem;
  }
  td {
  line-height: 0.4rem;
  .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;
  }
  }
</style>

