<template>
  <div>

    <div class="Dialog" v-show="!selecting">
      <div class="DialogTit">
        <span @click="close()" class="iconfont">&#xe6e9;</span>
        <h1 class="name">透析上机</h1>
        <span class="success" v-if="this.record.id == 0 || this.$store.getters.user.user.id != this.creator"></span>
        <span class="success" @click="modify()" v-if="isPremission|| this.$store.getters.user.user.id == this.creator">修改</span>
      </div>

      <div class="DialogContent ">
        <div class="item" @click="select_type">
          <h2 class="name">班次</h2>
          <div class="content">
            <span class="text" style="width: 100px">{{getSchedualType(this.schedual_type)}}</span>
            <span class="iconfont">&#xe6f9;</span>
          </div>
        </div>
        <div class="item" @click="select_bed">
          <h2 class="name">上机床位</h2>
          <div class="content">
            <span class="text" style="width: 100px">{{ device_number_map[bed_id].number }}</span>
            <span class="iconfont">&#xe6f9;</span>
          </div>
        </div>
        <div class="item" @click="select_nurse">
          <h2 class="name">上机护士</h2>
          <div class="content">
            <span class="text" style="width: 100px">{{ admin_map[nurse_id].name }}</span>
            <span class="iconfont">&#xe6f9;</span>
          </div>
        </div>

        <div class="item" @click="select_puncture_nurse">
          <h2 class="name">穿刺者</h2>
          <div class="content">
            <span class="text" style="width: 100px" v-if="admin_map[puncture_nurse_id]">{{ admin_map[puncture_nurse_id].name}}</span>
            <span class="iconfont">&#xe6f9;</span>
          </div>
        </div>

        <div class="item" v-if="template_id == 6">
          <label class="name" for="xll">引血(ml/min)</label>
          <div class="content">
            <input type="tel" @focus="inputFocus"  id="xll" v-model="blood_drawing"/>
          </div>
        </div>

        <div class="item">
          <h2 class="name">上机时间</h2>
          <div class="content">
            <span class="text" style="width: 100px" @click="selectStartTimeAction">{{ start_time_str }}</span>
            <span class="iconfont">&#xe6f9;</span>
          </div>
        </div>




        <div class="perform">
          <button @click="commitInfo" v-if="(record == null || record.id == '')">执行上机</button>
          <button :disabled="true" style="background-color:lightgray;" v-else>已上机</button>
        </div>
      </div>
    </div>

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


