<template>
  <div class="mainBox">
    <div class="mainContent">
      <div class="navigation">
        <div class="goBack">
          <span class="back" @click="$router.back(-1)" style="font-size: 0.875rem;">
            <span class="iconfont">&#xe720;</span>返回
          </span>
        </div>
        <div class="nav">
          <span>临时排班</span>
        </div>
        <div class="goBack"></div>
      </div>

      <div class="form" v-loading="loading">
        <van-row class="row">
          <van-col :span="24" class="danger_hint">
            <!--本次临时排班会覆盖已有排班中的同班次、同床位的排班，请仔细检查后再提交-->
            温馨提示：本次临时排班只能调整到空余的床位
          </van-col>
        </van-row>
        <van-row class="row">
          <van-col :span="24">
            <div class="field_panel">
              <el-autocomplete
                class="Input"
                popper-class="my-autocomplete"
                v-model="value"
                :fetch-suggestions="querySearchAsync"
                :trigger-on-focus="false"
                placeholder="请输入病人名字"
                @select="handleSelect"
              >
                <i class="el-icon-search el-input__icon" slot="suffix"></i>
                <template slot-scope="{ item }">
                  <div class="name">{{ item.name }}</div>
                </template>
              </el-autocomplete>
            </div>
          </van-col>
        </van-row>
        <van-row class="row">
          <van-col :span="24">
            <span class="title">日期：</span>
            <div class="field_panel">
              <van-field v-model="date" class="field"></van-field>
            </div>
          </van-col>
        </van-row>
        <van-row class="row">
          <van-col :span="24">
            <span class="title">患者：</span>
            <div class="field_panel">
              <van-field
                ref="patient_field"
                @focus="selectPatientAction"
                :value="patient_name"
                class="field"
                left-icon="arrow-down"
              ></van-field>
            </div>
          </van-col>
        </van-row>
        <van-row class="row">
          <van-col :span="24">
            <span class="title">班次：</span>
            <div class="field_panel">
              <van-field
                ref="sch_type_field"
                @focus="selectSchTypeAction"
                :value="schedule_type_title"
                class="field"
                left-icon="arrow-down"
              ></van-field>
            </div>
          </van-col>

          <van-col :span="24">
            <span class="title">床位：</span>
            <div class="field_panel">
              <van-field
                ref="bed_field"
                @focus="selectBedAction"
                :value="bed_name"
                class="field"
                left-icon="arrow-down"
              ></van-field>
            </div>
          </van-col>

          <van-col :span="24">
            <span class="title">治疗模式：</span>
            <div class="field_panel">
              <van-field
                ref="mode_field"
                @focus="selectModeAction"
                :value="mode_name"
                class="field"
                left-icon="arrow-down"
              ></van-field>
            </div>
          </van-col>
        </van-row>
        <van-row class="row">
          <van-col :span="24">
            <div class="nowScheduling" @click="submitAction">立即排班</div>
          </van-col>
        </van-row>
      </div>
    </div>
    <!-- <side-bar :active_index="0"></side-bar> -->
    <van-popup v-model="show_patient_picker" position="bottom" class="popup">
      <van-picker :columns="patients" value-key="name" @change="didChangePatient"></van-picker>
    </van-popup>
    <van-popup v-model="show_mode_picker" position="bottom" class="popup">
      <van-picker :columns="modes" value-key="name" @change="didChangeMode"></van-picker>
    </van-popup>
    <van-popup v-model="show_bed_picker" position="bottom" class="popup">
      <van-picker
        ref="picker"
        :columns="zone_device_options"
        value-key="number"
        @change="didChangeBed"
      ></van-picker>
    </van-popup>
    <van-popup v-model="show_sch_type_picker" position="bottom" class="popup">
      <van-picker
        :default-index="defaultIndex"
        ref="schedule"
        :columns="schedule_types"
        value-key="text"
        @change="didChangeSchType"
      ></van-picker>
    </van-popup>
  </div>
</template>

