<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.project_name" placeholder="服务名称" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="getProjects"/>
      <el-select v-model="listQuery.type" placeholder="服务类型" clearable style="width: 200px" class="filter-item" >
        <el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <el-select v-model="listQuery.is_active" placeholder="是否服役" clearable style="width: 200px" class="filter-item" >
        <el-option v-for="item in avtiveOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" >
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getProjects">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <el-table
      :data="proconfigs"
      fit
      max-height="700"
      size="medium"
      style="width: 100%;">

      <el-table-column label="ID" type="index" align="center" width="55"/>

      <el-table-column label="服务名称" align="center">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.project_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="服务描述" prop="des" align="center"/>

      <el-table-column label="线上域名" prop="host_name" align="center"/>

      <el-table-column label="负责人" width="80px" prop="auth" align="center"/>

      <el-table-column label="状态" width="90px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.is_active | statusFilter">{{ row.is_active | activeFileter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="部署容器" width="90px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.deploy_to_testenv | statusFilter">{{ row.deploy_to_testenv | deployFileter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="API地址"
        align="center"
        width="80px">
        <template slot-scope="{row}">
          <el-tooltip :content="row.api" class="item" effect="dark" placement="top">
            <el-button v-show="row.api" type="primary" icon="el-icon-time" circle @click="openUrl(row.api)"/>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column
        label="DDL地址"
        width="80px"
        align="center">
        <template slot-scope="{row}">
          <el-tooltip :content="row.ddl" class="item" effect="dark" placement="top">
            <el-button v-show="row.ddl" type="success" icon="el-icon-time" circle @click="openUrl(row.ddl)"/>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column
        label="Wiki"
        width="80px"
        align="center">
        <template slot-scope="{row}">
          <el-tooltip :content="row.wiki" class="item" effect="dark" placement="top">
            <el-button v-show="row.wiki" type="warning" icon="el-icon-time" circle @click="openUrl(row.wiki)"/>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column
        label="Git地址"
        width="80px"
        align="center">
        <template slot-scope="{row}">
          <el-tooltip :content="row.git_path" class="item" effect="dark" placement="top">
            <el-button type="info" icon="el-icon-tickets" circle />
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" width="70" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
          <!-- <el-button size="mini" type="danger" @click="handleDelete(row)">{{ $t('table.delete') }}
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="115px" style="width: 90%; margin-left:40px;">
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="Git地址" prop="git_path" style="width: 100%;">
          <el-input v-model="temp.git_path"/>
        </el-form-item>

        <el-form-item label="负责人" style="width: 100%;" prop="auth">
          <el-input v-model="temp.auth"/>
        </el-form-item>
        <el-form-item label="服务描述" style="width: 100%;">
          <el-input :autosize="{ minRows: 1, maxRows: 4}" v-model="temp.des" type="textarea" placeholder="Please input"/>
        </el-form-item>
        <el-form-item label="API" style="width: 100%;">
          <el-input v-model="temp.api"/>
        </el-form-item>
        <el-form-item label="数据库DDL" style="width: 100%;">
          <el-input v-model="temp.ddl"/>
        </el-form-item>
        <el-form-item label="Wiki" style="width: 100%;">
          <el-input v-model="temp.wiki"/>
        </el-form-item>

        <el-form-item label="是否服役" prop="is_active">
          <el-select v-model="temp.is_active" class="filter-item" placeholder="Please select">
            <el-option v-for="item in avtiveOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>

        <el-form-item label="是否部署容器" prop="deploy_to_testenv">
          <el-select v-model="temp.deploy_to_testenv" class="filter-item" placeholder="Please select">
            <el-option v-for="item in deployOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="temp.deploy_to_testenv" label="线上域名" prop="host_name" style="width: 100%;">
          <el-input v-model="temp.host_name"/>
        </el-form-item>

        <el-form-item v-if="temp.deploy_to_testenv" label="配置文件路径" style="width: 100%;">
          <el-input v-model="temp.config_path"/>
        </el-form-item>
        <el-form-item v-if="temp.deploy_to_testenv" label="Build文件路径" style="width: 100%;">
          <el-input v-model="temp.jar_path"/>
        </el-form-item>
        <el-form-item v-if="temp.deploy_to_testenv" label="日志路径" style="width: 100%;">
          <el-input v-model="temp.log_path"/>
        </el-form-item>
        <el-form-item v-if="temp.deploy_to_testenv" label="部署命令" style="width: 100%;">
          <el-input v-model="temp.build_command"/>
        </el-form-item>

        <el-form-item v-if="temp.deploy_to_testenv" label="Sonar扫描" prop="sonar">
          <el-select v-model="temp.sonar" class="filter-item" placeholder="Please select">
            <el-option v-for="item in deployOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>

        <el-form-item v-show="temp.type==='java' && temp.deploy_to_testenv" label="Database" style="width: 100%;">
          <el-input :autosize="{ minRows: 1, maxRows: 2}" v-model="temp.database" type="textarea" placeholder="依赖的数据库，库名与库名之间使用空格分隔"/>
        </el-form-item>

        <el-alert
          v-show="temp.type==='java' && temp.deploy_to_testenv"
          style="margin-bottom:20px"
          title="编辑启动命令需要管理员权限"
          type="warning"/>

        <el-form-item v-show="temp.type==='java' && temp.deploy_to_testenv" label="启动命令" style="width: 100%;">
          <el-input :autosize="{ minRows: 2, maxRows: 10}" v-model="temp.start_command" :disabled="disabled" type="textarea" placeholder="Please input"/>
        </el-form-item>

        <el-card v-permission="['admin']" v-if="temp.deploy_to_testenv" class="box-card">
          <div slot="header" >
            <span>Kubernetes设置</span>
          </div>
          <el-form :inline="true" size="medium" >
            <el-form-item label="CPU request" style="width:40%" prop="cpuRequest">
              <el-input v-model="temp.cpuRequest" />
            </el-form-item>
            <el-form-item label="CPU limit" style="width:40%" prop="cpuLimit">
              <el-input v-model="temp.cpuLimit" />
            </el-form-item>
            <el-form-item label="内存 request" style="width:40%" prop="memRequest">
              <el-input v-model="temp.memRequest" />
            </el-form-item>
            <el-form-item label="内存 limit" style="width:40%" prop="memLimit">
              <el-input v-model="temp.memLimit" />
            </el-form-item>
          </el-form>
        </el-card>

      </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.project_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 { getProjects, saveProject, deleteProject, getType } from '@/api/proconfig'
import waves from '@/directive/waves' // Waves directive
import permission from '@/directive/permission/index.js' // 权限判断指令

const avtiveOptions = [
  { key: true, display_name: '服役中' },
  { key: false, display_name: '退役了' }
]

const activeKeyValue = avtiveOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const deployOptions = [
  { key: true, display_name: '是' },
  { key: false, display_name: '否' }
]

const deployKeyValue = deployOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  directives: { waves, permission },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    },
    activeFileter(status) {
      return activeKeyValue[status]
    },
    deployFileter(status) {
      return deployKeyValue[status]
    }
  },
  data() {
    return {
      total: 0,
      listQuery: {
        // type: 'ui',
        is_active: true,
        sort: '+project_name'
      },
      typeOptions: [],
      sortOptions: [{ label: '服务名升序', key: '+project_name' }, { label: '服务名降序', key: '-project_name' }],
      temp: {
      },
      dialogFormVisible: false,
      dialogDeleteVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      proconfigs: [],
      avtiveOptions,
      deployOptions,
      disabled: undefined,
      rules: {
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        git_path: [{ required: true, message: '请输入', trigger: 'change' }],
        is_active: [{ required: true, message: '请选择', trigger: 'change' }],
        deploy_to_testenv: [{ required: true, message: '请选择', trigger: 'change' }],
        host_name: [{ required: true, message: '请输入', trigger: 'change' }],
        auth: [{ required: true, message: '请输入', trigger: 'change' }]
      }
    }
  },
  watch: {
    listQuery: {
      handler: 'getProjects',
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getType()
    this.disabled = !this.$store.getters.roles.includes('admin')
  },
  methods: {
    getProjects() {
      for (const prop in this.listQuery) {
        if (this.listQuery[prop] === '') {
          delete this.listQuery[prop]
        }
      }
      getProjects(this.listQuery).then(res => {
        this.proconfigs = res.data
      })
    },

    openUrl(data) {
      window.open(`${data}`, '_blank')
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'project_name') {
        this.sortByName(order)
      }
    },
    sortByName(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+project_name'
      } else {
        this.listQuery.sort = '-project_name'
      }
      this.getProjects()
    },

    getType() {
      getType().then((res) => {
        this.typeOptions = res.data.map(i => {
          return { key: i._id, display_name: i._id.toUpperCase() }
        })
      })
    },

    handleCreate() {
      this.temp = {}
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveProject(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
            this.getProjects()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

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

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