<template>
  <div>
    <loading :active.sync="loaderKVM" :can-cancel="false" :is-full-page="false"></loading>
    <div class="InnerInfo">
      <div class="row InnerSelect" v-show="isshowTool">
        <div class="col-md-3" v-show="!hidden">
          <div class="item-list">
            <div class="item-title">{{'deviceon.device.wizard.selectAccount' | translate}}</div>
            <vuestic-simple-select
              v-model="selectedAccount"
              option-key="mail"
              :options="accountOptions"
              :unselect-disabled="true"
              :notCollapse="true"
              :showSearchBox="true"
              :searchText="$t('deviceon.wizard.keywordSearch')"
              v-tooltip.top-center="{ content: selectedAccount.mail, trigger: 'hover', offset: 8}"
            />
          </div>
        </div>
        <div class="col-md-3" v-show="!hidden">
          <div class="item-list">
            <div class="item-title">{{'deviceon.device.wizard.selectGroup' | translate}}</div>
            <vuestic-simple-select
              v-model="selectedGroup"
              option-key="name"
              :options="groupOptions"
              :unselect-disabled="true"
              :notCollapse="true"
              :showSearchBox="true"
              :searchText="$t('deviceon.wizard.keywordSearch')"
              @showdropdown="groupDropStatus('open')"
              @closedropdown="groupDropStatus('close')"
            />
          </div>
        </div>
        <div class="col-md-3" v-show="!hidden">
          <div class="item-list">
            <div class="item-title">{{'deviceon.device.wizard.selectDevice' | translate}}</div>
            <vuestic-simple-select
              v-model="selectedDevice"
              option-key="name"
              :options="deviceOptions"
              :unselect-disabled="true"
              :notCollapse="true"
              :showSearchBox="true"
              :searchText="$t('deviceon.wizard.keywordSearch')"
              :showdropdownstatus="true"
              :dropStatus='dropStatus'
              :limitclass="'device-data-dropdown'"
              :class="{'disable': totalDevices === 0}"
              @filterSelection="serchTxt"
              @scroll-to-bottom="ScrollToBottom"
            />
          </div>
        </div>
        <div class="chart-title" :class="{'col-md-3':!hidden}">
          <div class="map-popup-title map-kvm-title" v-if="hidden">
            {{selectedDevice.name}}
          </div>
          <!--Screen Big -->
          <span class="btn-svg svg-colorful" @click="ScreenBig" v-if="!ScreensmallBtn" v-tooltip.top-center="{ content: $t('deviceon.device.view.zoom'), trigger: 'hover', offset: 8}">
            <icon iconName="tool-zoomin"/>
          </span>
          <!--Screen Small-->
          <span class="btn-svg svg-colorful" @click="Screensmall" v-if="ScreensmallBtn" v-tooltip.top-center="{ content: $t('deviceon.device.view.zoomOut'), trigger: 'hover', offset: 8}">
            <icon iconName="tool-zoomout"/>
          </span>
          <span v-if="!oRMM.iscfapp && amtsupport" class="btn-svg svg-colorful" @click="iAMTPower" v-tooltip.top-center="{ content: $t('deviceon.power.iAMT.intel-iamt'), trigger: 'hover', offset: 8}">
            <icon iconName="intel-AMT-normal"/>
          </span>
        </div>
      </div>
      <div class="text-right mb-2" v-show="!isshowTool">
        <!--Screen Big -->
        <span class="btn-svg svg-colorful" @click="ScreenBig" v-if="!ScreensmallBtn" v-tooltip.top-center="{ content: $t('deviceon.device.view.zoom'), trigger: 'hover', offset: 8}">
          <icon iconName="tool-zoomin"/>
        </span>

      </div>
      <div class="chart-wrapper">
        <div class="panel_wrap" v-if="showKVM">
          <!--Screen Small-->
          <span class="btn-svg svg-colorful isActive tool-zoomout" @click="Screensmall" v-if="ScreensmallBtn" v-tooltip.top-center="{ content: $t('deviceon.device.view.zoomOut'), trigger: 'hover', offset: 8}">
            <icon iconName="tool-zoomout"/>
          </span>
          <iframe
            frameBorder="0"
            :src="kvmURL"
            style="width: 100%; height: 100%;">
          </iframe>
        </div>
      </div>
    </div>

    <vuestic-modal
      ref="iAMTPowerModal"
      :okText="'modal.confirm' | translate"
      :cancelText="'modal.cancel' | translate"
      :keepOpen="keepOpen"
      @ok="iAMTPowerOK"
    >
      <div slot="title">{{'deviceon.power.iAMT.intel-iamt' | translate}}</div>
      <div class="modal-content-inner pt-3 pb-3">
        <label class="labelStyle">{{'deviceon.power.iAMT.amt-status' | translate}}</label>
        <span style="font-weight:bold;">{{iAMTPowerStatus}}</span>
        <br>
        <br>
        <vuestic-simple-select
          :label="$t('deviceon.power.iAMT.amt-action')"
          v-model="iAMTPowerOption"
          :options="iAMTPowerOptions"
          option-key="name"
          :unselect-disabled="true"
        />
      </div>
    </vuestic-modal>
  </div>
