<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <schema-table
      ref="table"
      :schema="schema"
    />
    <confirm-dialog
      ref="addDialog"
      title="新增升级"
      @confirm="onDeploy"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label required">升级名称</span>
        <el-input
          v-model.trim="version.name"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
        <span class="c-grid-form__label required">目标版本</span>
        <input
          class="el-input__inner u-pointer u-ellipsis"
          :value="apk"
          placeholder="请选择目标版本"
          readonly
          @click="onChooseApk"
        >
        <span class="c-grid-form__label required">目标设备</span>
        <input
          class="el-input__inner u-pointer u-ellipsis"
          :value="devices"
          placeholder="请选择目标设备"
          readonly
          @click="chooseDevices"
        >
        <span class="c-grid-form__label">升级方式</span>
        <div class="l-flex--row c-grid-form__option">
          <el-radio>强制升级</el-radio>
        </div>
        <span class="c-grid-form__label">描述</span>
        <el-input
          v-model.trim="version.remark"
          type="textarea"
          maxlength="100"
          :rows="3"
          show-word-limit
        />
      </div>
    </confirm-dialog>
    <table-dialog
      ref="apkDialog"
      title="目标版本选择"
      :schema="apkSchema"
      append-to-body
      @choosen="onChoosenApk"
    />
    <el-dialog
      title="目标设备选择"
      :visible.sync="choosingDevice"
      custom-class="c-dialog"
      append-to-body
    >
      <div
        v-if="choosingDevice"
        class="l-flex__auto l-flex"
      >
        <div class="c-tree-sidebar u-overflow-y--auto">
          <el-tree
            ref="tree"
            :data="groups"
            class="c-tree-sidebar__main"
            node-key="path"
            highlight-current
            @node-click="onGroupTreeClick"
          />
        </div>
        <device-tree
          v-if="group"
          class="l-flex__fill u-overflow-y--auto"
          :invoke="getDevices"
          @change="onChooseDevices"
        />
      </div>
      <template #footer>
        <button
          class="o-button"
          @click="onChoosenDevices"
        >
          确定
        </button>
        <button
          class="o-button cancel"
          @click="choosingDevice = false"
        >
          取消
        </button>
      </template>
    </el-dialog>
  </wrapper>
</template>

<script>
import {
  getApks,
  getVersions,
  deployVersion,
  delVersion
} from '@/api/platform'
import { getTopGroups } from '@/api/user'
import { getDevicesByAdmin } from '@/api/device'

export default {
  name: 'UpgradeDeploy',
  data () {
    return {
      version: {},
      apkSchema: {
        condition: { status: 1 },
        list: getApks,
        cols: [
          { prop: 'name', label: '文件名' },
          { prop: 'versionName', label: '版本名称' },
          { prop: 'versionCode', label: '版本号' },
          { prop: 'createTime', label: '创建时间' },
          { prop: 'remark', label: '备注' }
        ]
      },
      apk: '',
      choosingDevice: false,
      devices: '',
      schema: {
        condition: { status: void 0, name: '' },
        list: getVersions,
        buttons: [
          { type: 'add', on: this.onAdd }
        ],
        filters: [
          {
            key: 'status', type: 'select', placeholder: '全部状态',
            options: [
              { value: 1, label: '待升级' },
              { value: 2, label: '已升级' },
              { value: 3, label: '已废弃' }
            ]
          },
          { key: 'name', type: 'search', placeholder: '升级名称' }
        ],
        cols: [
          { prop: 'name', label: '升级名称' },
          { prop: 'fileName', label: '升级文件' },
          { prop: 'versionName', label: '目标版本' },
          { prop: 'deviceName', label: '目标设备' },
          { label: '升级方式', render () { return '强制升级' } },
          { prop: 'createTime', label: '创建时间' },
          { prop: 'remark', label: '备注' },
          { type: 'tag', width: 100, render ({ status }) {
            return {
              type: [null, 'warning', 'success', 'info'][status],
              label: [null, '待升级', '已升级', '已废弃'][status]
            }
          } },
          { type: 'invoke', render: [
            { label: '删除', on: this.onDel }
          ] }
        ]
      },
      groups: [],
      group: null
    }
  },
  methods: {
    onAdd () {
      this.version = {
        name: '',
        fileId: '',
        remark: ''
      }
      this.apk = ''
      this.$devices = []
      this.devices = ''
      this.$refs.addDialog.show()
    },
    onDeploy (done) {
      if (!this.version.name) {
        this.$message({
          type: 'warning',
          message: '请填写升级名称'
        })
        return
      }
      if (!this.version.fileId) {
        this.$message({
          type: 'warning',
          message: '请选择目标版本'
        })
        return
      }
      if (!this.$devices?.length) {
        this.$message({
          type: 'warning',
          message: '请选择目标设备'
        })
        return
      }
      deployVersion({
        deviceId: this.$devices.map(device => device.id),
        ...this.version
      }).then(() => {
        done()
        this.$refs.table.resetCondition({ status: 1, name: this.version.name })
      })
    },
    onChooseApk () {
      this.$refs.apkDialog.show()
    },
    onChoosenApk ({ value: { id, versionName, versionCode }, done }) {
      done()
      this.apk = `${versionName} ${versionCode}`
      this.version.fileId = id
    },
    chooseDevices () {
      this.getTopGroups().then(({ data }) => {
        if (data.length) {
          this.choosingDevice = true
          this.groups = data
          this.group = this.groups[0]
          this.$slectedDevices = []
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.group.path)
          })
        } else {
          this.$message({
            type: 'warning',
            message: '请先添加租户'
          })
        }
      })
    },
    getTopGroups () {
      if (this.groups.length === 0) {
        return getTopGroups()
      }
      return Promise.resolve({ data: this.groups })
    },
    onGroupTreeClick (group) {
      if (!this.group || this.group.id !== group.id) {
        this.group = null
        this.$nextTick(() => {
          this.group = group
        })
      }
    },
    getDevices (params) {
      return getDevicesByAdmin({ tenant: this.group.path, ...params })
    },
    onChooseDevices (devices) {
      this.$slectedDevices = devices
    },
    onChoosenDevices () {
      if (this.$slectedDevices.length) {
        this.$devices = this.$slectedDevices
        this.devices = this.$slectedDevices.map(({ name }) => name).join(', ')
      }
      this.choosingDevice = false
    },
    onDel (version) {
      delVersion(version).then(() => {
        this.$refs.table.decrease(1)
      })
    }
  }
}
</script>
