<template>
  <section class="AppNativeAppVersion">
    <ai-list>
      <ai-title slot="title" title="App版本管理" isShowBottomBorder/>
      <template #content>
        <ai-search-bar>
          <template #left>
            <el-select size="small" v-model="search.type" clearable @change="page.current=1,searchList()"
                       placeholder="请选择系统">
              <el-option
                  v-for="item in system"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </template>
          <template #right>
            <el-input size="small" v-model.trim="search.versionName" placeholder="版本号/版本名称" clearable
                      @keyup.enter.native="page.current=1,searchList()" prefix-icon="iconfont iconSearch"/>
          </template>
        </ai-search-bar>
        <ai-search-bar>
          <template #left>
            <el-button
                size="small"
                type="primary"
                icon="iconfont iconAdd"
                @click="toAdd()">添加
            </el-button>
          </template>
        </ai-search-bar>
        <el-table
            :data="list"
            v-loading="loading"
            header-cell-class-name="table-header"
            tooltip-effect="light"
            row-class-name="table-row"
            cell-class-name="table-cell"
            @selection-change="v=>this.selectAccounts=v"
            max-height="calc(100% - 200px)">
          <el-table-column
              v-for="(item,i) in recordCols"
              :key="i" :prop="item.prop"
              show-overflow-tooltip
              :label="item.label"
              :align="item.align"
              :width="item.width">
            <div class="nowarp-text" slot-scope="{row}">
              {{ row[item.prop] || "-" }}
            </div>
          </el-table-column>
          <el-table-column align="center" label="系统" :width="120">
            <template slot-scope="{row}">
              <span v-if="row.type === '0'">苹果</span>
              <span v-else>安卓</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否强制更新" :width="120">
            <template slot-scope="{row}">
              <span v-if="row.type === '0'">{{ row.isForceUpdate === '0' ? '否' : '是' }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="下载二维码">
            <div slot-scope="{row}">
              <img @click="showQRcode(row.qrCodeUrl)" title="预览" style="margin: 10px 0;width: 80px;cursor: pointer;"
                   :src="row.qrCodeUrl">
            </div>
          </el-table-column>
          <el-table-column align="center" prop="createTime" label="上传时间">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="{row}">
              <el-button
                  v-if="row.type === '0'"
                  class="account-list-operation icon-color89B"
                  type="text"
                  icon="iconfont iconDownload"
                  title="下载"
                  @click="download(row)"
              ></el-button>
              <el-button
                  v-if="$permissions('admin_sysuser_del')"
                  class="account-list-operation icon-color89B"
                  type="text"
                  icon="iconfont iconDelete"
                  title="删除"
                  @click="remove(row.id)">
              </el-button>
            </template>
          </el-table-column>
          <div slot="empty" class="no-data"></div>
        </el-table>
        <div class="pagination">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.current"
              background :page-size="page.pageSize"
              :page-sizes="[10, 20, 50, 100,200]"
              layout="total,prev, pager, next,sizes, jumper"
              :total="total">
          </el-pagination>
        </div>
      </template>
    </ai-list>
    <el-dialog
        title="新增版本"
        :close-on-click-modal="false"
        class="editStyle"
        :visible.sync="dialog.add.visible"
        width="600px"
        @close="closeAdd">
      <el-form ref="addVersionForm" :model="dialog.add" :rules="rules.add" size="small" label-width="120px">
        <el-form-item required label="系统" prop="type">
          <el-select style="width: 240px" v-model="dialog.add.type" placeholder="请选择" @change="onSystemChange">
            <el-option
                v-for="item in system"
                v-show="item.label !== '全部'"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="版本号" prop="versionCode">
          <el-input style="width: 240px" v-model.trim="dialog.add.versionCode" placeholder="请输入..."
                    clearable></el-input>
        </el-form-item>
        <el-form-item required label="版本名称" prop="versionName">
          <el-input style="width: 240px" v-model.trim="dialog.add.versionName" placeholder="请输入..."
                    clearable></el-input>
        </el-form-item>
        <el-form-item required label="更新日志" prop="updateLog">
          <el-input style="width: 240px" type="textarea" :rows="3" v-model="dialog.add.updateLog" placeholder="请输入..."
                    clearable></el-input>
        </el-form-item>
        <el-form-item :required="dialog.add.type === '0'" v-if="dialog.add.type === '0'" label="是否强制更新"
                      prop="isForceUpdate">
          <el-switch
              v-model="dialog.add.isForceUpdate" active-value="1" inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item :required="dialog.add.type === '0'" v-if="dialog.add.type === '0'" label="appstore 地址"
                      prop="downloadUrl">
          <el-input style="width: 240px" v-model.trim="dialog.add.downloadUrl" placeholder="请输入..." clearable>
          </el-input>
        </el-form-item>
        <el-form-item :required="dialog.add.type === '1'" v-if="dialog.add.type === '1'" label="上传APK"
                      prop="downloadUrl">
          <el-upload
              class="upload-demo"
              width="240px"
              action
              :multiple="false"
              accept=".apk"
              :limit="1"
              :file-list="fileList"
              :on-success="onSuccess"
              :on-error="onError"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :http-request="uploadFile">
            <el-button size="small" icon="el-icon-upload" type="primary">点击上传</el-button>
            <div class="el-upload__tip" slot="tip">只能上传APK文件</div>
          </el-upload>
          <!--<el-upload
            class="upload-demo"
            width="240px"
            :multiple="false"
            accept="file"
            :limit="1"
            :file-list="fileList"
            :headers="headers"
            :on-success="onSuccess"
            :on-error="onError"
            :before-upload="onBeforeUpload"
            action="/lan/admin/file/add-apk">
            <el-button size="small" icon="el-icon-upload" type="primary">点击上传</el-button>
            <div class="el-upload__tip" slot="tip">只能上传APK文件</div>
          </el-upload>-->
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button style="width:92px" size="small" @click="dialog.add.visible=false">取消</el-button>
        <el-button style="width:92px" size="small" type="primary" @click="addVersion">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="下载二维码"
        :visible.sync="isShowQRcode"
        width="30%"
        center
        :before-close="handleClose">
      <div style="text-align: center;">
        <img :src="qrcode">
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  name: "AppNativeAppVersion",
  label: "App版本管理",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  data() {
    return {
      list: [],
      loading: true,
      headers: {},
      isShowQRcode: false,
      qrcode: '',
      search: {
        versionCode: '',
        type: ''
      },
      system: [
        {
          value: '0',
          label: '苹果'
        },
        {
          value: '1',
          label: '安卓'
        }
      ],
      recordCols: [
        {label: '版本号', prop: 'versionCode', align: 'center', width: 100},
        {label: '版本名称', prop: 'versionName', align: 'center', width: 100},
        {label: '更新日志', prop: 'updateLog', align: 'center'}
      ],
      page: {
        current: 1,
        size: 10
      },
      total: 0,
      rules: {
        add: {
          versionCode: [{required: true, message: '请填写版本号'}],
          versionName: [{required: true, message: '请填写版本名称'}],
          updateLog: [{required: true, message: '请填写更新日志'}],
          isForceUpdate: [{required: true, message: '请选择是否强制更新'}],
          downloadUrl: [{required: true, message: '请上传apk文件'}]
        }
      },
      unitObj: {},
      dialog: {
        add: {
          versionCode: '',
          versionName: '',
          updateLog: '',
          isForceUpdate: '0',
          downloadUrl: '',
          qrCodeUrl: '',
          visible: false,
          type: '0'
        }
      },
      fileList: []
    }
  },

  mounted() {
    this.headers = {
      Authorization: JSON.parse(localStorage.getItem('vuex')).user.token
    }
    this.getVersionList()
  },
  methods: {
    // 上传APK
    uploadFile: function (file) {
      let formData = new FormData();
      formData.append("file", file.file);
      this.instance.post(`/admin/file/add-apk`, formData).then(res => {
        if (res.code == 0) {
          this.dialog.add.downloadUrl = res.data.split(';').shift()
          // let apkUrl = res.data.split(';');
          // this.fileList = [];
          // this.fileList.push({id: apkUrl[1], url: apkUrl[0]});
        }
      });

    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    // 查询
    searchList() {
      this.page.current = 1

      this.$nextTick(() => {
        this.getVersionList()
      })
    },

    // 重置查询条件
    resetConditon() {
      this.search.versionCode = ''
      this.search.type = ''
      this.page.current = 1
      this.getVersionList()
    },

    // 获取历史版本列表
    getVersionList() {
      this.loading = true
      this.instance.post('/admin/sysversion/list', null, {
        params: {
          ...this.page,
          ...this.search
        }
      }).then(({data}) => {
        this.list = data.records
        this.total = data.total

        this.$nextTick(() => {
          this.loading = false
        })
      })
    },

    // 关闭图片预览回调
    handleClose() {
      this.isShowQRcode = false
      this.qrcode = ''
    },

    // 图片预览
    showQRcode(src) {
      this.qrcode = src

      this.$nextTick(() => {
        this.isShowQRcode = true
      })
    },

    // 分页change
    handleCurrentChange(val) {
      this.page.current = val;
      this.getVersionList();
    },

    // 分页页数change
    handleSizeChange(val) {
      this.page.size = val;
      this.getVersionList();
    },

    // 下载apk
    download(row) {
      var a = document.createElement('a')
      a.setAttribute('download', '')
      a.href = row.downloadUrl.split(';')[0]
      a.click()
    },

    // 删除版本
    remove(id) {
      this.$confirm('确认删除该版本吗？').then(() => {
        this.instance.post('/admin/sysversion/delete', null, {
          params: {
            ids: id
          }
        }).then(res => {
          if (res.code === 0) {
            this.getVersionList()
            this.$message.success('删除成功')
          }
        })
      }).catch(() => {
      })
    },
    // apk文件校验
    onBeforeUpload(file) {
      const type = file.name && file.name.split('.')[1]

      if (type === 'apk') {
        return true
      }

      this.$message('请上传apk文件')
      return false
    },

    // 文件上传成功回调
    onSuccess(res) {
      if (res.code === 0) {
        this.dialog.add.downloadUrl = res.data
      } else {
        this.$message.error(res.msg)
      }
    },

    // 文件上传失败回调
    onError() {
      this.$message.error('上传失败')
    },

    // 新增版本表单充值
    closeAdd() {
      this.dialog.add.versionCode = ''
      this.dialog.add.versionName = ''
      this.dialog.add.updateLog = ''
      this.dialog.add.isForceUpdate = '0'
      this.dialog.add.downloadUrl = ''
      this.dialog.add.qrCodeUrl = ''
      this.dialog.add.visible = false
      this.dialog.add.type = '0'
      this.fileList = []
    },

    // 添加版本
    toAdd() {
      this.dialog.add.visible = true;
      this.$nextTick(() => {
        this.$refs.addVersionForm.resetFields()
      })
    },

    // 添加版本
    addVersion() {
      this.page.pageNum = 1;
      this.$refs.addVersionForm.validate(v => {
        if (v) {
          this.instance.post('/admin/sysversion/addOrUpdate', this.dialog.add).then(() => {
            this.dialog.add.visible = false
            this.getVersionList()
            this.$message.success('添加成功!')
          })
        }
      })
    },

    // 重置表单校验
    onSystemChange() {
      this.$refs.addVersionForm.clearValidate()
    }
  }
}
</script>

<style lang="scss" scoped>
.AppNativeAppVersion {
  height: 100%;
}
</style>
