<template>
  <div>
    <div
      class="wrapper"
      v-loading="loading">
      <div>
        <div class="block-title">
          基本信息
        </div>
        <el-form
          inline
          :model="paramData"
          ref="paramData"
          class="form-wrap"
          label-width="100px"
        >
          <el-form-item
            verify
            label="名称"
            prop="name">
            <el-input
              v-model="paramData.name"
              placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item
            verify
            label="文件名"
            prop="download_suffix">
            <el-input
              v-model="paramData.download_suffix"
              placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item
            label="版本号"
            prop="version">
            <el-input
              v-model="paramData.version"
              placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item
            label="设备状态"
            prop="enable">
            <el-select
              v-model="paramData.enable"
              placeholder="请选择">
              <el-option
                label="开启"
                :value="1">
              </el-option>
              <el-option
                label="关闭"
                :value="0">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </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="currentData"
              ref="form"
              v-loading="uploadLoading"
              v-if="currentData">
              <el-form-item
                :label="typeMap[key] && typeMap[key].label"
                :key="key"
                label-width="200px"
                v-for="(val,key) in currentData">
                <component
                  v-if="typeMap[key]"
                  style="margin-left: -150px;"
                  :style="{width:typeof currentData[key]==='boolean'?'auto':'80%'}"
                  :is="typeMap[key].type || Input"
                  :disabled="typeMap[key].disabled"
                  v-model="currentData[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>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="dialog-btn-wrap">
      <el-button
        @click="getConfig">
        重置
      </el-button>
      <el-button
        @click="handleClose">
        关闭
      </el-button>
      <el-button
        @click="submitForm"
        type="primary">
        保存
      </el-button>
    </div>
  </div>
</template>
<script>
import { nameMap_terminal, typeMap } from '../deviceManage/configSetting/const'
import configData from '@/assets/checkerConfig.json'
import http from '@/utils/request'
import { addTerminalConfig, updateTerminalConfig } from '@/api/terminalConfig'
const defaultForm = {
  name: '',
  download_suffix: '',
  downloadUrl: '',
  type: 'CONFIG_FILE',
  version_name: '',
  enable: 0,
  version: ''
}
export default {
  props: {
    ip: {
      type: String,
      default: ''
    },
    dialogType: {
      type: String,
      default: ''
    },
    configInfo: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      visible: false,
      currentIndex: 0, // 配置菜单序号
      activeName: 'uiConfig', // 当前tap
      menus: Object.entries(nameMap_terminal),
      loading: false,
      uploadLoading: false,
      configList: null,
      currentData: null, // 当前表单数据
      typeMap,
      form: null,
      paramData: {
        ...defaultForm
      },
      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: {
    handleClose () {
      this.$parent.handleClose()
    },
    // 从下载链接获取配置内容
    getConfigContent () {
      return new Promise((resolve) => {
        if (this.configInfo) {
          const Store = require('electron-store')
          const localStore = new Store()
          const serverUrl = localStore.get('serverUrl') // 服务器地址
          const newUrl = serverUrl + this.configInfo.downloadUrl.split('.cn')[1]
          http.post(newUrl).then((res) => {
            this.configList = res
            resolve()
          })
        } else {
          resolve()
        }
      })
    },

    // 获取配置信息
    async getConfig () {
      this.loading = true
      await this.getConfigContent()
      this.form = (this.dialogType === 'edit' && this.configList) || JSON.parse(JSON.stringify(configData))
      this.paramData.name = (this.configInfo && this.configInfo.name) || ''
      this.paramData.download_suffix = (this.configInfo && this.configInfo.download_suffix) || ''
      this.paramData.enable = this.form.enable
      this.paramData.version = this.form.version
      this.currentData = this.form[this.menus[this.currentIndex][0]]
      this.loading = false
    },

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

    // 提交表单
    submitForm () {
      this.$refs.paramData.validate(valid => {
        if (valid) {
          this.loading = true
          this.form.version = this.paramData.version
          this.form.enable = this.paramData.enable
          const data = new Blob([JSON.stringify(this.form, null, 2)], {
            type: 'text/plain'
          })
          const file = new File([data], 'CheckerConfig.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.paramData.downloadUrl = res.upload_path
            if (this.dialogType === 'add') {
              addTerminalConfig(this.paramData).then(res => {
                this.$message.success('操作成功')
                this.$emit('update')
                this.handleClose()
              }).finally(() => {
                this.loading = false
              })
            } else {
              this.paramData.id = this.configInfo.id
              updateTerminalConfig(this.paramData).then(res => {
                this.$message.success('更新成功')
                this.$emit('update')
                this.handleClose()
              }).finally(() => {
                this.loading = false
              })
            }
          }).catch(() => {
            this.$message.error('保存失败')
            this.loading = false
          })
        }
      }
      )
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.activeName = 'uiConfig'
        this.currentIndex = 0
        this.$refs.paramData.resetFields()
        this.getConfig()
      } else {
        this.form = null
        this.currentData = null
        this.configList = null
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.form-wrap{
  display: flex;
}
.wrapper {
  position: relative;
  padding: 20px 20px;
  ::v-deep .el-input,  .el-select,  .el-date-editor, .el-input,  .el-input-number {
    width: auto;
  }
}
.version {
  position: absolute;  top: 5px;
 right: 10px;
}
.content {
  padding: 20px 20px;
}
.btnWrapper {
  text-align: center;
}
.upload-demo {
  margin-left: -150px;
}

</style>