<script>
import SideBar from '@/pages/layout/SideBar'
import { parseTime } from '@/utils'
import {
  getUrgentScheduleInitData,
  PostSearch,
  postUrgentSchedule
} from '@/api/dialysis'
import { Dialog, Toast } from 'vant'

export default {
  name: 'AddUrgentSchedule',
  components: {
    SideBar
  },
  data () {
    return {
      loading: false,
      value: '',
      date: '2019-09-09',
      patient_id: 0,
      mode_id: 0,
      device_id: 0,
      schedule_type: 2,
      zone_name: '',

      show_patient_picker: false,
      show_mode_picker: false,
      show_bed_picker: false,
      show_sch_type_picker: false,

      patients: [],
      modes: [],
      schedule_types: [
        { value: 1, text: '上午' },
        { value: 2, text: '下午' },
        { value: 3, text: '晚上' }
      ],

      origin_device_numbers: [],
      zone_device_map: {},
      zone_names: [],
      current_devices: [],
      zone_device_options: [],

      origin_schedules: [],
      defaultIndex: 0
    }
  },
  computed: {
    patient_name: function () {
      for (let index = 0; index < this.patients.length; index++) {
        const patient = this.patients[index]
        if (patient.id == this.patient_id) {
          return patient.name
        }
      }
      return ''
    },
    mode_name: function () {
      for (let index = 0; index < this.modes.length; index++) {
        const mode = this.modes[index]
        if (mode.id == this.mode_id) {
          return mode.name
        }
      }
      return ''
    },
    bed_name: function () {
      if (this.zone_name.length > 0 && this.device_id != 0) {
        for (let index = 0; index < this.current_devices.length; index++) {
          const device_number = this.current_devices[index]
          if (device_number.id == this.device_id) {
            return device_number.zone_name + ' - ' + device_number.number
          }
        }
      }
      return ''
    },
    schedule_type_title: function () {
      for (let index = 0; index < this.schedule_types.length; index++) {
        const type = this.schedule_types[index]
        if (type.value == this.schedule_type) {
          this.defaultIndex = this.schedule_type - 1
          return type.text
        }
      }
      return ''
    }
  },
  created () {
    var today = new Date()
    this.date = parseTime(today, '{y}-{m}-{d}')
    var hour = today.getHours()
    if (hour > 3 && hour < 11) {
      this.schedule_type = 1
    } else if (hour >= 11 && hour < 18) {
      this.schedule_type = 2
    } else {
      this.schedule_type = 3
    }
  },
  mounted () {
    this.loading = true
    let params = {
      type: this.schedule_type
    }

    getUrgentScheduleInitData(params)
      .then(rs => {
        this.loading = false

        if (rs.data.state == 1) {
          this.origin_schedules = rs.data.data.schedules

          this.patients = rs.data.data.patients
 
          this.modes = rs.data.data.modes
          this.origin_device_numbers = rs.data.data.device_numbers

          if (this.patients.length > 0) {
            this.patient_id = this.patients[0].id
          }
          if (this.modes.length > 0) {
            this.mode_id = this.modes[0].id
          }

          var zone_device_map = {}
          for (
            let index = 0;
            index < this.origin_device_numbers.length;
            index++
          ) {
            const device_number = this.origin_device_numbers[index]
            if (
              zone_device_map[device_number.zone_name] == null ||
              zone_device_map[device_number.zone_name] == undefined
            ) {
              zone_device_map[device_number.zone_name] = []
            }
            zone_device_map[device_number.zone_name].push(device_number)
          }
          this.zone_device_map = zone_device_map

          this.zone_names = Object.keys(this.zone_device_map)
          if (this.zone_names.length > 0) {
            this.zone_name = this.zone_names[0]
            this.current_devices = this.zone_device_map[this.zone_name]
            this.device_id = this.current_devices[0].id
          }
          this.zone_device_options = [
            { values: this.zone_names },
            // { values: this.getDeviceNumberNames(this.current_devices) },
            { values: this.current_devices }
          ]
        } else {
          Toast.fail(rs.data.msg)
        }
      })
      .catch(err => {
        this.loading = false
        Toast.fail(err)
      })
  },
  methods: {
    handleSelect (val) {

      this.patient_name = val.name
      this.patient_id = val.id
    },
    querySearchAsync (keyword, cb) {
      let key = ''
      if (keyword != undefined) {
        key = keyword
      }
      let searchArray = []
      let newArr=[]
      PostSearch(key).then(response => {
        if (response.data.state == 1) {
          searchArray = response.data.data.patient
          cb(searchArray)
        } else {
          cb([])
        }
      })
    },

    selectPatientAction: function () {
      this.$refs.patient_field.blur()
      this.show_patient_picker = true
    },
    selectModeAction: function () {
      this.$refs.mode_field.blur()
      this.show_mode_picker = true
    },
    selectBedAction: function () {
      this.$refs.bed_field.blur()
      this.show_bed_picker = true
    },
    selectSchTypeAction: function () {
      this.$refs.sch_type_field.blur()
      this.show_sch_type_picker = true
      //
      // this.$nextTick(() => {
      //   // this.$refs.schedule.setColumnIndex(2)
      //   // .setIndexes(this.schedule_type)
      //
      // })
    },

    didChangePatient: function (picker, patient, index) {
      this.patient_id = patient.id
    },
    didChangeMode: function (picker, mode, index) {
      this.mode_id = mode.id
    },
    didChangeBed: function (picker, values, col_index) {
      if (col_index == 0) {
        this.zone_name = values[0]
        this.current_devices = this.zone_device_map[this.zone_name]
        this.device_id = this.current_devices[0].id

        picker.setColumnValues(1, this.current_devices)
      } else if (col_index == 1) {
        this.device_id = values[1].id
      }
    },
    didChangeSchType: function (picker, sch_type, index) {
      this.schedule_type = sch_type.value
      this.loading = true
      let params = {
        type: this.schedule_type
      }
      getUrgentScheduleInitData(params)
        .then(rs => {
          this.loading = false

          if (rs.data.state == 1) {
            this.zone_device_options = []
            this.origin_schedules = rs.data.data.schedules
            this.patients = rs.data.data.patients
            this.modes = rs.data.data.modes
            this.origin_device_numbers = rs.data.data.device_numbers

            var zone_device_map = {}
            for (
              let index = 0;
              index < this.origin_device_numbers.length;
              index++
            ) {
              const device_number = this.origin_device_numbers[index]
              if (
                zone_device_map[device_number.zone_name] == null ||
                zone_device_map[device_number.zone_name] == undefined
              ) {
                zone_device_map[device_number.zone_name] = []
              }
              zone_device_map[device_number.zone_name].push(device_number)
            }
            this.zone_device_map = zone_device_map

            this.zone_names = Object.keys(this.zone_device_map)
            if (this.zone_names.length > 0) {
              this.zone_name = this.zone_names[0]
              this.current_devices = this.zone_device_map[this.zone_name]
              this.device_id = this.current_devices[0].id
            }
            this.zone_device_options = [
              { values: this.zone_names },
              // { values: this.getDeviceNumberNames(this.current_devices) },
              { values: this.current_devices }
            ]
          } else {
            Toast.fail(rs.data.msg)
          }
        })
        .catch(err => {
          this.loading = false
          Toast.fail(err)
        })
    },

    submitAction: function () {
      if (this.patient_id == 0 || this.mode_id == 0 || this.device_id == 0) {
        Toast.fail('请选择班次、床位等')
        return
      }

      var repeated = false
      for (let index = 0; index < this.origin_schedules.length; index++) {
        const schedule = this.origin_schedules[index]
        if (
          schedule.bed_id == this.device_id &&
          this.schedule_type == schedule.schedule_type
        ) {
          repeated = true
          break
        }
      }
      if (repeated) {
        Dialog.confirm({
          title: '提醒',
          message: '你选择的床位已经被排班，确认要替换吗？'
        })
          .then(() => {
            // on confirm
            this.submit()
          })
          .catch(() => {
            // on cancel
          })
      } else {
        this.submit()
      }
    },
    submit: function () {
      var params = {
        patient_id: this.patient_id,
        mode: this.mode_id,
        schedule_type: this.schedule_type,
        bed: this.device_id
      }
      this.loading = true
      postUrgentSchedule(params)
        .then(rs => {
          this.loading = false
          var resp = rs.data
          if (resp.state == 1) {
            var patient = resp.data.patient
            var schedule = resp.data.schedule
            this.$router.push({
              path: '/details',
              query: {
                patient_id: patient.id,
                date: schedule.schedule_date,
                patient_name: patient.name
              }
            })
          } else {
            Toast.fail(resp.msg)
          }
        })
        .catch(err => {
          this.loading = false
          Toast.fail('err')
        })
    }
  }
}
</script>

