<template>
  <div style="margin-top: 30px">
    <el-header style="text-align: right;height: 40px;overflow: hidden">
      <h3 style="float:left;">{{ name }}：<span style="font-weight:normal">{{ description }}</span></h3>
      <el-button type="primary" plain size="small" style="margin-right: 80px" @click="handleCreate()"> +新增Stage </el-button>
    </el-header>
    <el-main v-for="(stage, index) in pipesConf" :key="index" style="width: 75%;margin-left: 80px;">
      <el-container style="height: 270px; border-bottom: 5px solid #B3C0D1; box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">
        <el-aside width="250px" style="text-align: center; padding-top: 85px; border-right: 5px solid #B3C0D1">
          <div>{{ stage.name }}</div>
          <div>{{ stage.id }}</div>
          <div style="margin-top:10px">
            <el-button type="primary" plain circle icon="el-icon-edit" size="mini" @click="handleStageUpdate(stage.name)"/>
            <el-button type="danger" plain circle icon="el-icon-delete" size="mini" @click="handleStageDelete(stage)"/>
          </div>
        </el-aside>
        <el-container>
          <el-header style="text-align:right;height: 50px" >
            <el-button type="primary" plain size="small" icon="el-icon-plus" style="margin-top: 15px;margin-right: 40px" @click="handleTask(stage)"/>
          </el-header>
          <el-main>
            <el-table :data="stage.tasks">
              <el-table-column prop="name" label="name" width="180"/>
              <el-table-column prop="mode" label="构建模式" width="180"/>
              <el-table-column prop="type" label="类型" width="180"/>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button type="info" plain circle icon="el-icon-info" size="mini" @click="handleTaskInfo(scope.row)"/>
                  <el-button type="primary" plain circle icon="el-icon-edit" size="mini" @click="handleTaskUpdate(scope.row, index)"/>
                  <el-button type="danger" plain circle icon="el-icon-delete" size="mini" @click="handleTaskDelete(scope.row, index)"/>
                </template>
              </el-table-column>
            </el-table>
          </el-main>
        </el-container>
      </el-container>
    </el-main>
    <el-dialog :title="dialogStatus" :visible.sync="dialogResultVisible" width="30%">
      Name ：
      <el-input v-model="temp.name" placeholder="请输入名称" style="width:70%"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogResultVisible = 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="stage" width="30%" title="删除">
      <span >
        确定要删除 <strong>{{ stage.name }}</strong> 吗?
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDeleteVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="deleteStage(stage.id)">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
    <div v-show="dialogFormVisible" class="el-dialog__wrapper" style="z-index:2002">
      <div role="dialog" aria-modal="true" aria-label="新建Task" class="el-dialog" style="margin-top: 15vh; width: 50%;">
        <div class="el-dialog__header"><span class="el-dialog__title">{{ dialogTaskStatus }}</span><button type="button" aria-label="Close" class="el-dialog__headerbtn" @click="dialogFormVisible=false"><i class="el-dialog__close el-icon el-icon-close"/></button></div>
        <div class="el-dialog__body">
          <el-form ref="dataForm" :rules="rules" :model="tasks" label-position="left" label-width="50px" size="mini" style="margin-left:40px;">
            <el-form-item label="Name" label-width="100px" style="width: 50%">
              <el-input v-model="tasks.name"/>
            </el-form-item>
            <el-form-item label="Necessary" label-width="100px" style="width: 25%">
              <el-switch
                v-model="tasks.necessary"
                active-color="#13ce66"
                inactive-color="#909399"/>
            </el-form-item>
            <el-form-item label="Mode" label-width="100px" style="width: 25%">
              <el-select v-model="tasks.mode" placeholder="请选择">
                <el-option
                  v-for="item in modes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="Notice Mode" label-width="100px" style="width: 35%">
              <el-select v-model="tasks.noticeMode" placeholder="请选择">
                <el-option
                  v-for="item in notices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="type" label-width="100px" style="width: 25%">
              <el-select v-model="tasks.type" placeholder="请选择">
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div v-show="tasks.type == 'script'" style="position: relative;padding-left: 60px;overflow: hidden">
          <span
            style="color: #606266; font-size: 14px;-webkit-font-smoothing: antialiased;
            text-rendering: optimizeLegibility;
            font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;font-weight: 700;float: left;padding-right: 12px;">Script:</span>
          <div id="editorDiv" style="width: 650px;height: 250px;" />
        </div>
        <div class="el-dialog__footer">
          <div v-show="dialogTaskStatus != '查看Task'" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
            <el-button type="primary" @click="createTask()">{{ $t('table.confirm') }}</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="dialogDeleteTask" :data="tasks" width="30%" title="删除">
      <span >
        确定要删除 <strong>{{ tasks.name }}</strong> 吗?
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDeleteTask = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="deleteTask()">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { find, createStage, updateStage, deleteStage, createTask, updateTask, deleteTask } from '@/api/pipeline'
import moment from 'moment'
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 {
  data() {
    return {
      pipesConf: [],
      name: '',
      description: '',
      pipes: [],
      listLoading: true,
      pipelineId: '',
      temp: { name: '',
        id: '',
        tasks: [{ mode: '', name: '', necessary: 'false', noticeMode: '', num: '', script: '', type: '' }] },
      dialogResultVisible: false,
      dialogStatus: '',
      dialogTaskStatus: '',
      stageIndex: 0,
      taskId: 0,
      stage: {},
      editor: null,
      tasks: { mode: '', name: '', necessary: 'false', noticeMode: '', num: '', script: '', type: '' },
      modes: [{ value: 'serial', label: 'serial' }, { value: 'parallel', label: 'parallel' }],
      notices: [{ value: 'pass', label: 'pass' }, { value: 'notpass', label: 'notpass' }, { value: 'all', label: 'all' }, { value: 'no', label: 'no' }],
      types: [{ value: 'manual', label: 'manual' }, { value: 'script', label: 'script' }],
      script: {},
      dialogFormVisible: false,
      dialogDeleteVisible: false,
      dialogDeleteTask: false,
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        description: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.getPipelineManager()
  },
  mounted() {
    this.editor = ace.edit('editorDiv', {
      maxLines: 40, // 最大行数，超过会自动出现滚动条
      minLines: 20, // 最小行数，还未到最大行数时，编辑器会自动伸缩大小
      fontSize: 14, // 编辑器内字体大小
      tabSize: 4, // 制表符设置为 4 个空格大小
      theme: 'ace/theme/twilight', // 默认设置的主题
      mode: 'ace/mode/groovy'
    })
  },
  methods: {
    getPipelineManager() {
      // 获取PipelineId
      this.pipelineId = this.$route.query.pipelineId
      // 根据pipelineId获取详情数据
      find(this.pipelineId).then(res => {
        this.listLoading = false
        this.pipesConf = res.data.data.stages
        this.name = res.data.data.name
        this.description = res.data.data.description
      }).catch(() => {
        this.listLoading = false
      })
    },
    formatDate(row, val) {
      var pattern = 'YYYY-MM-DD HH:mm:ss'
      return moment(row.updateTime).format(pattern)
    },
    resetTemp() {
      this.temp = { name: '',
        id: '',
        tasks: [{ mode: '', name: '', necessary: 'false', noticeMode: '', num: '', script: '', type: '' }] }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = '新建Stage'
      this.dialogResultVisible = true
    },
    createData() {
      // 获取PipelineId
      this.pipelineId = this.$route.query.pipelineId
      if (this.dialogStatus === '新建Stage') {
        createStage(this.pipelineId, { name: this.temp.name }).then(res => {
          this.dialogResultVisible = false
          if (res.data.code === '0000') {
            this.getPipelineManager()
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      } else {
        updateStage(this.pipelineId, { name: this.temp.name }).then(res => {
          this.dialogResultVisible = false
          if (res.data.code === '0000') {
            this.getPipelineManager()
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      }
    },
    handleStageUpdate(name) {
      this.dialogResultVisible = true
      this.dialogStatus = '编辑Stage'
      this.temp.name = name
    },
    handleStageDelete(stage) {
      this.dialogDeleteVisible = true
      this.stage = stage
    },
    deleteStage(stageId) {
      // 获取PipelineId
      this.pipelineId = this.$route.query.pipelineId
      deleteStage(this.pipelineId, stageId).then(res => {
        this.dialogDeleteVisible = false
        if (res.data.code === '0000') {
          this.getPipelineManager()
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    resetTasks() {
      this.tasks = { mode: '', name: '', necessary: 'false', noticeMode: '', num: '', script: '', type: '' }
    },
    handleTask(stage) {
      this.resetTasks()
      this.tasks.script = this.editor.setValue('')
      this.dialogTaskStatus = '新建Task'
      this.dialogFormVisible = true
      this.temp = stage
    },
    createTask() {
      // 获取PipelineId
      this.pipelineId = this.$route.query.pipelineId
      if (this.dialogTaskStatus === '新建Task') {
        this.tasks.script = this.editor.getValue()
        createTask(this.pipelineId, this.temp.id, this.tasks).then(res => {
          this.dialogFormVisible = false
          if (res.data.code === '0000') {
            this.getPipelineManager()
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      } else {
        this.tasks.script = this.editor.getValue()
        updateTask(this.pipelineId, this.stageIndex, this.tasks).then(res => {
          this.dialogFormVisible = false
          if (res.data.code === '0000') {
            this.getPipelineManager()
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      }
    },
    handleTaskInfo(row) {
      this.dialogTaskStatus = '查看Task'
      this.dialogFormVisible = true
      this.tasks = Object.assign({}, row)
      this.editor.setValue(this.tasks.script)
    },
    handleTaskUpdate(row, index) {
      this.tasks = Object.assign({}, row)
      this.dialogTaskStatus = '编辑Task'
      this.dialogFormVisible = true
      this.stageIndex = index
      this.editor.setValue(this.tasks.script)
    },
    handleTaskDelete(row, index) {
      this.tasks = Object.assign({}, row)
      this.dialogDeleteTask = true
      this.taskId = row.id
      this.stageIndex = index
    },
    deleteTask() {
      // 获取PipelineId
      this.pipelineId = this.$route.query.pipelineId
      deleteTask(this.pipelineId, this.stageIndex, this.taskId).then(res => {
        this.dialogDeleteTask = false
        if (res.data.code === '0000') {
          this.getPipelineManager()
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    }
  }
}
</script>
