<template>
  <div>
    <el-card>
      <div class="filter">
        <el-button type="primary" icon="el-icon-circle-plus" @click="addEnvTemplate()"
          v-permission="('docker:envTemplate:create')">新增</el-button>
      </div>
      <el-table :data="envTemplateList" border style="width: 100%;margin-top:20px">
        <el-table-column type='index' width="50px">
          <template slot-scope="scope">
            <span>{{(queryModuleInfo.pageNum -1 ) * queryModuleInfo.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="envTemplate.name" label="名称" width="100px"></el-table-column>
        <el-table-column prop="envTemplate.updateTime" label="更新时间" width="200px"></el-table-column>
        <el-table-column label="操作">
          <slot slot-scope="scope">
            <el-button type="warning" icon="el-icon-edit" @click="editEnvTemplate(scope.row)"
              v-permission="('docker:envTemplate:modify')">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deEnvTemplateFrom(scope.row)"
              v-permission="('docker:envTemplate:delete')">删除</el-button>
          </slot>
        </el-table-column>
      </el-table>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="queryModuleInfo.pageNum" :page-size="queryModuleInfo.pageSize"
        layout="total, prev, pager, next" :total="totalNum">
      </el-pagination>
    </el-card>

    <!-- 新增环境模版页面 -->
    <el-dialog :title='titleName' :visible.sync="AddEnvTemplateDialog" width="80%">
      <el-form ref="addEnvTemplateFormRef" :rules="rules" :model="addEnvTemplateForm" label-width="90px">
        <el-form-item label="模版名称:" style="width:400px" prop="envTemplate.name">
          <el-input v-model="addEnvTemplateForm.envTemplate.name"></el-input>
        </el-form-item>
        <el-form-item v-for="(ns,index) in repoNamespaces" :label="ns.type" :key="index">
          <el-card>
            <el-button v-for="item in ns.repos" :key="item.serviceName" style="margin:3px"
              @click="selectSystem(item, ns.type)"
              :type="dependant[ns.type]&& dependant[ns.type].find(sys=>sys.serviceName===item.serviceName)?'success':''">
              {{ item.serviceName }}
            </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>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddEnvTemplateDialog=false">取 消</el-button>
        <el-button type="primary" @click="saveEnvTemplate">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import {
  getEnvTemplateList,
  getAllEnvRepo,
  addEnvTemplate,
  delEnvTemplate,
  editEnvTemplate
} from '@/api/getEnvTemplate'
export default {
  data() {
    return {
      queryModuleInfo: {
        pageNum: 1,
        pageSize: 10
      },
      AddEnvTemplateDialog: false,
      envTemplateList: [],
      totalNum: 0,
      addEnvTemplateForm: {
        envTemplate: {
          name: ''
        },
        envTemplateDetailList: []
      },
      repoNamespaces: [],
      dependant: {},
      isIndeterminate: {},
      checkAll: {},
      titleName: '',
      rules: {
        envTemplate: {
          name: [
            {
              required: true,
              message: '环境模版名称不能为空！',
              trigger: 'blur'
            }
          ]
        }
      }
    }
  },
  methods: {
    // 获取环境模版列表
    getEnvTemplateList() {
      getEnvTemplateList(this.queryModuleInfo).then((resp) => {
        this.envTemplateList = resp.data.data.list
        this.totalNum = resp.data.data.total
      })
    },
    handleSizeChange(newSize) {
      this.queryModuleInfo.pageSize = newSize
      this.getEnvTemplateList()
    },
    handleCurrentChange(newPage) {
      this.queryModuleInfo.pageNum = newPage
      this.getEnvTemplateList()
    },
    // 获取所有的服务信息
    getAllRepos() {
      getAllEnvRepo().then((resp) => {
        this.repoNamespaces = resp.data.data
        this.repoNamespaces.forEach((item) => {
          this.checkAll[item.type] = false
          this.isIndeterminate[item.type] = true
        })
      })
    },
    // 新增环境模版按钮
    addEnvTemplate() {
      this.titleName = '新增环境模版'
      this.AddEnvTemplateDialog = true
      this.addEnvTemplateForm.envTemplate = {}
      this.addEnvTemplateForm.envTemplateDetailList = []
      this.dependant = {}
    },
    // 保存环境模版
    saveEnvTemplate() {
      // 验证必填项
      this.$refs.addEnvTemplateFormRef.validate((valid) => {
        if (!valid) {
          return false
        } else {
          this.addEnvTemplateForm.envTemplateDetailList = []
          for (var i in this.dependant) {
            this.dependant[i].forEach((item) => {
              this.addEnvTemplateForm.envTemplateDetailList.push(item)
            })
          }
          // 编辑环境模版
          if (this.addEnvTemplateForm.envTemplate.id) {
            editEnvTemplate(this.addEnvTemplateForm)
              .then((resp) => {
                if (resp.data.msg === 'SUCCESS') {
                  this.$message.success('修改成功')
                  this.AddEnvTemplateDialog = false
                  this.getEnvTemplateList()
                } else {
                  this.$message.error(resp.data.msg)
                }
              })
              .catch((error) => {
                this.$message({ type: 'error', message: error })
              })
          } else {
            // 添加环境模版
            addEnvTemplate(this.addEnvTemplateForm)
              .then((resp) => {
                if (resp.data.data === true) {
                  this.$message.success('新增成功')
                  this.AddEnvTemplateDialog = false
                  this.getEnvTemplateList()
                } else {
                  this.$message.error(resp.data.msg)
                }
              })
              .catch((error) => {
                this.$message({ type: 'error', message: error })
              })
          }
        }
      })
    },
    // 点击button按钮 触发事件
    selectSystem(item, type) {
      if (!this.dependant[type]) this.$set(this.dependant, type, [])
      const index = this.dependant[type].findIndex(
        (sys) => sys.serviceName === item.serviceName
      )
      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()
      }
    },
    // 编辑环境模版
    editEnvTemplate(row) {
      this.titleName = '编辑环境模版'
      this.AddEnvTemplateDialog = true
      this.addEnvTemplateForm.envTemplate.id = row.envTemplate.id
      this.addEnvTemplateForm.envTemplate.name = row.envTemplate.name
      this.addEnvTemplateForm.envTemplateDetailList = row.envTemplateDetailList
      this.dependant = {}
      this.addEnvTemplateForm.envTemplateDetailList.forEach((item) => {
        this.selectSystem(item, item.label)
      })
    },
    // 对话框方法
    openMessage(message, confirmText, doit) {
      this.$messageBox
        .confirm(message, '确定', {
          cancelButtonText: '取消',
          confirmButtonText: confirmText,
          type: 'warning'
        })
        .then(() => {
          doit()
        })
        .catch(() => {})
    },
    // 删除环境模版
    deEnvTemplateFrom(row) {
      var formdata = new FormData()
      formdata.set('templateId', row.envTemplate.id)
      this.openMessage('您确定要删除吗？', '删除', () => {
        delEnvTemplate(formdata)
          .then((resp) => {
            if (resp.data.msg === 'SUCCESS') {
              this.$message.success('删除成功！')
              this.getEnvTemplateList()
            } else if (resp.data.data === false) {
              this.$message.error(resp.data.msg)
            }
          })
          .catch((error) => {
            this.$message({ type: 'error', message: error })
          })
      })
    }
  },
  created() {
    this.getEnvTemplateList()
    this.getAllRepos()
  }
}
</script>
