<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="640px"
    @close="handleClose">
    <el-form
      inline
      :model="form"
      ref="form"
      class="form-wrap"
      label-width="120px"
      v-loading="uploadLoading"
    >
      <div class="dialog-info">
        <el-form-item
          style="width:100%"
          verify
          label="名称"
          prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item
          style="width:100%"
          verify
          label="文件名"
          prop="download_suffix">
          <el-input v-model="form.download_suffix"></el-input>
        </el-form-item>
        <el-form-item
          label="上传文件"
          verify
          prop="downloadUrl"
          v-if="visible"
        >
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :show-file-list="true"
            :http-request="uploadFile"
            :on-remove="removeFile"
            :limit="1"
            :auto-upload="true"
          >
            <el-button
              size="small"
              type="primary">
              点击上传
            </el-button>
            <div
              slot="tip"
              class="el-upload__tip">
              只能上传1个文件
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item
          style="width:100%"
          label="下载地址"
          prop="downloadUrl">
          <el-input
            style="width: 400px;"
            v-model="form.downloadUrl"
            disabled></el-input>
        </el-form-item>
        <el-form-item
          style="width:100%"
          label="版本名"
          v-if="form.version_name"
          prop="version_name">
          <el-input
            v-model="form.version_name"
            disabled></el-input>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer">
      <el-button @click="handleClose">
        取 消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addTerminalConfig, updateTerminalConfig } from '@/api/terminalConfig'
import http from '@/utils/request'

const AppInfoParser = require('app-info-parser')
const defaultForm = {
  name: '',
  download_suffix: '',
  downloadUrl: '',
  type: 'APK_FILE',
  version_name: ''
}

export default {
  computed: {
    ticketTypeList () {
      return this.$store.state.app.ticketTypeList
    },
    uploadUrl () {
      const obj = this.$store.state.app.systemConfig.find(i => i.configKey === 'export_file_upload_url')
      return obj && obj.configValue
    }
  },
  data () {
    return {
      title: '',
      visible: false,
      loading: false,
      uploadLoading: false,
      packageList: {
        versionCode: '',
        versionName: '',
        packageName: '',
        downloadUrl: '',
        localPath: ''
      },
      form: {
        ...defaultForm
      }
    }
  },
  methods: {
    // 删除上传文件
    removeFile () {
      this.form.downloadUrl = ''
    },
    show (type, data) {
      this.type = type
      this.title = type === 'edit' ? '编辑apk' : '新增apk'
      this.visible = true
      this.$nextTick(() => {
        this.reset()
        if (type === 'edit' && data) {
          this.form = Object.assign({}, this.form, JSON.parse(JSON.stringify(data)))
          this.form.downloadUrl = ''
        } else {
          this.form = JSON.parse(JSON.stringify(defaultForm))
        }
      })
    },
    reset () {
      this.$refs.form.resetFields()
    },
    handleClose () {
      this.visible = false
    },
    handleSubmit () {
      if (this.type === 'edit' && !this.form.downloadUrl) {
        this.form.downloadUrl = 'null'
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          params.download_suffix = params.download_suffix.trim()
          if (params.downloadUrl === 'null') {
            params.downloadUrl = null
          }
          this.loading = true
          if (this.type === 'edit') {
            updateTerminalConfig(params).then(res => {
              this.$message.success('修改成功')
              this.$emit('update')
              this.handleClose()
            }).finally(() => {
              this.loading = false
            })
          } else {
            addTerminalConfig(params).then(res => {
              this.$message.success('添加成功')
              this.$emit('update')
              this.handleClose()
            }).finally(() => {
              this.loading = false
            })
          }
        }
      })
    },
    // 自定义上传方法
    uploadFile (params) {
      // 获取文件的后缀
      var fileName = params.file.name
      var fileArr = fileName.split('.')
      var fileType = fileArr[fileArr.length - 1]
      // 判断文件后缀是否正确
      this.uploadLoading = true

      if (fileType === 'apk') {
        const formdata = new FormData()
        formdata.append('file', params.file)
        http.post(this.uploadUrl, formdata, { headers: {
          'Content-Type': 'multipart/form-data' // 之前说的以表单传数据的格式来传递fromdata
        } }).then((res) => {
          this.packageList.downloadUrl = res.upload_path
          this.$message.success('上传成功')
          this.uploadLoading = false
          // 解析apk信息（这里很重要）
          // params.file 是这个文件对象
          const parser = new AppInfoParser(params.file)
          // parser.parse().then();是这个插件提供的方法，注意不要写错了
          parser.parse().then(result => {
            console.log('apk解析后的信息', result)
            this.form.version_name = result.versionName
            this.packageList.versionCode = result.versionCode
            this.packageList.versionName = result.versionName
            this.packageList.packageName = result.package
            console.log('this.packageList', this.packageList)
            const data = new Blob([JSON.stringify(this.packageList, null, 2)], {
              type: 'text/plain'
            })
            const file = new File([data], 'ApkConfig.json', { type: 'json' })
            const formdata = new FormData()
            formdata.append('file', file)
            http.post(this.uploadUrl, formdata, { headers: {
              'Content-Type': 'multipart/form-data'
            } }).then((res) => {
              this.form.downloadUrl = res.upload_path
            })
          }).catch(err => {
            console.log('err ----> ', err)
          })
        }).catch(() => {
          this.$message.error('上传失败')
          this.uploadLoading = false
        })
      } else {
        this.$message.error('请上传.apk格式的文件')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.periodItem {
  display: flex;  margin: 0 10px 10px 0; align-items: center;
}
.form-wrap {
  .priceInput {
     margin: 0 10px;
    .el-input-number{
        width: 160px;
    }
    ::v-deep .el-input {
      width: 100%;
    }
  }
}

</style>
