<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"
            controls-position="right"
            :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--info"
          @click="cancel"
        >
          取消
        </button>
      </template>
    </confirm-dialog>
    <table-dialog
      ref="resultDialog"
      size="lg"
      title="抓取结果"
      :schema="resultSchema"
    />
    <table-dialog
      ref="heartbeatDialog"
      size="lg fixed"
      :title="title"
      :schema="heartbeatSchema"
    />
  </wrapper>
</template>

<script>
import { parseTime } from '@/utils'
import { getAssetUrl } from '@/api/asset'
import { getDevicesByTenant } from '@/api/device'
import {
  getRemoteLogConfig,
  startRemoteLog,
  stopRemoteLog,
  getRemoteLogs,
  getHeartbeats
} 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: {
        autoRefreshEachPage: true,
        props: {
          size: 'small'
        },
        list: this.getDevicesByTenant,
        buttons: [
          { label: '未入库设备心跳记录', on: this.onHeartbeats }
        ],
        filters: [
          { key: 'serialNumber', type: 'search', placeholder: '序列号' },
          { key: 'mac', type: 'search', placeholder: 'MAC' },
          { key: 'name', type: 'search', placeholder: '名称' },
          { type: 'refresh' }
        ],
        cols: [
          { prop: 'name', label: '名称', 'min-width': 120 },
          { prop: 'serialNumber', label: '序列号', 'min-width': 80 },
          { prop: 'mac', label: 'MAC', 'min-width': 80 },
          { prop: 'remark', label: '型号', width: 100 },
          { type: 'tag', render: ({ activate, onlineStatus }) => activate
            ? onlineStatus === 0
              ? { type: 'primary', label: '待接入' }
              : onlineStatus === 1
                ? { type: 'success', label: '在线' }
                : { type: 'danger', label: '离线' }
            : { type: 'warning', label: '未激活' }, 'size': 'sm', width: 80 },
          { type: 'invoke', render: [
            { label: '开始抓取', on: this.onStart },
            { label: '停止抓取', on: this.onStop },
            { label: '抓取结果', on: this.onResult },
            { label: '心跳记录', on: this.onHeartbeat }
          ], width: 300 }
        ]
      },
      curDeviceId: null,
      currDeviceTenant: null,
      title: '',
      sn: ''
    }
  },
  computed: {
    heartbeatSchema () {
      return {
        nonPagination: true,
        autoRefresh: true,
        list: this.getheartbeatData,
        condition: { sn: this.sn },
        filters: this.sn
          ? null
          : [
            { key: 'sn', type: 'search', placeholder: '序列号' },
            { type: 'refresh' }
          ],
        cols: this.sn
          ? [
            { prop: 'sn', label: '序列号' },
            { prop: 'mac', label: 'MAC', width: 160 },
            { prop: 'ip', label: 'ip', width: 140 },
            { prop: 'settingId', label: '当前事件' },
            { label: '上报时间', render: ({ timestamp }) => parseTime(timestamp), width: 180 }
          ]
          : [
            { prop: 'sn', label: '序列号' },
            { prop: 'mac', label: 'MAC', width: 200 },
            { prop: 'ip', label: 'ip', width: 180 },
            { label: '上报时间', render: ({ timestamp }) => parseTime(timestamp), width: 180 }
          ]
      }
    },
    resultSchema () {
      return {
        list: getRemoteLogs,
        autoRefresh: true,
        condition: { tenant: this.currDeviceTenant, deviceId: this.curDeviceId },
        cols: [
          { prop: 'settingId', label: '事件' },
          { label: '执行状态', type: 'tag', render: ({ status }) => {
            return {
              type: ['warning', 'success', 'danger', 'primary'][status],
              label: ['抓取中', '成功', '失败', '取消'][status]
            }
          } },
          { prop: 'message', label: '备注' },
          { prop: 'createTime', label: '抓取开始时间', width: 180, align: 'center' },
          { prop: 'commandArrayString', label: '抓取命令数组' },
          { prop: 'duration', label: '抓取时长(s)', width: 100, align: 'center' },
          { type: 'invoke', render: [
            { label: '下载日志', allow: ({ status }) => status === 1, on: this.onDownload }
          ] }
        ]
      }
    }
  },
  methods: {
    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)
    },
    getheartbeatData (params) {
      if (this.sn) {
        return getHeartbeats(params, this.sn).then(({ data }) => {
          if (data.length && data[0].timestamp !== this.$heartbeats[0]?.timestamp) {
            this.$heartbeats.unshift(data[0])
          }
          return { data: this.$heartbeats }
        })
      }
      return getHeartbeats(params)
    },
    onHeartbeats () {
      this.title = '未入库设备心跳记录'
      this.sn = ''
      this.$refs.heartbeatDialog.show()
    },
    onHeartbeat ({ name, serialNumber }) {
      this.title = `${name}心跳记录`
      this.sn = serialNumber
      this.$heartbeats = []
      this.$refs.heartbeatDialog.show()
    },
    onStop ({ tenant, id }) {
      stopRemoteLog({
        tenant,
        deviceId: id,
        duration: 60,
        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.currDeviceTenant = device.tenant
        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({
        tenant: this.currDeviceTenant,
        deviceId: this.curDeviceId,
        duration,
        activate: true,
        commands: commands.split(';'),
        reboot
      })
      done()
    },
    onResult (device) {
      this.$deviceName = device.name
      this.currDeviceTenant = device.tenant
      this.curDeviceId = device.id
      this.$refs.resultDialog.show()
    },
    showDocument () {
      window.open('https://inspur-rd.feishu.cn/docx/M4oIdhmU1oFyvAxErn3cYv6Cnuf', '_blank')
    },
    onDownload ({ fileName, createTime, duration }) {
      const a = document.createElement('a')
      a.style.display = 'none'
      a.setAttribute('target', '_blank')
      a.setAttribute('download', `${this.$deviceName}-${createTime}-${duration}s日志.zip`)
      a.href = getAssetUrl(fileName)
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
  }
}
</script>