<style style="stylesheet/scss" lang="scss" scoped>
.mainContent {
  position: relative;
  .navigation {
    padding: 0.5625rem 0.625rem;
    border-bottom: 1px #e5e5e5 solid;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;
    .goBack {
      float: left;
      .back {
        color: $main-color;
        margin-right: 1.625rem;
        .iconfont {
          color: $main-color;
        }
      }
    }
    .nav {
      text-align: center;
      font-size: 0.875rem;
      margin-right: 3.5rem;
    }
  }

  .form {
    background: #fff;
    min-height: calc(100vh - 2px);
    padding-top: 3.4375rem;
    // padding-left: 20px;
    @media only screen and (min-width: 768px) {
      padding-top: 6.25rem;
    }
    .row {
      // padding: 5px 0;
      width: 80%;
      margin: 0 auto;
      .title {
        color: #8f8f8f;
        margin-right: 0.3125rem;
        text-align: left;
        font-size: 0.875rem;
        line-height: 2.8125rem;
        width: 5.625rem;
        float: left;
        // @media only screen and (max-width: 812px) {
        //   font-size: 0.3rem !important;
        // }
        // @media only screen and (max-width: 376px) {
        //   width: 50px !important;
        //   font-size: 0.3rem !important;
        // }
      }
      .el-input__inner {
        @media only screen and (max-width: 812px) {
          height: 24px !important;
          line-height: 24px !important;
        }
      }
      .field_panel {
        // display: inline-block;
        height: 2.625rem;
        .field {
          padding: 0 0;
          font-size: 0.875rem;
          line-height: 2.8125rem;
          width: 11.25rem;
          // @media only screen and (max-width: 812px) {
          //   width: 100px;
          // }
        }
      }

      .danger_hint {
        font-size: 0.75rem;
        line-height: 2.5rem;
        text-align: center;
        color: #f56c6c;
        @media only screen and (max-width: 812px) {
          margin-left: -10px !important;
        }
      }
      .nowScheduling {
        width: 100%;
        height: 2.375rem;
        line-height: 2.375rem;
        border-radius: 1.875rem;
        text-align: center;
        background: #258ffc;
        font-size: 0.875rem;
        color: #fff;
        margin-top: 0.9375rem;
      }
    }
  }
}
.popup {
  border-radius: 0 !important;
  top: initial !important;
  transform: translate3d(0, 0, 0) !important;
}
.mainBox {
  display: flex;
  height: 100%;
  flex-direction: column;
  > :first-child {
    overflow: auto;
    flex: 1;
  }
}
</style>
<style lang="scss">
.Input {
  width: 100%;
  .el-input__inner {
    border-radius: 30px;
    font-size: 0.75rem;
    @media only screen and (max-width: 767px) {
      height: 2.625rem;
      line-height: 2.625rem;
    }
    @media only screen and (min-width: 768px) {
      height: 2.25rem;
      line-height: 2.25rem;
      border-radius: 50px;
    }
  }
  .el-input__icon {
    font-size: 0.875rem;
    @media only screen and (min-width: 768px) {
      margin-top: 2px;
      margin-right: 8px;
    }
  }
}
.form {
  .van-ellipsis {
    font-size: 0.875rem;
  }
}
</style>
