<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <platform-page
      class="l-flex__fill"
      @change="onTenantChanged"
    >
      <schema-table
        ref="table"
        :schema="schema"
      />
    </platform-page>
    <confirm-dialog
      ref="editDialog"
      title="日志抓取配置"
      @confirm="onConfirm"
    >
      <div class="c-sibling-item--v c-grid-form u-align-self--center">
        <div class="c-grid-form__row u-font-size--xs u-bold">
          <button
            class="o-button"
            @click="showDocument"
          >
            抓取说明
          </button>
        </div>
        <div class="c-grid-form__row u-font-size--xs u-bold">当前状态：{{ logSetting.activate ? '已下发配置' : '未下发配置' }}</div>
        <span class="c-grid-form__label u-required">抓取时长</span>
        <div class="l-flex--row">
          <el-input-number
            v-model="logSetting.duration"
            :min="60"
            :max="86400"
            step-strictly
          />&nbsp;秒
        </div>
        <span class="c-grid-form__label u-required">抓取指令</span>
        <div
          class="has-info"
          data-info="多条指令以分号分隔"
        >
          <el-input
            v-model="logSetting.commands"
            type="textarea"
            :rows="5"
          />
        </div>
        <span class="c-grid-form__label u-required">是否重启</span>
        <el-switch
          v-model="logSetting.reboot"
          class="c-grid-form__option"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </div>
      <template #footer="{ confirm, cancel }">
        <button
          class="c-sibling-item o-button"
          @click="confirm"
        >
          开启抓取
        </button>
        <button
          class="c-sibling-item o-button o-button--cancel"
          @click="cancel"
        >
          取消
        </button>
      </template>
    </confirm-dialog>
    <table-dialog
      ref="resultDialog"
      size="lg"
      title="抓取结果"
      :schema="resultSchema"
    />
    <table-dialog
      ref="heartbeatDialog"
      size="lg fixed"
      title="心跳记录"
      :schema="heartbeatSchema"
      @hook:beforeDestroy="closeTimer"
    />
  </wrapper>
</template>

<script>
import { parseTime } from '@/utils'
import { getAssetUrl } from '@/api/asset'
import { getDevicesByTenant } from '@/api/device'
import {
  getRemoteLogConfig,
  startRemoteLog,
  stopRemoteLog,
  getRemoteLogs,
  getHeartbeats,
  getDownloadUrl
} from './api'

const defaultLogSettingForm = {
  activate: false,
  duration: 60,
  commands: 'logcat -vtime | grep -i -E "MqttClient|PushCallback|MqttService"',
  reboot: false
}

