<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.query"
        placeholder="请输入检索词"
        style="width: 60%;"
        class="filter-item"
        @keyup.enter.native="fetchData()"
      />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="fetchData">
        检索
      </el-button>
      <el-button
        class="filter-item"
        style="margin: 0 10px 20px 0; float: right;"
        type="success"
        icon="el-icon-circle-plus-outline"
        @click="handleCreateOrUpdate('create')"
      >
        新建
      </el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="index" label="序号" align="center" fixed width="60" />
      <el-table-column label="名称" align="center" fixed width="150">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" width="300">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="90">
        <template slot-scope="{row}">
          <el-dropdown @command="handleCommand">
            <el-button size="small" type="primary" @click.stop="{}">
              操作<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{row: row, command: 'update'}">更新/查看</el-dropdown-item>
              <el-dropdown-item :command="{row: row, command: 'manage'}">管理营养素</el-dropdown-item>
              <el-dropdown-item :disabled="!canUpdate(row.userId)" :command="{row: row, command: 'moveUp'}">上移</el-dropdown-item>
              <el-dropdown-item :disabled="!canUpdate(row.userId)" :command="{row: row, command: 'moveDown'}">下移</el-dropdown-item>
              <el-dropdown-item :disabled="!canUpdate(row.userId)" :command="{row: row, command: 'moveTop'}">置顶</el-dropdown-item>
              <el-dropdown-item :disabled="!canUpdate(row.userId)" :command="{row: row, command: 'moveBottom'}">置底</el-dropdown-item>
              <el-dropdown-item :disabled="!canUpdate(row.userId)" :command="{row: row, command: 'delete'}">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchData"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="params" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="params.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="params.description" placeholder="请输入描述" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :disabled="dialogStatus === 'update' && !canUpdate(params.userId)" @click="createOrUpdateData">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import Pagination from '@/components/Pagination'
import { getNutrientTemplates, createTemplate, updateSort, updateTemplate, removeTemplate } from '@/api/nutrientTemplate'

export default {
  name: 'NutrientTemplateList',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      listQuery: {
        query: '',
        pageNum: 1,
        pageSize: 20
      },
      listLoading: false,
      list: [],
      total: 0,
      textMap: {
        update: '更新',
        create: '新建'
      },
      dialogStatus: '',
      dialogFormVisible: false,
      rules: {},
      params: {}
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getNutrientTemplates(this.listQuery).then(res => {
        this.list = res.data.list
        this.total = res.data.count
        this.listLoading = false
      }).catch(res => {
        this.$message.error('获取数据失败')
        this.listLoading = false
      })
    },
    handleCreateOrUpdate(type, row) {
      this.dialogStatus = type
      this.params = type === 'create' ? {} : Object.assign(row, {})
      this.dialogFormVisible = true
    },
    updateSort(row, type) {
      updateSort(row.id, { type }).then(res => {
        this.fetchData()
        this.$notify.success('提交成功')
      }).catch(res => {
        this.fetchData()
        this.$message.error(res.data.message)
      })
    },
    handleDelete(row) {
      removeTemplate(row.id).then(res => {
        this.fetchData()
        this.$notify.success('提交成功')
      }).catch(res => {
        this.fetchData()
        this.$message.error(res.data.message)
      })
    },
    createOrUpdateData() {
      const resultPromise = this.dialogStatus === 'create' ? createTemplate(this.params) : updateTemplate(this.params.id,
        this.params)
      resultPromise.then(res => {
        this.$notify.success('提交成功')
        this.fetchData()
        this.dialogFormVisible = false
      }).catch(res => {
        this.$message.error(res.data.message)
        this.fetchData()
      })
    },
    canUpdate(userId) {
      return store.getters.isAdmin || store.getters.userId === userId
    },
    manageNutrients(row) {
      this.$router.push({ path: `nutrient-template/${row.id}/detail` })
    },
    handleCommand(data) {
      switch (data.command) {
        case 'update':
          this.handleCreateOrUpdate('update', data.row)
          break
        case 'manage':
          this.manageNutrients(data.row)
          break
        case 'moveUp':
          this.updateSort(data.row, 0)
          break
        case 'moveDown':
          this.updateSort(data.row, 1)
          break
        case 'moveTop':
          this.updateSort(data.row, 2)
          break
        case 'moveBottom':
          this.updateSort(data.row, 3)
          break
        case 'delete':
          this.handleDelete(data.row)
          break
      }
    }
  }
}
</script>

<style scoped>

</style>
