<template>
  <div
    class="wrapper"
    v-loading="loading">
    <span class="version"> 当前版本：{{ allData && allData.version }}</span>
    <div v-if="form">
      <div class="block-title">
        终端操作
      </div>
      <el-button
        type="primary"
        @click="openGateInOnce">
        开门（1次）
      </el-button>
      <el-button
        type="primary"
        @click="keepOpenGate">
        常开
      </el-button>
      <el-button
        type="primary"
        @click="closeGate">
        关门
      </el-button>
      <el-button
        type="danger"
        @click="reboot">
        重启
      </el-button>
    </div>

    <div
      class="block-title"
      style="margin-top:20px">
      基本配置
    </div>
    <el-tabs
      tab-position="left"
      @tab-click="handleClick"
      v-model="activeName"
    >
      <el-tab-pane
        :label="m[1]"
        v-for="(m) in menus"
        :name="m[0]"
        :key="m[0]">
        <div
          class="content"
        >
          <el-form
            :model="form"
            ref="form"
            v-loading="uploadLoading"
            v-if="form">
            <el-form-item
              label="上传更新包"
              v-if="m[0] ==='terminalUpgrade'"
              label-width="200px">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :show-file-list="true"
                :http-request="uploadFile"
                :limit="1"
                :auto-upload="true"
                :before-upload="beforeUploadFile"
              >
                <el-button
                  size="small"
                  type="primary">
                  点击上传
                </el-button>
                <div
                  slot="tip"
                  class="el-upload__tip">
                  文件格式.apk，且只能上传1个文件
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item
              :label="typeMap[key] && typeMap[key].label"
              :key="key"
              label-width="200px"
              v-for="(val,key) in form">
              <component
                v-if="typeMap[key]"
                style="margin-left: -150px;"
                :style="{width:typeof form[key]==='boolean'?'auto':'80%'}"
                :is="typeMap[key].type || Input"
                :disabled="typeMap[key].disabled"
                v-model="form[key]">
                <template v-if="typeMap[key].options">
                  <el-option
                    v-for="item in typeMap[key].options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </template>
              </component>
            </el-form-item>
            <el-form-item>
              <div class="btnWrapper">
                <el-button
                  type="primary"
                  @click="upgradeForm('ruleForm')"
                  v-if="m[0] ==='terminalUpgrade'">
                  升级
                </el-button>
                <el-button
                  v-else
                  type="primary"
                  @click="submitForm('ruleForm')">
                  提交
                </el-button>
                <el-button @click="resetForm('ruleForm')">
                  重置
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import { getConfig, upDataConfig, upgradeForm, reboot, openGateInOnce, keepOpenGate, closeGate } from './configSetting/api'
import { nameMap, typeMap } from './configSetting/const'
import http from '@/utils/request'
const AppInfoParser = require('app-info-parser')
export default {
  props: {
    ip: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      visible: false,
      currentIndex: 0, // 配置菜单序号
      activeName: 'uiConfig', // 当前tap
      menus: Object.entries(nameMap),
      allData: {},
      loading: false,
      uploadLoading: false,
      currentData: null, // 当前表单数据
      typeMap,
      form: null,
      pathMap: {
        uiConfig: 'ui',
        cardReaderConfig: 'cardreader',
        checkerConfig: 'checker',
        faceConfig: 'face',
        gateConfig: 'gate',
        serverConfig: 'server'
      } // 请求path拼接
    }
  },
  computed: {
    uploadUrl () {
      return this.$store.state.app.systemConfig.find(i => i.configKey === 'export_file_upload_url').configValue
    }
  },
  methods: {
    // 自定义上传方法
    uploadFile (params) {
      // 获取文件的后缀
      var fileName = params.file.name
      var fileArr = fileName.split('.')
      var fileType = fileArr[fileArr.length - 1]
      // 判断文件后缀是否正确
      if (fileType === 'apk') {
        this.uploadLoading = true
        const formdata = new FormData()
        formdata.append('file', params.file)
        http.post(this.uploadUrl, formdata, { headers: {
          'Content-Type': 'multipart/form-data' // 之前说的以表单传数据的格式来传递fromdata
        } }).then((res) => {
          this.form.downloadUrl = res.upload_path
          this.$message.success('上传成功')
          this.uploadLoading = false
        }).catch(() => {
          this.$message.error('上传失败')
          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.versionCode = result.versionCode
          this.form.versionName = result.versionName
          this.form.packageName = result.package
        }).catch(err => {
          console.log('err ----> ', err)
        })
      }
    },

    // 上传改变
    beforeUploadFile (file) {
      const isApk = file.type.indexOf('android') > -1
      if (!isApk) {
        this.$message.error('文件只能是.apk 格式')
        return false
      }
    },

    // 获取配置信息
    getConfig () {
      this.loading = true
      getConfig(this.ip).then(res => {
        res.terminalUpgrade = {
          versionCode: '',
          packageName: '',
          versionName: '',
          downloadUrl: ''
        }
        this.allData = res
        console.log('this.allData', this.allData)
        this.currentData = res[this.menus[this.currentIndex][0]]
        this.form = JSON.parse(JSON.stringify(this.currentData))
        this.loading = false
      }).catch(e => {
        this.loading = false
        this.$message.error('获取失败')
      })
    },

    // 切换tap
    handleClick (tab, event) {
      this.currentIndex = Number(tab.index)
      this.currentData = this.allData[this.menus[this.currentIndex][0]]
      this.form = JSON.parse(JSON.stringify(this.currentData))
    },

    // 升级终端
    upgradeForm () {
      const ip = this.ip
      const data = this.form
      upgradeForm({ ip, data }).then(res => {
        this.$message.success('操作成功')
      }).catch(e => {
        this.$message.error('操作失败')
      })
    },

    // 提交表单
    submitForm () {
      const ip = this.ip
      const path = this.pathMap[this.activeName]
      const action = 'setData'
      const data = this.form
      upDataConfig({ ip, path, action, data }).then(res => {
        this.$message.success('操作成功')
        this.getConfig()
      }).catch(e => {
        this.$message.error('操作失败')
      })
    },

    // 重置表单
    resetForm () {
      this.form = JSON.parse(JSON.stringify(this.currentData))
    },

    // 重启
    reboot () {
      reboot(this.ip)
    },

    // 开门一次
    openGateInOnce () {
      openGateInOnce(this.ip)
    },

    // 门常开
    keepOpenGate () {
      keepOpenGate(this.ip)
    },

    // 关门
    closeGate () {
      closeGate(this.ip)
    }

  },
  watch: {
    visible (val) {
      if (val) {
        this.activeName = 'uiConfig'
        this.currentIndex = 0
        this.getConfig()
        console.log('typeMap', typeMap)
      } else {
        this.allData = null
        this.form = null
        this.currentData = null
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.wrapper {
  ::v-deep .el-input,  .el-select,  .el-date-editor, .el-input,  .el-input-number {
    width: auto;
  }
}

.wrapper {
  position: relative;  padding: 20px 20px;
}
.version {
  position: absolute;  top: 5px;
 right: 10px;
}
.content {
  padding: 20px 20px;
}
.btnWrapper {
  text-align: center;
}
.upload-demo {
  margin-left: -150px;
}

</style>