export default {
  name: 'DeviceLog',
  data () {
    return {
      logSetting: {},
      schema: {
        list: this.getDevicesByTenant,
        buttons: [
          { label: '心跳记录', on: this.onHeartbeats }
        ],
        filters: [
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        cols: [
          { type: 'refresh' },
          { prop: 'name', label: '设备名称' },
          { prop: 'serialNumber', label: '序列号' },
          { prop: 'mac', label: 'MAC' },
          { type: 'tag', render: ({ activate, onlineStatus }) => activate
            ? onlineStatus === 0
              ? { type: 'primary', label: '待接入' }
              : onlineStatus === 1
                ? { type: 'success', label: '在线' }
                : { type: 'danger', label: '离线' }
            : { type: 'warning', label: '未激活' } },
          { type: 'invoke', render: [
            { label: '开始抓取', on: this.onStart },
            { label: '停止抓取', on: this.onStop },
            { label: '抓取结果', on: this.onResult },
            { label: '心跳记录', on: this.onHeartbeat }
          ], width: 300 }
        ]
      },
      heartbeatSchema: {
        nonPagination: true,
        list: this.getheartbeatData,
        filters: [
          { key: 'name', type: 'search', placeholder: '设备名称' }
        ],
        cols: [
          { type: 'refresh' },
          { prop: 'name', label: '设备名称', sortable: true },
          { prop: 'sn', label: '序列号', sortable: true },
          { prop: 'mac', label: 'MAC', width: 140 },
          { prop: 'ip', label: 'ip', width: 140 },
          { prop: 'settingId', label: '当前事件' },
          { label: '上报时间', render: ({ timestamp }) => parseTime(timestamp), sortable: true, sortBy: 'timestamp', width: 160 }
        ]
      },
      curDeviceId: null
    }
  },
  computed: {
    resultSchema () {
      return {
        list: getRemoteLogs,
        condition: { deviceId: this.curDeviceId },
        cols: [
          { type: 'refresh' },
          { prop: 'settingId', label: '事件' },
          { label: '执行状态', type: 'tag', render: ({ status }) => {
            return {
              type: status ? 'success' : 'danger',
              label: status ? '成功' : '失败'
            }
          } },
          { prop: 'message', label: '备注' },
          { prop: 'commandArrayString', label: '抓取命令数组' },
          { prop: 'releaseTime', label: '命令发布时间', width: 180 },
          { prop: 'createTime', label: '上传时间', width: 180 },
          { type: 'invoke', render: [
            { label: '下载日志', allow: ({ status }) => status, on: this.onDownload }
          ] }
        ]
      }
    }
  },
  beforeDestroy () {
    this.closeTimer()
  },
  methods: {
    closeTimer () {
      clearTimeout(this.$timer)
      this.$timer = null
    },
    onTenantChanged (tenant) {
      this.$tenant = tenant
      this.$refs.table?.pageTo(1)
    },
    getDevicesByTenant (params) {
      if (!this.$tenant) {
        return Promise.resolve({ data: [] })
      }
      return getDevicesByTenant(this.$tenant.path, params)
    },
    onStop () {
      stopRemoteLog({
        duration: 60,
        deviceId: this.curDeviceId,
        activate: false
      })
    },
    onStart (device) {
      getRemoteLogConfig(device.id).then(({ data }) => {
        if (data) {
          const { activate, duration, commands, reboot } = data
          this.logSetting = {
            activate,
            duration,
            commands: commands ? commands.join(';') : [],
            reboot
          }
        } else {
          this.logSetting = { ...defaultLogSettingForm }
        }
        this.curDeviceId = device.id
        this.$refs.editDialog.show()
      })
    },
    async onConfirm (done) {
      const { duration, commands, reboot } = this.logSetting
      if (~commands.indexOf('；')) {
        this.$message({
          type: 'warning',
          message: '请使用英文输入下的【;】符号'
        })
        return
      }

      await startRemoteLog({
        deviceId: this.curDeviceId,
        duration,
        activate: true,
        commands: commands.split(';'),
        reboot
      })
      done()
    },
    onResult (device) {
      this.$deviceName = device.name
      this.curDeviceId = device.id
      this.$refs.resultDialog.show()
    },
    getheartbeatData () {
      this.closeTimer()
      return getHeartbeats(this.$mac).then(({ data }) => {
        this.$timer = setTimeout(() => {
          this.$refs?.heartbeatDialog.getTable()?.onPagination()
        }, 5 * 1000)
        if (!data) {
          return { data: [] }
        }

        if (Array.isArray(data)) {
          if (this.$refs?.heartbeatDialog.getTable()?.options.params.name?.length) {
            return { data: data.filter(i => i).map(i => JSON.parse(i))
              .filter(i => new RegExp(this.$refs.heartbeatDialog.getTable().options.params.name).test(i.name)) }
          }
          return { data: data.filter(i => i).map(i => JSON.parse(i)) }
        }
        data = JSON.parse(data)
        if (this.$mac) {
          const timestamp = data.timestamp
          data.name = this.$deviceName
          this.$heartBeatData = this.$heartBeatData || []
          if (!(this.$heartBeatData.length && this.$heartBeatData[0].timestamp === timestamp)) {
            this.$heartBeatData.unshift(data)
          }

          return { data: this.$heartBeatData }
        }
        return { data }
      })
    },
    onHeartbeats () {
      this.$heartBeatData = []
      this.$mac = null
      this.heartbeatSchema.filters = [
        { key: 'name', type: 'search', placeholder: '设备名称' }
      ]
      this.$refs.heartbeatDialog.show()
    },
    onHeartbeat (device) {
      this.$heartBeatData = []
      this.$deviceName = device.name
      this.$mac = device.mac
      this.heartbeatSchema.filters = null
      this.$refs.heartbeatDialog.show()
    },
    showDocument () {
      window.open('https://inspur-rd.feishu.cn/docx/M4oIdhmU1oFyvAxErn3cYv6Cnuf', '_blank')
    },
    onDownload ({ recordId, createTime }) {
      getDownloadUrl(recordId).then(
        ({ data: url }) => {
          const a = document.createElement('a')
          a.style.display = 'none'
          a.setAttribute('target', '_blank')
          a.setAttribute('download', `${this.$deviceName}-${createTime}日志`)
          a.href = getAssetUrl(url)
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      )
    }
  }
}
</script>
