<template>
  <div class="app-container">
    <h3 style="overflow:hidden;">
      Pipeline Adapter
      <el-button type="primary" style="margin-right:40px;float:right" icon="el-icon-edit" @click="handleCreate">新建</el-button>
    </h3>
    <el-table
      v-loading="listLoading"
      :data="adapters"
      border
      fit
      highlight-current-row
      style="width: 100%;">
      <el-table-column type="index" align="center" width="65"/>
      <el-table-column label="name" prop="name" align="center"/>
      <el-table-column label="hook uri" prop="id" width="350" align="center"/>
      <el-table-column prop="description" label="description" align="center"/>
      <el-table-column prop="user" label="user" align="center"/>
      <el-table-column label="ops" align="center" width="180">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="scope.row.status!=='deleted'" size="mini" type="danger" @click="handleDelete(scope.row)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogStatus" :visible.sync="dialogFormVisible" width="50%">
      <el-form ref="dataForm" :rules="rules" :model="currentAdapter" label-position="left" label-width="100px" style="width: 90%; margin-left:40px;">
        <el-form-item label="name" prop="name" >
          <el-input v-model="currentAdapter.name"/>
        </el-form-item>
        <el-form-item label="description" prop="description" style="width:100%">
          <el-input v-model="currentAdapter.description"/>
        </el-form-item>
        <div >
          <div style="width:100%;margin-bottom:20px" >
            <el-button type="primary" style="width:20%" @click="newAdapter()"> + 新建</el-button>
          </div>
          <div v-for="(obj, index) in currentAdapter.triggerPipelines" :key="index" style="width:110%;margin-bottom:20px" >
            <label style="margin-right:20px"/>
            <el-input v-model="obj.name" placeholder="请输入名称" style="width:30%"/>
            <label style="margin:1px"/>
            <el-button type="primary" size="mini" icon="el-icon-edit" style="margin:5px" @click="handelScript(obj,index)">script</el-button>
            <el-select v-model="obj.pipelineId" value-key="id" style="width:30%">
              <el-option v-for="item in pipes" :value="item.id" :label="item.name" :key="item.id" />
            </el-select>
            <el-button :disabled="index===0?true:false" style="margin-left:5px" @click="currentAdapter.triggerPipelines.splice(index, 1)">删除</el-button>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="createData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogDeleteVisible" :data="currentAdapter" width="30%" title="删除">
      <span >
        确定要删除{{ currentAdapter.name }}吗?
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDeleteVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="deleteData">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
    <div v-show="modalshow&&dialogFormVisible" class="modal" @focusout="saveScript">
      <pre id="enditor" />
    </div>
  </div>
</template>
<script>
import { getAdapters, saveAdapter, getFlow, deleteAdapter } from '@/api/pipeline'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import ace from 'ace-builds/src-noconflict/ace'
import 'ace-builds/webpack-resolver' // 在 webpack 环境中使用必须要导入
import 'ace-builds/src-noconflict/theme-twilight' // 默认设置的主题
import 'ace-builds/src-noconflict/mode-javascript' // 默认设置的语言模式

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      id: 0,
      pipes: [],
      triggerPipelines: [],
      adapters: [],
      hook_uri: '',
      listLoading: true,
      dialogStatus: '',
      dialogFormVisible: false,
      dialogDeleteVisible: false,
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        description: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      currentAdapter: {
        name: '',
        description: '',
        triggerPipelines: [{ name: '', pipelineId: '', script: '' }]
      },
      modalshow: false,
      cont: '',
      editor: null,
      thescript: {}
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.getAdapters()
    this.getFlow()
  },
  mounted() {
    this.editor = ace.edit('enditor', {
      maxLines: 40, // 最大行数，超过会自动出现滚动条
      minLines: 20, // 最小行数，还未到最大行数时，编辑器会自动伸缩大小
      fontSize: 14, // 编辑器内字体大小
      tabSize: 4, // 制表符设置为 4 个空格大小
      theme: 'ace/theme/twilight', // 默认设置的主题
      mode: 'ace/mode/groovy'
    })
  },
  methods: {
    getAdapters() {
      getAdapters({}).then(res => {
        this.listLoading = false
        this.adapters = res.data.data
      }).catch(() => {
        this.listLoading = false
      })
    },
    newAdapter() {
      this.currentAdapter.triggerPipelines.push({ name: '', pipelineId: '', script: '' })
    },
    resetTemp() {
      this.currentAdapter = {
        name: '',
        description: '',
        triggerPipelines: [{ name: '', pipelineId: '', script: '' }]
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = '新建'
      this.dialogFormVisible = true
      this.modalshow = false
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.dialogStatus === '新建') {
            this.triggerPipelines.forEach((item) => {
              if (item.name === '' || item.pipelineId === '') {
                this.$notify({
                  title: 'error',
                  message: '请仔细检查名称及流水线是否填写正确',
                  type: 'error',
                  duration: 2000
                })
              }
            })
            saveAdapter(this.currentAdapter).then(res => {
              this.dialogFormVisible = false
              if (res.data.code === '0000') {
                this.getAdapters()
                this.$notify({
                  title: '成功',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
          } else {
            saveAdapter(this.currentAdapter).then(res => {
              this.dialogFormVisible = false
              if (res.data.code === '0000') {
                this.getAdapters()
                this.$notify({
                  title: '成功',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
          }
        }
      })
    },
    getFlow() {
      getFlow().then(res => {
        for (const index in res.data.data) {
          const item = res.data.data[index]
          this.pipes.push({ id: item.id, name: item.name })
        }
      })
    },
    handelScript(obj) {
      this.modalshow = true
      this.editor.setValue(obj.script)
      this.thescript = obj
    },
    handleDelete(row) {
      this.dialogDeleteVisible = true
      this.row = row
    },
    saveScript() {
      this.thescript.script = this.editor.getValue()
    },
    deleteData() {
      deleteAdapter(this.row.id).then(res => {
        this.dialogDeleteVisible = false
        if (res.data.code === '0000') {
          this.getAdapters()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },

    handleUpdate(row) {
      this.currentAdapter = Object.assign({}, row)
      this.dialogStatus = '编辑'
      this.dialogFormVisible = true
      this.modalshow = false
    }
  }
}
</script>
<style>
  .modal {
    position: absolute;
    height:100%;
    width:400px;
    bacground:#fff;
    z-index:9999;
    right:20px;
    top:20px;
  }
</style>
