<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.application_name" placeholder="应用名称" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.new_user" placeholder="新建用户" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-switch
        v-model="value1"
        style="float: right"
        inactive-text="系统列表"
        active-text="用户列表"
        @change="filterUserData(value1)"/>
    </div>

    <el-table
      :data="applications"
      border
      fit
      highlight-current-row
      style="width: 100%;">
      <el-table-column :label="$t('table.id')" prop="id" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应用名称" prop="application_name" align="center">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.application_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务->分支" align="center" width="300px">
        <template slot-scope="scope">
          <div v-for="item in scope.row.repos" :key="item.id"><b>{{ item.repository }}</b> -> {{ item.ref.name }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="new_user" label="创建者" align="center"/>
      <el-table-column prop="update_user" label="更新者" align="center"/>
      <el-table-column prop="isDeploy" label="自动部署" align="center">
        <template slot-scope="scope">
          {{ scope.row.isDeploy | formatDeploy }}
        </template>
      </el-table-column>
      <el-table-column prop="namespace" label="命名空间" align="center"/>
      <el-table-column :formatter="formatDate" label="时间" align="center"/>
      <el-table-column :label="$t('table.actions')" align="center" width="180" class-name="small-padding fixed-width">
        <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>

    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" /> -->

    <el-dialog :title="dialogStatus" :visible.sync="dialogFormVisible" @close="handleFilter">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 90%; margin-left:40px;">
        <el-form-item label="应用名称" prop="application_name" >
          <el-input v-model="temp.application_name"/>
        </el-form-item>
        <div >
          <div v-for="(repoAndRefItem,index) in temp.repos" :key="repoAndRefItem.id" style="width:110%;margin-bottom:20px" >
            <label style="margin-right:20px">服务</label>
            <el-select v-model="repoAndRefItem.repository" filterable value-key="id" style="width:30%" class="filter-item" @change="getRefs(repoAndRefItem.repository,true)">
              <el-option v-for="item in repos" :value="item.project_name" :label="item.project_name" :key="item.project_name" />
            </el-select>
            <label style="margin:20px">分支</label>
            <el-select v-model="repoAndRefItem.ref.name" filterable value-key="id" style="width:30%" class="filter-item">
              <el-option v-for="item in refs[repoAndRefItem.repository]" :value="item.name" :label="item.name" :key="item.name" />
            </el-select>
            <el-button :disabled="index===0 && temp.repos.length===1" style="margin-left:5px" @click="temp.repos.splice(index, 1)">删除</el-button>
          </div>
          <div style="width:100%;margin-bottom:20px" >
            <el-button type="primary" style="width:100%" @click="newRepoAndRef()"> + 新增服务&分支</el-button>
          </div>
        </div>
        <el-form-item label="通知方式" prop="noticeType">
          <el-select v-model="temp.noticeType" label="通知方式" style="width:100%">
            <el-option v-for="item in noticeTypes" :value="item" :label="item " :key="item" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="temp.noticeType === 'dingding'" label="通知地址">
          <el-input :autosize="{ minRows: 3, maxRows: 4}" v-model="temp.noticeAddress" type="textarea" placeholder="Please input"/>
        </el-form-item>
        <el-form-item label="是否部署到容器" label-width="120px !important">
          <el-switch
            v-model="temp.isDeploy"
            inactive-color="#efefef"
            active-color="#13ce66"
          />
        </el-form-item>
        <el-form-item v-if="temp.isDeploy" label="所属集群" prop="cluster" >
          <el-select v-model="temp.cluster" filterable style="width:100%" @change="changeCluster">
            <el-option v-for="item in clusterArray" :value="item.clusterName" :label="item.clusterName" :key="item.clusterName" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="temp.isDeploy" label="命名空间" prop="namespace" >
          <!-- <el-input v-model="temp.namespace"/> -->
          <el-select v-model="temp.namespace" filterable style="width:100%">
            <el-option v-for="item in nsArray" :value="item.name" :label="item.name" :key="item.name" />
          </el-select>
        </el-form-item>
      </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="temp" title="Delete">
      <span >
        确定要删除{{ temp.application_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>
</template>

<script>
import { getApplications, saveApplication, updateApplication, deleteApplication, getBranch } from '@/api/pipelineNode'
import { getProjects } from '@/api/proconfig'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import moment from 'moment'
import { getCluster } from '@/api/cluster'
import { fetchKubernetesList } from '@/api/docker'

export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    replaceeRef(ref) {
      return ref ? ref.replace('refs/heads/', '') : ''
    },
    formatDeploy(data) {
      return data ? '是' : '否'
    }
  },
  data() {
    return {
      value1: true,
      repository: '',
      total: 0,
      listQuery: {},
      temp: {},
      dialogFormVisible: false,
      dialogDeleteVisible: false,
      dialogStatus: '',
      rules: {
        application_name: [{ required: true, message: '请输入', trigger: 'change' }],
        namespace: [{ required: true, message: '请输入', trigger: 'blur' }],
        cluster: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      noticeTypes: ['dingding', 'mail'],
      applications: [],
      application: [],
      repos: [],
      repo: '',
      refs: {},
      ref: undefined,
      clusterArray: [],
      nsArray: []
    }
  },
  computed: {

  },
  watch: {
  },
  created() {
    this.getApplications()
    this.getCluster()
    this.fetchK8sList()
  },
  methods: {
    getCluster() {
      getCluster().then(res => {
        this.clusterArray = res.data
      })
    },

    changeCluster() {
      this.$store.dispatch('changeCluster', this.temp.cluster)
      sessionStorage.setItem('cluster', this.temp.cluster)
      this.fetchK8sList()
    },

    fetchK8sList() {
      fetchKubernetesList().then(res => {
        this.nsArray = res.data.namespaces
      })
    },

    filterUserData() {
      this.getApplications()
    },
    getApplications() {
      for (const prop in this.listQuery) {
        if (this.listQuery[prop] === '') {
          delete this.listQuery[prop]
        }
      }
      var arr = Object.keys(this.listQuery)
      getApplications(arr.length > 0 ? this.listQuery : null).then(res => {
        if (!this.value1) {
          this.applications = res.data.filter((item) => {
            if (item.application_name.indexOf('master分支订阅') > -1 && item.new_user.indexOf('胡慧') > -1) {
              return item
            }
          })
        } else {
          this.applications = res.data.filter((item) => {
            if (item.application_name.indexOf('master分支订阅') <= 0 && item.new_user.indexOf('胡慧') <= 0) {
              return item
            }
          })
        }
      })
    },
    newRepoAndRef() {
      this.temp.repos.push({ repository: '', ref: {}})
    },

    handleFilter() {
      this.getApplications()
    },

    formatDate(row, val) {
      const pattern = 'YYYY-MM-DD HH:mm:ss'
      return moment(row.updatedAt || row.createdAt).format(pattern)
    },

    resetTemp() {
      this.temp = {
        id: 0,
        namespace: null,
        noticeAddress: '',
        noticeType: '',
        isDeploy: false,
        repos: [{ repository: '', ref: { id: '请选择' }}],
        application_name: '',
        new_user: '',
        update_user: '',
        cluster: this.$store.getters.cluster
      }
    },

    getProjects() {
      getProjects({ is_active: true, deploy_to_testenv: true }).then(res => {
        this.repos = res.data
        this.repos.sort((s1, s2) => {
          return s1.project_name.localeCompare(s2.project_name)
        })
      })
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = '新建'
      this.getProjects()
      this.dialogFormVisible = true
    },

    getRefs(repo, flag) {
      if (flag) {
        this.temp.repos.forEach(item => {
          if (item.repository === repo) {
            item.ref = {}
          }
        })
      }
      getBranch({ name: repo }).then(res => {
        if (res.data.code === '0001') {
          this.$notify({
            title: 'error',
            message: '因权限问题,获取分支失败',
            type: 'error',
            duration: 2000
          })
        } else {
          this.$set(this.refs, repo, res.data.map(item => {
            return {
              id: item.commit.id,
              name: item.name
            }
          }))
          this.refs[repo].push({ id: '0', name: '请选择' })
          this.refs[repo].reverse()
        }
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.repos.forEach(item => {
            this.repos.forEach(value => {
              if (item.repository === value.project_name) {
                this.$set(item, 'type', value.type)
                this.$set(item, 'groupName', value.git_path_group)
              }
            })
          })
          if (this.dialogStatus === '新建') {
            this.temp.new_user = this.$store.getters.name
            let flag = true
            this.temp.repos.forEach((item) => {
              if (item.ref.name == null || item.ref.name === '请选择') {
                this.$notify({
                  title: 'error',
                  message: '请仔细检查服务和分支名称是否填写正确',
                  type: 'error',
                  duration: 2000
                })
                flag = false
              }
            })
            if (!flag) return false
            saveApplication(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
              this.getApplications()
            })
          } else {
            this.temp.update_user = this.$store.getters.name
            let flag = true
            this.temp.repos.forEach((item) => {
              if (item.ref.name == null || item.ref.name === '请选择') {
                this.$notify({
                  title: 'error',
                  message: '请仔细检查服务和分支名称是否填写正确',
                  type: 'error',
                  duration: 2000
                })
                flag = false
              }
            })
            if (!flag) return false
            updateApplication(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
              this.getApplications()
            })
          }
        }
      })
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = '编辑'
      this.dialogFormVisible = true
      this.getProjects()
      row.repos.forEach(item => {
        this.getRefs(item.repository)
      })
    },

    handleDelete(row) {
      this.temp = row
      this.dialogDeleteVisible = true
    },

    deleteData() {
      deleteApplication({ id: this.temp._id }).then(() => {
        this.dialogDeleteVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getApplications()
      })
    }
  }
}
</script>
