<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <c-table
      :curr="options"
      @pagination="getList"
    >
      <template #header>
        <div class="l-flex__auto c-sibling-item">
          <button
            class="o-button"
            @click="toAdd"
          >
            <i class="o-button__icon el-icon-circle-plus-outline" />
            新增
          </button>
        </div>
        <el-select
          v-model="options.params.status"
          class="l-flex__none c-sibling-item"
          placeholder="请选择状态"
          @change="search"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <search-input
          v-model.trim="options.params.name"
          class="l-flex__none c-sibling-item"
          placeholder="文件名"
          @search="search"
        />
        <button
          class="l-flex__none c-sibling-item o-button"
          @click="search"
        >
          搜索
        </button>
      </template>
      <el-table-column
        prop="name"
        label="文件名"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="versionName"
        label="版本名称"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="versionCode"
        label="版本号"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="md5"
        label="MD5"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="size"
        label="文件大小"
        align="center"
        width="100"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="remark"
        label="描述"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="状态"
        align="center"
        width="100"
      >
        <template v-slot="scope">
          <el-tag
            v-if="scope.row.status"
            class="o-tag u-pointer"
            type="success"
            size="medium"
            @click.stop="deactive(scope.row)"
          >
            启用
          </el-tag>
          <el-tag
            v-else
            class="o-tag u-pointer"
            type="danger"
            size="medium"
            @click.stop="active(scope.row)"
          >
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120"
      >
        <template v-slot="scope">
          <div
            v-if="scope.row.status"
            class="c-table__btn u-pointer"
            @click="deactive(scope.row)"
          >
            禁用
          </div>
          <div
            v-else
            class="c-table__btn u-pointer"
            @click="active(scope.row)"
          >
            启用
          </div>
          <div
            class="c-table__btn u-pointer"
            @click="del(scope.row)"
          >
            删除
          </div>
        </template>
      </el-table-column>
    </c-table>
    <el-dialog
      title="新增升级文件"
      :visible.sync="show"
      custom-class="c-dialog"
      :close-on-click-modal="false"
      :before-close="close"
    >
      <div class="c-form large">
        <div class="c-form__section fill">
          <el-upload
            ref="upload"
            class="o-upload u-pointer"
            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>
        <div class="c-form__section">
          <span class="c-form__label required">文件名：</span>
          <el-input
            v-model.trim="apk.name"
            class="c-form__item"
            maxlength="100"
            show-word-limit
          />
        </div>
        <div class="c-form__section extra o-version-name">
          <span class="c-form__label required">版本名称：</span>
          <el-input
            v-model.trim="apk.versionName"
            class="c-form__item"
            :disabled="!manual"
            maxlength="50"
            show-word-limit
          />
        </div>
        <div class="c-form__section extra o-version-code">
          <span class="c-form__label">版本号：</span>
          <el-input-number
            v-model="apk.versionCode"
            class="c-form__item"
            :disabled="!manual"
            :min="1"
            :max="99999999999999"
            step-strictly
          />
        </div>
        <div class="c-form__section">
          <span class="c-form__label">描述：</span>
          <el-input
            v-model="apk.remark"
            class="c-form__item"
            type="textarea"
            maxlength="100"
            show-word-limit
          />
        </div>
        <div class="c-form__section">
          <span class="c-form__label">状态：</span>
          <div class="c-form__item">
            <el-radio
              v-model="apk.status"
              :label="1"
            >
              启用
            </el-radio>
            <el-radio
              v-model="apk.status"
              :label="0"
            >
              禁用
            </el-radio>
          </div>
        </div>
      </div>
      <template #footer>
        <button
          class="o-button"
          @click="toSave"
        >
          确定
        </button>
        <button
          class="o-button cancel"
          @click="close"
        >
          取消
        </button>
      </template>
    </el-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/upgrade'
import {
  createListOptions,
  parseByte
} from '@/utils'
import AppInfoParse from 'app-info-parser'

export default {
  name: 'UpgradeApk',
  data () {
    return {
      statusOptions: [
        { value: void 0, label: '全部状态' },
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' }
      ],
      options: createListOptions({
        status: void 0,
        name: ''
      }),
      show: false,
      apk: {},
      manual: false,
      showProgress: false,
      progress: 0
    }
  },
  created () {
    this.getList()
  },
  methods: {
    search () {
      const options = this.options
      options.list = []
      options.totalCount = 0
      options.params.pageNum = 1
      this.getList()
    },
    transform (apk) {
      apk.size = parseByte(apk.size)
      return apk
    },
    getList () {
      const options = this.options
      options.error = false
      options.loading = true
      getApks(options.params).then(({ data, totalCount }) => {
        options.list = data.map(this.transform)
        options.totalCount = totalCount
      }, () => {
        options.error = true
        options.list = []
      }).finally(() => {
        options.loading = false
      })
    },
    toAdd () {
      this.apk = {
        file: null,
        name: '',
        versionName: '',
        versionCode: 1,
        remark: '',
        status: 1
      }
      this.manual = false
      this.show = true
    },
    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版本失败，请手动填写'
        })
      })
    },
    toSave () {
      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(() => {
        this.close()
        const params = this.options.params
        if (params.status !== void 0 && params.status !== status) {
          params.status = void 0
        }
        if (params.name && !(new RegExp(params.name).test(name))) {
          params.name = ''
        }
        this.search()
      })
    },
    close () {
      this.show = false
    },
    active (apk) {
      enableApk(apk).then(() => {
        apk.status = 1
      })
    },
    deactive (apk) {
      disableApk(apk).then(() => {
        apk.status = 0
      })
    },
    del (apk) {
      delApk(apk).then(() => {
        if (this.options.list.length === 1 && this.options.params.pageNum > 1) {
          this.options.params.pageNum -= 1
        }
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.o-version-name::after {
  content: "例：1.0.0";
}

.o-version-code::after {
  content: "只能由小往大升";
}
</style>