</template>

<script>
import DeviceOnApis from '@/util/DeviceOnApis'
import RMMGlobal from '@/util/RMMGlobal'

let self
export default {
  name: 'KVM',
  data () {
    return {
      loaderKVM: true,
      showKVM: false,
      oRMM: RMMGlobal.get(),
      kvmURL: '',
      ScreensmallBtn: false,
      ScreensmallHover: false,
      ScreenBigHover: false,
      PanelWrap: '',
      selectedAccount: {},
      selectedGroup: {},
      selectedDevice: {},
      accountOptions: [],
      groupOptions: [],
      deviceOptions: [],

      // popup
      keepOpen: true,
      iAMTPowerOption: {},
      amtState: '', // "on", "off", "s3", "s4", "unknown",

      newGid: 0,
      dropNo: 1, // 撈下拉選單第幾頁資料
      totalDevices: 0,
      dropStatus: '', // onloading   finish  nodata
      keyword: '', // string
      keywordTimer: 0,
      isopendropdown: 'close',

      isshowTool: true
    }
  },
  props: {
    aid: {
      type: Number,
      default: 0
    },
    gid: {
      type: Number,
      default: 0
    },
    did: {
      type: Number,
      default: 0
    },
    agentid: {
      type: String,
      default: ''
    },
    os: {
      type: String,
      default: ''
    },
    amtsupport: {
      type: Boolean,
      default: false
    },
    vncMode: {
      type: String,
      default: 'false'
    },
    hidden: {
      type: Boolean,
      default: false
    }
  },
  mounted () {
    self = this
    console.log(this.aid, this.gid, this.did, this.agentid, this.os, this.amtsupport, this.vncMode)

    this.PanelWrap = this.$parent.$el.firstElementChild.firstElementChild.firstElementChild
    // if aid is undefined, because maybe is from AnomalyDetection open
    if (this.aid !== 0) {
      this.getAccounts(this.aid)
    } else {
      this.setKVMControl(this.agentid, this.os, this.amtsupport, this.vncMode)
      self.isshowTool = false
    }
  },
  methods: {
    setKVMControl (agentid, os, amtsupport, vncMode) {
      self.kvmURL = '/static/kvm/kvmIndex.html?agentId=' + agentid + '&os=' + os + '&amtsupport=' + amtsupport + '&vncMode=' + vncMode
      self.showKVM = true
      self.loaderKVM = false
    },
    ScreenBig () {
      this.PanelWrap.classList.add('changeBig')
      this.ScreensmallBtn = true
    },
    Screensmall () {
      this.PanelWrap.classList.remove('changeBig')
      this.ScreensmallBtn = false
    },
    iAMTPower () {
      // this.amtState = "on"
      // self.iAMTPowerOption = self.iAMTPowerOptions[0]
      DeviceOnApis.iamt.get
        .devices(this.agentid)
        .then(function (xhr) {
          if (xhr && xhr.data) {
            self.$refs.iAMTPowerModal.open()
            self.amtState = xhr.data.result.amtState
            setTimeout(function () {
              self.iAMTPowerOption = self.iAMTPowerOptions[0]
            }, 100)
          }
        })
        .catch(function (error) {
          DeviceOnApis.MessageBox.Error(self, error)
        })
    },
    iAMTPowerOK () {
      DeviceOnApis.MessageBox.Normal(
        self,
        self.$t('deviceon.power.iAMT.amt-action'),
        self.$t('deviceon.power.messages.confirm') + ' : ' + this.iAMTPowerOption.name,
        'warning',
        true
      ).then(value => {
        if (value.value) {
          let data = {
            agentId: self.agentid,
            action: self.iAMTPowerOption.key
          }
          DeviceOnApis.iamt.post
            .devices(data)
            .then(function (xhr) {
              self.isLoading = false
              if (xhr && xhr.data && xhr.data.result) {
                DeviceOnApis.MessageBox.Normal(
                  self,
                  self.$t('deviceon.power.messages.success'),
                  '',
                  'success'
                ).then(value => {
                  self.$refs.iAMTPowerModal.close()
                })
              } else {
                DeviceOnApis.MessageBox.Error(self, { message: xhr.data })
              }
            })
            .catch(function (error) {
              self.isLoading = false
              DeviceOnApis.MessageBox.Error(self, error)
            })
        }
      })
    },
    getAccounts (aid) {
      DeviceOnApis.accounts.get
        .accounts(aid)
        .then(function (xhr) {
          let data = self.sortAccounts(xhr, aid)
          if (data) {
            self.accountOptions = data.accountOptions
            self.selectedAccount = data.selectedAccount
          }
        })
        .catch(function (error) {
          self.loaderKVM = false
          DeviceOnApis.MessageBox.Error(self, error)
        })
    },
    getDeviceGroups (aid) {
      this.loaderKVM = true
      DeviceOnApis.accounts.get
        .deviceGroups(aid)
        .then(function (xhr) {
          let data = self.sortGroups(xhr, aid, self.gid, false)
          if (data) {
            self.groupOptions = data.groupOptions
            self.selectedGroup = data.selectedGroup
          }
          if (self.groupOptions.length === 0) {
            self.deviceOptions = []
            self.selectedDevice = ''
          }
          self.loaderKVM = false
        })
        .catch(function (error) {
          self.loaderKVM = false
          DeviceOnApis.MessageBox.Error(self, error)
        })
    },
    getDevices (gid, data) {
      this.isLoading = true
      if (gid === 0) {
        DeviceOnApis.devicegroups.get
          .devicesAll(data)
          .then(function (xhr) {
            if (xhr && xhr.data && xhr.data.devices) {
              self.totalDevices = xhr.data.total
              let data = self.LimitDevice_forEach(xhr.data.devices)
              data.deviceOptions.forEach(function (d, i) {
                self.deviceOptions.push(d)
              })

              let sortdata = self.LimitDevice_sort(self.deviceOptions)
              self.deviceOptions = sortdata

              let selectedDeviceDid = self.LimitDevice_did(self.deviceOptions, self.did)
              if (self.deviceOptions.length > 0) {
                self.dropStatus = 'finish'
                self.selectedDevice = selectedDeviceDid
              } else {
                self.deviceOptions = []
                self.selectedDevice = ''
                self.showPanel = false
                self.showType = 'no_device'
                self.dropStatus = 'nodata'
              }
            }
            self.isLoading = false
          })
          .catch(function (error) {
            self.isLoading = false
            DeviceOnApis.MessageBox.Error(self, error)
          })
      } else {
        this.isLoading = true
        DeviceOnApis.devicegroups.get
          .devices(gid, data)
          .then(function (xhr) {
            if (
              xhr &&
              xhr.data &&
              xhr.data.groups &&
              xhr.data.groups[0] &&
              xhr.data.groups[0] &&
              xhr.data.groups[0].devices
            ) {
              self.totalDevices = xhr.data.groups[0].total_acc_cond
              let data = self.LimitDevice_forEach(xhr.data.groups[0].devices)
              data.deviceOptions.forEach(function (d, i) {
                self.deviceOptions.push(d)
              })

              let sortdata = self.LimitDevice_sort(self.deviceOptions)
              self.deviceOptions = sortdata

              let selectedDeviceDid = self.LimitDevice_did(self.deviceOptions, self.did)
              if (self.deviceOptions.length > 0) {
                self.dropStatus = 'finish'
                self.selectedDevice = selectedDeviceDid
              } else {
                self.deviceOptions = []
                self.selectedDevice = ''
                self.showPanel = false
                self.showType = 'no_device'
                self.dropStatus = 'nodata'
              }
            }
            self.isLoading = false
          })
          .catch(function (error) {
            self.isLoading = false
            DeviceOnApis.MessageBox.Error(self, error)
          })
      }
    },
    // dropdown
    ScrollToBottom () {
      if (self.deviceOptions.length % 10 === 0 && (self.deviceOptions.length < self.totalDevices) && self.dropStatus !== 'onloading') {
        self.dropNo += 1
        self.dropStatus = 'onloading'
        let oData = {
          pageSize: 10,
          no: self.dropNo,
          orderBy: 'connected',
          orderType: 'desc',
          like: ''
        }
        setTimeout(function () {
          self.getDevices(self.gid, oData)
        }, 1000)
      }
    },
    groupDropStatus (value) {
      self.isGroupSelectOpen = value
    },
    serchTxt (Txt) {
      self.keyword = Txt
    },
    resetGetDevice (hasKeyWord) {
      // ""Group""" dropdown status:
      // if open : reset anything
      // if close: reset anything, and push how many dropNo for device, and focus selected device did
      self.deviceOptions = []
      self.totalDevices = 0
      let oData = {
        pageSize: 10,
        no: 1,
        orderBy: 'connected',
        orderType: 'desc',
        like: ''
      }
      if (hasKeyWord) {
        oData.like = hasKeyWord
        self.getDevices(self.newGid, oData)
      } else {
        if (self.isopendropdown === 'open') {
          self.dropNo = 1
          self.getDevices(self.newGid, oData)
        } else {
          if (self.dropNo > 1) {
            for (let i = 1; i <= self.dropNo; i++) {
              let ArrayData = {
                pageSize: 10,
                no: i,
                orderBy: 'connected',
                orderType: 'desc',
                like: ''
              }
              self.getDevices(self.newGid, ArrayData)
            }
          } else {
            self.getDevices(self.newGid, oData)
          }
        }
      }
    }
  },
  watch: {
    selectedAccount (data) {
      if (data) this.getDeviceGroups(data.aid)
    },
    selectedGroup (data) {
      if (data) {
        self.newGid = data.gid
        self.resetGetDevice()
      }
    },
    selectedDevice (data) {
      if (data) {
        this.setKVMControl(data.agentid, data.os, data.amtsupport, this.vncMode)
      }
    },
    keyword (val) {
      clearTimeout(self.keywordTimer)
      self.keywordTimer = setTimeout(function () {
        self.resetGetDevice(val)
      }, 1000)
    },
  },
  computed: {
    // languageChange () {
    //   let language = RMMGlobal.currentLanguage().toLowerCase()
    //   return language
    // },
    iAMTPowerOptions () {
      let aActon = []
      switch (this.amtState) {
        case 'on':
          aActon = [
            {
              key: 'PowerDown',
              name: this.$t('deviceon.power.iAMT.amt-power-down')
            },
            {
              key: 'PowerCycle',
              name: this.$t('deviceon.power.iAMT.amt-power-cycle')
            },
            {
              key: 'PowerReset',
              name: this.$t('deviceon.power.iAMT.amt-power-reset')
            }
          ]
          break
        case 'off':
          aActon = [
            {
              key: 'PowerUp',
              name: this.$t('deviceon.power.iAMT.amt-power-up')
            }
          ]
          break
        case 's3':
          aActon = [
            {
              key: 'PowerUp',
              name: this.$t('deviceon.power.iAMT.amt-power-up')
            }
          ]
          break
        case 's4':
          aActon = [
            {
              key: 'PowerUp',
              name: this.$t('deviceon.power.iAMT.amt-power-up')
            }
          ]
          break
        case 'unknown':
          aActon = [
            {
              key: 'PowerUp',
              name: this.$t('deviceon.power.iAMT.amt-power-up')
            },
            {
              key: 'PowerCycle',
              name: this.$t('deviceon.power.iAMT.amt-power-cycle')
            },
            {
              key: 'PowerReset',
              name: this.$t('deviceon.power.iAMT.amt-power-reset')
            }
          ]
          break
      }
      return aActon
    },
    iAMTPowerStatus () {
      let strActon = []
      switch (this.amtState) {
        case 'on':
          strActon = this.$t('deviceon.power.iAMT.amt-on')
          break
        case 'off':
          strActon = this.$t('deviceon.power.iAMT.amt-off')
          break
        case 's3':
          strActon = this.$t('deviceon.power.iAMT.amt-sleep')
          break
        case 's4':
          strActon = this.$t('deviceon.power.iAMT.amt-hibernate')
          break
        case 'unknown':
          strActon = this.$t('deviceon.power.iAMT.amt-unknown')
          break
      }
      return strActon
    }
  }
}
</script>
