<template>
  <div class="Screenshot">
    <loading :active.sync="loaderScreenshot" :can-cancel="false" :is-full-page="false"></loading>
    <div class="InnerInfo">
      <div class="row InnerSelect">
        <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>
          <div class="link-group">
            <!--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>
            <!--Save-->
            <span class="btn-svg svg-colorful svg-border" @click="save" v-tooltip.top-center="{ content: $t('deviceon.wizard.save'), trigger: 'hover', offset: 8}">
              <icon iconName="tool-save"/>
            </span>
            <!--Screen Refresh-->
            <span class="btn-svg svg-colorful svg-border" @click="screenRefresh" v-tooltip.top-center="{ content: $t('deviceon.eventAlert.tabs.refresh'), trigger: 'hover', offset: 8}">
              <icon iconName="tool-refresh"/>
            </span>
          </div>
        </div>
      </div>
      <div class="chart-wrapper">
        <div class="panel_wrap" :class="{'smallImg':!ScreensmallBtn }">
          <!--Screen-->
          <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>
          <img ref="screenshot" :src="screenshotURL" v-if="showScreenshot && screenshotURL"/>
          <div class="show-unavailable" v-else>
            <div class="btn-svg svg-show-unavailable">
              <icon iconName="notice-nologin"/>
            </div>
            <div class="title-unavailable">{{'deviceon.device.message.notLogin' | translate}}</div>
            <div class="text-unavailable">{{'deviceon.device.message.checkDevice' | translate}}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import DeviceOnApis from '@/util/DeviceOnApis'
import RMMGlobal from '@/util/RMMGlobal'
import moment from 'moment'
let self

export default {
  name: 'Screenshot',
  data () {
    return {
      showScreenshot: false,
      loaderScreenshot: true,
      ScreenBigHover: false,
      ScreensmallHover: false,
      SaveHover: false,
      ScreenRefreshHover: false,
      screenshotURL: '',
      oRMM: RMMGlobal.get(),
      ScreensmallBtn: false,
      agentId: this.agentid,
      selectedAccount: {},
      selectedGroup: {},
      selectedDevice: {},
      accountOptions: [],
      groupOptions: [],
      deviceOptions: [],
      PanelWrap: '',

      newGid: 0,
      dropNo: 1, // 撈下拉選單第幾頁資料
      totalDevices: 0,
      dropStatus: '', // onloading   finish  nodata
      keyword: '', // string
      keywordTimer: 0,
      isopendropdown: 'close'
    }
  },
  props: {
    did: {
      type: Number,
      default: 0
    },
    gid: {
      type: Number,
      default: 0
    },
    aid: {
      type: Number,
      default: 0
    },
    agentid: {
      type: String,
      dafault: ''
    },
    cancel: {
      type: Boolean
    },
    hidden: {
      type: Boolean
    }
  },
  mounted () {
    self = this
    this.PanelWrap = this.$parent.$el.firstElementChild.firstElementChild.firstElementChild
    this.getAccounts(this.aid)
  },
  methods: {
    getScreenshot (agentid) {
      self.loaderScreenshot = true
      self.showScreenshot = false
      DeviceOnApis.screenshot.get.device(agentid, 'base64')
        .then(function (xhr) {
          self.loaderScreenshot = false
          if (xhr.data.result === false) {
            self.screenshotURL = ''
          }
          if (xhr && xhr.data && xhr.data.result) {
            self.showScreenshot = true
            if (xhr.data.result.login) {
              // self.screenshotURL = self.oRMM.baseUrl.RMM + '/' + xhr.data.result.path + '?_timestamp=' + new Date().getTime()
              self.screenshotURL = 'data:image/png;base64, ' + xhr.data.result.picBase64
            } else {
              self.screenshotURL = ''
            }
          }
        })
        .catch(function (error) {
          self.loaderScreenshot = false
          DeviceOnApis.MessageBox.Error(self, error)
        })
    },
    screenRefresh () {
      this.loaderScreenshot = true
      this.getScreenshot(this.agentid)
    },
    save () {
      this.saveBase64AsFile(self.screenshotURL, 'Screenshot-' + moment().format('YYYY-MM-DD HH_mm_ss') + '.png')
    },
    saveBase64AsFile (base64, fileName) {
      var link = document.createElement('a')
      link.setAttribute('href', base64)
      link.setAttribute('download', fileName)
      link.click()
    },
    ScreenBig () {
      this.PanelWrap.classList.add('changeBig')
      this.ScreensmallBtn = true
    },
    Screensmall () {
      this.PanelWrap.classList.remove('changeBig')
      this.ScreensmallBtn = false
    },
    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.loaderTerminal = false
          DeviceOnApis.MessageBox.Error(self, error)
        })
    },
    getDeviceGroups (aid) {
      this.isLoading = true
      this.showPanel = true
      this.showChart = false
      let oAllGroup = {
        aid: aid,
        description: this.$t('deviceon.device.status.all'),
        gid: 0,
        name: this.$t('deviceon.device.status.all')
      }
      DeviceOnApis.accounts.get
        .deviceGroups(aid)
        .then(function (xhr) {
          if (
            xhr &&
            xhr.data &&
            xhr.data.accounts &&
            xhr.data.accounts[0] &&
            xhr.data.accounts[0].groups
          ) {
            let groups = xhr.data.accounts[0].groups
            if (groups.length > 0) {
              groups = groups.sort(function (a, b) {
                if (a.name < b.name) return -1
                else if (a.name > b.name) return 1
                else return 0
              })
              // 自己的帳戶 和 mentee的創建者帳號 可以看全部
              if (aid === self.oRMM.Login.aid || aid === self.mentorAid) {
                groups.unshift(oAllGroup)
              }
              self.groupOptions = groups
              let aGroup = self.groupOptions.filter(function (g, i) {
                return g.gid === Number(self.gid)
              })
              if ((aGroup.length === 0) && (self.groupOptions.length > 0)) {
                self.selectedGroup = self.groupOptions[0]
              } else {
                if (self.gid !== 0) {
                  for (let i = 0; i < self.groupOptions.length; i++) {
                    if (parseInt(self.gid) === self.groupOptions[i].gid) {
                      self.selectedGroup = self.groupOptions[i]
                      return false
                    }
                  }
                } else {
                  self.selectedGroup = self.groupOptions[0]
                }
              }
            } else {
              self.groupOptions = []
              self.selectedGroup = ''
              self.deviceOptions = []
              self.selectedDevice = ''
            }
          }
          self.isLoading = false
        })
        .catch(function (error) {
          self.isLoading = 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.showScreenshot = true
        if (data.connected) {
          this.getScreenshot(data.agentid)
        } else {
          this.showScreenshot = false
        }
      } else {
        this.showScreenshot = false
      }
    },
    cancel () {
      this.Screensmall()
    },
    keyword (val) {
      clearTimeout(self.keywordTimer)
      self.keywordTimer = setTimeout(function () {
        self.resetGetDevice(val)
      }, 1000)
    },
  }
}
</script>
