<template>
  <div class="mainBox">
    <side-bar :active_index="0"></side-bar>
    <div class="mainContent">
      <div class="navigation">
        <div class="goBack">
          <span class="back" @click="$router.back(-1)"><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="9">
            <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="9">
            <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-col :span="9">
            <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-row>
        <van-row class="row">
          <van-col :span="9">
            <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-col :span="9">
            <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-row>
        <van-row class="row">
          <van-col :span="24">
            <span class="title">&nbsp;</span>
            <div class="field_panel">
              <van-button type="info" size="normal" @click="submitAction">立即排班</van-button>
            </div>
          </van-col>
        </van-row>
      </div>
    </div>

    <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 :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 :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, postUrgentSchedule} from '@/api/dialysis'
  import {Dialog, Toast} from 'vant'

  export default {
    name: 'AddUrgentSchedule',
    components: {
      SideBar,
    },
    data () {
      return {
        loading: false,

        date: '2019-09-09',
        patient_id: 0,
        mode_id: 0,
        device_id: 0,
        schedule_type: 1,
        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: [],
      }
    },
    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) {
            return type.text
          }
        }
        return ''
      },
    },
    mounted () {
      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
      }

      this.loading = true
      getUrgentScheduleInitData().then(rs => {
        this.loading = false
        // console.log(rs.data.data)
        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

          for (let i = this.origin_schedules.length-1; i >= 0 ; i--) {
            for (let y = this.origin_device_numbers.length-1; y >=0 ; y--){
              if(this.origin_device_numbers[y].id == this.origin_schedules[i].bed_id){
                this.origin_device_numbers.splice(y,1)
              }
            }
          }

          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: {
      // getDeviceNumberNames: function(device_numbers) {
      //     var names = []
      //     for (let index = 0; index < device_numbers.length; index++) {
      //         const device_number = device_numbers[index];
      //         names.push(device_number.number)
      //     }
      //     return names
      // },

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

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

      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) {
            console.log(resp.data)
            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.3rem 0.36rem;
  border-bottom: 1px #e5e5e5 solid;
  position: fixed;
  top: 0;
  left:1.58rem;
  right: 0;
  z-index: 100;
  background: #fff;
  .goBack {
  float: left;
  .back {
  color: $main-color;
  margin-right: 0.87rem;
  .iconfont {
  color: $main-color;
  }
  }
  }
  .nav {
  text-align: center;
  font-size: 0.36rem;
  }
  }

  .form {
  background: #fff;
  min-height: calc(100vh - 2px);
  padding-top:55px;
  padding-left: 20px;
  .row {
  padding: 5px 0;
  .title {
  color: #8f8f8f;
  margin-right: 5px;
  text-align: right;
  font-size: 16px;
  line-height: 45px;
  width: 80px;
  float: left;
  }
  .field_panel {
  display: inline-block;
  .field {
  padding: 0 0;
  font-size: 18px;
  line-height: 45px;
  width: 180px;
  }
  }

  .danger_hint {
  font-size: 0.34rem;
  line-height: 40px;
  text-align: center;
  color: red;
  }
  }
  }
  }
  .popup {
  border-radius: 0 !important;
  top: initial !important;
  }
</style>

