<template>
  <div class="app-container" style="">
    <el-form ref="dataForm" label-position="left" label-width="130px" style="width: 95%; margin-left:20px;">
      <el-form-item label="模板名称">
        <el-input v-model="name"/>
      </el-form-item>
      <el-form-item label="选择已有模板" >
        <el-select v-model="currentTemplate" value-key="preset_name" style="width:100%" @change="useTemplate">
          <el-option v-for="item in templates" :value="item.name" :key="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item v-for="(ns, index) in repoNamespaces" :label="ns.type | upper" :key="index">
        <el-card>
          <el-button
            v-for="item in ns.repos"
            :key="item.appname"
            :type="dependant[ns.type] && dependant[ns.type].find(sys => sys.appname === item.appname) ? 'success' : ''"
            style="margin:3px"
            @click="selectSystem(item, ns.type)">
            {{ item.appname }}
          </el-button>
        </el-card>
        <el-checkbox :indeterminate="isIndeterminate[ns.type]" v-model="checkAll[ns.type]" @change="handleCheckAllChange(checkAll[ns.type],ns.type)">全选</el-checkbox>
      </el-form-item>
    </el-form >
    <div style="float:right">
      <el-button v-permission="['admin']" :disabled="name.length === 0" style="margin-right:10px;margin-bottom:40px;" type="primary" @click="createData()">新建</el-button>
      <el-button v-permission="['admin']" :disabled="!currentTemplateObj.base" style="margin-right:10px;margin-bottom:40px;" type="primary" @click="saveData()">保存</el-button>
      <el-button v-permission="['admin']" :disabled="!currentTemplateObj.base" style="margin-right:40px;margin-bottom:40px;" type="danger" @click="deleteData()">删除</el-button>
    </div>
  </div>
</template>

<script>
import { getAllRepos, getAllEnvTemplate, createEnvTemplate, saveEnvTemplate, deleteEnvTemplate } from '@/api/docker'
import permission from '@/directive/permission/index.js' // 权限判断指令

export default {
  directives: { permission },

  filters: {
    upper: function(value) {
      if (!value) return ''
      value = value.toString()
      return value[0].toUpperCase() + value.slice(1)
    }
  },

  data() {
    return {
      name: '',
      dependant: {},
      repoNamespaces: [],
      currentTemplate: '',
      currentTemplateObj: {},
      templates: {},
      checkAll: {},
      isIndeterminate: {}
    }
  },

  created() {
    this.getAllRepos()
    this.getAllEnvTemplate()
  },

  methods: {
    getAllRepos() {
      getAllRepos().then(res => {
        this.repoNamespaces = res.data
        this.repoNamespaces.forEach(item => {
          this.checkAll[item.type] = false
          this.isIndeterminate[item.type] = true
        })
      })
    },

    getAllEnvTemplate() {
      getAllEnvTemplate().then(res => {
        // todo: http服务统一返回res.data
        this.templates = res.data
      })
    },

    selectSystem(item, type) {
      if (!this.dependant[type]) this.$set(this.dependant, type, [])
      const index = this.dependant[type].findIndex(sys => sys.appname === item.appname)
      if (index === -1) {
        this.dependant[type].push(item)
      } else {
        this.dependant[type].splice(index, 1)
      }
    },

    handleCheckAllChange(val, type) {
      this.$set(this.dependant, type, [])
      this.isIndeterminate[type] = false
      if (val) this.dependant[type] = this.repoNamespaces.filter(item => item.type === type)[0].repos.concat()
    },

    useTemplate() {
      const vm = this
      this.currentTemplateObj = this.templates.find(item => item.name === this.currentTemplate)
      // 清空所有选择
      vm.$set(this, 'dependant', {})

      // 遍历设置
      const keys = Object.keys(this.currentTemplateObj)
      keys.forEach(key => {
        if (key !== 'name' && key !== '_id') {
          this.currentTemplateObj[key].forEach(repo => {
            vm.selectSystem(repo, key)
          })
        }
      })
    },

    createData() {
      const param = {
        name: this.name,
        ...this.dependant
      }
      createEnvTemplate(param).then(res => {
        // todo: 异常在http服务统一处理
        this.$message({
          message: res.data || '环境模板创建成功',
          type: 'success',
          duration: 1000
        })
        this.getAllEnvTemplate()
      })
    },

    saveData() {
      const param = {
        name: this.currentTemplateObj.name,
        _id: this.currentTemplateObj._id,
        ...this.dependant
      }
      saveEnvTemplate(param).then(res => {
        // todo: 异常在http服务统一处理
        this.$message({
          message: res.data || '环境模板保存成功',
          type: 'success',
          duration: 1000
        })
        this.getAllEnvTemplate()
      })
    },

    deleteData() {
      const vm = this
      const param = {
        _id: this.currentTemplateObj._id
      }
      deleteEnvTemplate(param).then(res => {
        // todo: 异常在http服务统一处理
        this.$message({
          message: '环境模板删除成功',
          type: 'success',
          duration: 1000
        })
        this.getAllEnvTemplate()
        this.currentTemplate = '空'
        vm.$set(this, 'dependant', {})
      })
    }
  }
}
</script>
