<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <schema-table
      ref="table"
      :schema="schema"
    />
    <confirm-dialog
      ref="addDialog"
      title="新增升级文件"
      @confirm="onSave"
    >
      <el-upload
        ref="upload"
        class="o-upload has-bottom-padding"
        action="none"
        accept=".apk"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="onChange"
        drag
      >
        <div class="l-flex--row">
          <i class="o-upload__icon el-icon-upload" />
          <template v-if="apk.file">
            <div class="o-upload__file">{{ apk.file.name }}</div>
          </template>
          <template v-else>
            拖拽文件到此或
            <span class="o-upload__tip">点击选择文件</span>
          </template>
        </div>
      </el-upload>
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label required">文件名：</span>
        <el-input
          v-model.trim="apk.name"
          placeholder="最多100个字符"
          maxlength="100"
          clearable
        />
        <span class="c-grid-form__label required">版本名称：</span>
        <div
          class="c-grid-form__info"
          data-info="例：1.0.0"
        >
          <el-input
            v-model.trim="apk.versionName"
            :disabled="!manual"
            placeholder="最多50个字符"
            maxlength="50"
            clearable
          />
        </div>
        <span class="c-grid-form__label">版本号：</span>
        <div
          class="c-grid-form__info"
          data-info="只能由小往大升"
        >
          <el-input-number
            v-model="apk.versionCode"
            :disabled="!manual"
            :min="1"
            :max="99999999999999"
            step-strictly
          />
        </div>
        <span class="c-grid-form__label">备注：</span>
        <el-input
          v-model.trim="apk.remark"
          type="textarea"
          maxlength="100"
          show-word-limit
        />
        <span class="c-grid-form__label">状态：</span>
        <div class="l-flex--row c-grid-form__option">
          <el-radio
            v-model="apk.status"
            :label="1"
          >
            启用
          </el-radio>
          <el-radio
            v-model="apk.status"
            :label="0"
          >
            禁用
          </el-radio>
        </div>
      </div>
    </confirm-dialog>
    <el-dialog
      class="c-progress"
      :visible.sync="showProgress"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-progress
        :percentage="progress"
        :stroke-width="24"
        text-inside
        status="success"
      />
    </el-dialog>
  </wrapper>
</template>

<script>
import {
  getApks,
  addApk,
  enableApk,
  disableApk,
  delApk
} from '@/api/platform'
import { parseByte } from '@/utils'
import AppInfoParse from 'app-info-parser'

export default {
  name: 'UpgradeApk',
  data () {
    return {
      apk: {},
      manual: false,
      showProgress: false,
      progress: 0,
      schema: {
        condition: { status: void 0, name: '' },
        list: getApks,
        buttons: [
          { type: 'add', on: this.onAdd }
        ],
        filters: [
          {
            key: 'status', type: 'select', placeholder: '全部状态',
            options: [
              { value: 1, label: '启用' },
              { value: 0, label: '禁用' }
            ]
          },
          { key: 'name', type: 'search', placeholder: '文件名' }
        ],
        cols: [
          { prop: 'name', label: '文件名' },
          { prop: 'versionName', label: '版本名称' },
          { prop: 'versionCode', label: '版本号' },
          { prop: 'md5', label: 'MD5' },
          { label: '文件大小', render ({ size }) {
            return parseByte(size)
          } },
          { prop: 'remark', label: '备注' },
          { type: 'tag', width: 100, render ({ status }) {
            return {
              type: status ? 'success' : 'danger',
              label: status ? '启用' : '禁用'
            }
          }, on: this.onTagClick },
          { type: 'invoke', render: [
            { label: '禁用', render ({ status }) { return status === 1 }, on: this.onDeactive },
            { label: '启用', render ({ status }) { return status === 0 }, on: this.onActive },
            { label: '删除', on: this.onDel }
          ] }
        ]
      }
    }
  },
  methods: {
    onAdd () {
      this.apk = {
        file: null,
        name: '',
        versionName: '',
        versionCode: 1,
        remark: '',
        status: 1
      }
      this.manual = false
      this.$refs.addDialog.show()
    },
    onChange ({ raw }) {
      this.$refs.upload.clearFiles()
      this.apk.file = raw
      this.apk.name = raw.name
      const loading = this.$showLoading()
      new AppInfoParse(raw).parse()
        .finally(() => {
          this.$closeLoading(loading)
        })
        .then(
          ({ versionName, versionCode }) => {
            this.manual = false
            this.apk.versionName = versionName
            this.apk.versionCode = versionCode
          },
          () => {
            this.manual = true
            this.$message({
              type: 'warning',
              message: '解析APK版本失败，请手动填写'
            })
          }
        )
    },
    onSave (done) {
      if (!this.apk.file) {
        this.$message({
          type: 'warning',
          message: '请选择升级APK'
        })
        return
      }
      if (!this.apk.name) {
        this.$message({
          type: 'warning',
          message: '请填写文件名'
        })
        return
      }
      if (this.apk.name.length > 100) {
        this.$message({
          type: 'warning',
          message: '文件名过长'
        })
        return
      }
      if (this.manual) {
        if (!this.apk.versionName) {
          this.$message({
            type: 'warning',
            message: '请填写版本名称'
          })
          return
        }
        if (!/^\d+(\.\d+)*$/.test(this.apk.versionName)) {
          this.$message({
            type: 'warning',
            message: '版本名称格式不正确，例 1.0.0'
          })
          return
        }
      }
      const formData = new FormData()
      const { file, name, versionName, versionCode, remark, status } = this.apk
      formData.append('file', file)
      formData.append('name', name)
      formData.append('versionName', versionName)
      formData.append('versionCode', versionCode)
      formData.append('remark', remark)
      formData.append('status', status)
      this.progress = 0
      this.showProgress = true
      addApk(formData, ({ loaded, total }) => {
        this.progress = Math.min(99, loaded * 100 / total | 0)
      }).finally(() => {
        this.progress = 100
        this.showProgress = false
      }).then(() => {
        done()
        this.$refs.table.resetCondition({ name, status })
      })
    },
    onTagClick (data) {
      switch (data.status) {
        case 0:
          this.onActive(data)
          break
        case 1:
          this.onDeactive(data)
          break
        default:
          break
      }
    },
    onActive (apk) {
      enableApk(apk).then(() => {
        apk.status = 1
      })
    },
    onDeactive (apk) {
      disableApk(apk).then(() => {
        apk.status = 0
      })
    },
    onDel (apk) {
      delApk(apk).then(() => {
        this.$refs.table.decrease(1)
      })
    }
  }
}
</script>