<script>
  import {startDialysis,PostModifyStartDialysis,GetSchedualNumber} from '@/api/dialysis'
  import {Toast} from 'vant'
  import {parseTime} from '@/utils'

  import TwoMenu from './TwoMenu'

  export default {
    name: 'ComputerDialog',
    components: {
      TwoMenu
    },
    data () {
      return {
        start_time: new Date(),
        selecting: false,
        start_time_str: '',
        bed_id: 0,
        nurse_id: 0,
        puncture_nurse_id: 0,
        isPremission: false,
        zone_beds: [], // 该排班的区里的床位
        creator: 0,
        template_id: 0,
        temp_device_numbers:[],
        blood_drawing:100,
        schedual_type:0,
        schedules_type: [
          {id: 1, name:"上午"},
          {id: 2, name:"下午"},
          {id: 3, name:"晚上"},
        ], // 该排班的区里的床位
      }
    },
    props: {
      schedule: {
        type: Object,
      },
      patient_prop: {
        type: Object,
      },
      record: {
        type: Object,
      },
      admins: {
        type: Array,
      },
      device_numbers: {
        type: Array,
      },
      admin_map: {
        type: Object,
      },
      device_number_map: {
        type: Object,
      },
      special_premission: {
        type: Array,
      },
    }, mounted () {


    },
    created () {
      this.temp_device_numbers = this.device_numbers



      if (this.record.id == 0) {
        this.start_time_str = parseTime(this.start_time, '{y}-{m}-{d} {h}:{i}') + ':00'
        let now = new Date()
        let hour = now.getHours()

        if (hour >= 6 && hour < 12){
          this.schedual_type = 1

        }else if(hour >= 12 && hour < 18){

          this.schedual_type = 2


        }else if(hour >= 18){
          this.schedual_type = 3
        }
      } else {
        if (this.record.start_time == 0) {
          this.start_time_str = parseTime(this.start_time, '{y}-{m}-{d} {h}:{i}') + ':00'
          this.schedual_type = this.record.schedual_type

        } else {
          this.start_time_str = parseTime(this.record.start_time, '{y}-{m}-{d} {h}:{i}') + ':00'
          this.schedual_type = this.record.schedual_type

        }
      }


      this.GetSchedualNumber()

      this.template_id = this.$store.getters.user.template_info.template_id;
      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.bed_id = (this.record == null || this.record.id == '') ? this.schedule.bed_id : this.record.bed_id
      this.nurse_id = (this.record == null || this.record.id == '') ? this.$store.getters.user.user.id : this.record.start_nurse
      this.puncture_nurse_id = (this.record == null || this.record.id == '') ? this.$store.getters.user.user.id : this.record.puncture_nurse

      if (this.puncture_nurse_id == 0) {
        this.puncture_nurse_id = this.$store.getters.user.user.id
      }

      // var beds = []
      // for (let index = 0; index < this.device_numbers.length; index++) {
      //   const device_number = this.device_numbers[index]
      //   if (device_number.zone_id == this.schedule.partition_id) {
      //     beds.push(device_number)
      //   }
      // }
      // this.zone_beds = beds

      for (let index = 0; index < this.temp_device_numbers.length; index++) {
        const device_number = this.temp_device_numbers[index]
        this.temp_device_numbers[index]['number'] = device_number['zone_name']+'-'+device_number['number']
      }
      this.zone_beds = this.temp_device_numbers

      if (this.record.id > 0) {
        for (let i = 0; i < this.special_premission.length; i++) {
          if (this.$store.getters.user.user.id == this.special_premission[i].admin_user_id) {
            this.isPremission = true
          }
        }
      }

      if (this.record.id > 0) {
        if (this.record.creator == 0) {
          this.creator = this.record.start_nurse
        } else {
          this.creator = this.record.creator
        }
      }



    },
    methods: {
      getSchedualType:function(type){
        for (let i = 0; i < this.schedules_type.length; i++){
          if(this.schedules_type[i].id == type){
            return  this.schedules_type[i].name
          }
        }
      },
      select_type:function(){
        if (this.record.id != 0) {
          var creator = 0
          if (this.record.creator == 0) {
            creator = this.record.start_nurse
          } else {
            creator = this.record.creator
          }

          if (this.$store.getters.user.user.id == creator || this.isPremission) {
            this.selecting = true
            var t = this
            this.$refs.selector.showSingleSelect(this.schedules_type, this.schedual_type, '选择班次', 'name', 'id', function (select_id) {
              t.schedual_type = select_id

              let ParamsQuery = {}
              ParamsQuery['schedual_type'] = select_id
              GetSchedualNumber(ParamsQuery).then(response => {
                if (response.data.state == 0) {
                  Toast.fail(response.data.msg)
                  return false
                } else {
                  t.temp_device_numbers = response.data.data.number
                  for (let index = 0; index < t.temp_device_numbers.length; index++) {
                    const device_number = t.temp_device_numbers[index]
                    t.temp_device_numbers[index]['number'] = device_number['zone_name']+'-'+device_number['number']
                  }
                  t.zone_beds = t.temp_device_numbers
                  t.bed_id = t.zone_beds[0].id
                }
              })
            }, function () {
              t.selecting = false
            })
          } else {
            return
          }
        }
        this.selecting = true
        var t = this
        this.$refs.selector.showSingleSelect(this.schedules_type, this.schedual_type, '选择班次', 'name', 'id', function (select_id) {
          t.schedual_type = select_id
          let ParamsQuery = {}
          ParamsQuery['schedual_type'] = select_id
          GetSchedualNumber(ParamsQuery).then(response => {
            if (response.data.state == 0) {
              Toast.fail(response.data.msg)
              return false
            } else {
              t.zone_beds = []
              t.temp_device_numbers = response.data.data.number
              for (let index = 0; index < t.temp_device_numbers.length; index++) {
                const device_number = t.temp_device_numbers[index]
                t.temp_device_numbers[index]['number'] = device_number['zone_name']+'-'+device_number['number']
              }
              t.zone_beds = t.temp_device_numbers
              t.bed_id = t.zone_beds[0].id


            }
          })
        }, function () {
          t.selecting = false
        })

      },
      GetSchedualNumber:function(){
        let ParamsQuery = {}
        ParamsQuery['schedual_type'] = this.schedual_type
        GetSchedualNumber(ParamsQuery).then(response => {
          if (response.data.state == 0) {
            Toast.fail(response.data.msg)
            return false
          } else {
            this.temp_device_numbers = response.data.data.number
            for (let index = 0; index < this.temp_device_numbers.length; index++) {
              const device_number = this.temp_device_numbers[index]
              this.temp_device_numbers[index]['number'] = device_number['zone_name']+'-'+device_number['number']
            }
            this.zone_beds = this.temp_device_numbers
          }
        })
      },

      inputFocus: function (event) {
        var input = event.target
        setTimeout(function () {
          input.scrollIntoView()
        }, 0)

        if (input.setSelectionRange) {
          setTimeout(function () {
            input.setSelectionRange(0, input.value.length)
          }, 0)
        } else if (input.createTextRange) {
          var rng = input.createTextRange()
          rng.move('character', input.value.length)
          rng.select()
        }
      },
      modify(){
        let ParamsQuery = {}
        ParamsQuery['schedual_type'] = this.schedual_type
        ParamsQuery['id'] = this.record.id
        ParamsQuery['nurse'] = this.nurse_id
        ParamsQuery['bed'] = this.bed_id
        ParamsQuery['start_time'] = this.start_time_str
        ParamsQuery['puncture_nurse'] = this.puncture_nurse_id
        PostModifyStartDialysis(ParamsQuery).then(response => {
          if (response.data.state == 0) {
            Toast.fail(response.data.msg)
            return false
          } else {
            Toast.success('修改成功')
            this.$emit('did_start', response.data.data.dialysis_order)
            var record = this.record
            for (const key in response.data.data.dialysis_order) {
              this.$set(record, key, response.data.data.dialysis_order[key])
            }
          }
        }).catch(error => {
          Toast.fail("请求失败")
        });
      },
      didSelectStartTime: function (time) {
        this.start_time_str = parseTime(time, '{y}-{m}-{d} {h}:{i}') + ':00'
      },
      selectStartTimeAction: function () {
        if (this.record.id != 0) {
          var creator = 0
          if (this.record.creator == 0) {
            creator = this.record.start_nurse
          } else {
            creator = this.record.creator
          }

          if (this.$store.getters.user.user.id == creator || this.isPremission) {
            this.$refs.start_time_picker.open()
          } else {
            return
          }
        }
        this.$refs.start_time_picker.open()
      },
      commitInfo: function () {
        Toast.loading({forbidClick: true, duration: 0})
        let ParamsQuery = {}
        ParamsQuery['schedual_type'] = this.schedual_type
        ParamsQuery['patient_id'] = this.patient_prop.id
        ParamsQuery['record_date'] = this.record_date
        ParamsQuery['nurse'] = this.nurse_id
        ParamsQuery['bed'] = this.bed_id
        ParamsQuery['start_time'] = this.start_time_str
        ParamsQuery['puncture_nurse'] = this.puncture_nurse_id
        ParamsQuery['blood_drawing'] = this.blood_drawing

        startDialysis(ParamsQuery).then(response => {
          if (response.data.state == 0) {
            Toast.fail(response.data.msg)
            return false
          } else {
            Toast.success('上机成功')
            var monitor = response.data.data.monitor
            this.$emit('did_add_monitor', monitor)
            this.$emit('did_start', response.data.data.dialysis_order)
            var record = this.record
            for (const key in response.data.data.dialysis_order) {
              this.$set(record, key, response.data.data.dialysis_order[key])
              // this.record[key] = response.data.data.dialysis_order[key]
            }
          }
        }).catch(error => {
          Toast.fail("请求失败")
        });
      },
      close: function () {
        this.$emit('close')
      },
      select_bed: function () {
        if (this.record.id != 0) {
          var creator = 0
          if (this.record.creator == 0) {
            creator = this.record.start_nurse
          } else {
            creator = this.record.creator
          }

          if (this.$store.getters.user.user.id == creator || this.isPremission) {
            this.selecting = true
            var t = this
            this.$refs.selector.showSingleSelect(this.zone_beds, this.bed_id, '选择床位号', 'number', 'id', function (select_id) {
              t.bed_id = select_id
            }, function () {
              t.selecting = false
            })
          } else {
            return
          }
        }

        this.selecting = true
        var t = this
        this.$refs.selector.showSingleSelect(this.zone_beds, this.bed_id, '选择床位号', 'number', 'id', function (select_id) {
          t.bed_id = select_id
        }, function () {
          t.selecting = false
        })
      },
      select_nurse: function () {
        if (this.record.id != 0) {
          var creator = 0
          if (this.record.creator == 0) {
            creator = this.record.start_nurse
          } else {
            creator = this.record.creator
          }
          if (this.$store.getters.user.user.id == creator || this.isPremission) {
            this.selecting = true
            var t = this
            this.$refs.selector.showSingleSelect(this.admins, this.nurse_id, '选择上机护士', 'name', 'id', function (select_id) {
              t.nurse_id = select_id
            }, function () {
              t.selecting = false
            })
          } else {
            return
          }
        }
        this.selecting = true
        var t = this
        this.$refs.selector.showSingleSelect(this.admins, this.nurse_id, '选择上机护士', 'name', 'id', function (select_id) {
          t.nurse_id = select_id
        }, function () {
          t.selecting = false
        })
      }, select_puncture_nurse: function () {
        if (this.record.id != 0) {
          var creator = 0
          if (this.record.creator == 0) {
            creator = this.record.start_nurse
          } else {
            creator = this.record.creator
          }
          if (this.$store.getters.user.user.id == creator || this.isPremission) {
            this.selecting = true
            var t = this
            this.$refs.selector.showSingleSelect(this.admins, this.puncture_nurse_id, '选择穿刺护士', 'name', 'id', function (select_id) {
              t.puncture_nurse_id = select_id
            }, function () {
              t.selecting = false
            })
          } else {
            return
          }
        }
        this.selecting = true
        var t = this
        this.$refs.selector.showSingleSelect(this.admins, this.puncture_nurse_id, '选择穿刺护士', 'name', 'id', function (select_id) {
          t.puncture_nurse_id = select_id
        }, function () {
          t.selecting = false
        })
      },
      open: function () {
        this.selecting = false
        this.$refs.selector.hide()
      }
    }, watch: {
      'record.id': function (val) {
        if (val > 0) {
          for (let i = 0; i < this.special_premission.length; i++) {
            if (this.$store.getters.user.user.id == this.special_premission[i].admin_user_id) {
              this.isPremission = true
            }
          }
          if (this.record.creator == 0) {
            this.creator = this.record.start_nurse
          } else {
            this.creator = this.record.creator
          }


        }
      }

    }

  }
</script>

<style style="stylesheet/scss" lang="scss" scoped>
.perform {
  text-align: center;
  font-size: 0.3rem;
  padding-top: 2rem;
  .crew {
    color: $pgh-color;
  }
  button {
    background: $main-color;
    color: #fff;
    font-size: 0.45rem;
    text-align: center;
    width: 3rem;
    height: 1.2rem;
    line-height: 1.2rem;
    border-radius: 4px;
    margin-top: 10px;
  }
}
</style>
