<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="内容" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入评论文案"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['live:quickComment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['live:quickComment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5" v-if="sortDirty">
        <el-button
          type="warning"
          plain
          icon="el-icon-check"
          size="mini"
          :loading="sortLoading"
          @click="handleSaveSort"
          v-hasPermi="['live:quickComment:edit']"
        >保存顺序</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="dragTable"
      border
      v-loading="loading"
      :data="quickCommentList"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="" width="50" align="center" class-name="allowDrag">
        <template>
          <i class="el-icon-rank" style="cursor: move;"></i>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center" prop="content" :show-overflow-tooltip="true" />
      <el-table-column label="排序" align="center" prop="sortOrder" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['live:quickComment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['live:quickComment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="3"
            maxlength="30"
            show-word-limit
            placeholder="请输入评论文案，最多30字"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" controls-position="right" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import {
  listQuickComment,
  getQuickComment,
  delQuickComment,
  addQuickComment,
  updateQuickComment,
  sortQuickComment
} from '@/api/live/quickComment'

export default {
  name: 'QuickComment',
  data() {
    const validateContent = (rule, value, callback) => {
      if (!value || !String(value).trim()) {
        callback(new Error('内容不能为空'))
      } else if (String(value).trim().length > 30) {
        callback(new Error('内容不能超过30字'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      sortLoading: false,
      sortDirty: false,
      ids: [],
      multiple: true,
      showSearch: true,
      total: 0,
      quickCommentList: [],
      title: '',
      open: false,
      sortable: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null
      },
      form: {},
      rules: {
        content: [{ required: true, validator: validateContent, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy()
      this.sortable = null
    }
  },
  methods: {
    getList() {
      this.loading = true
      listQuickComment(this.queryParams).then(response => {
        this.quickCommentList = response.rows || []
        this.total = response.total
        this.loading = false
        this.sortDirty = false
        this.$nextTick(() => {
          this.initSortable()
        })
      })
    },
    initSortable() {
      if (this.sortable) {
        this.sortable.destroy()
        this.sortable = null
      }
      const table = this.$refs.dragTable
      if (!table || !table.$el) {
        return
      }
      const el = table.$el.querySelector('.el-table__body-wrapper tbody')
      if (!el) {
        return
      }
      this.sortable = Sortable.create(el, {
        handle: '.allowDrag',
        animation: 150,
        onEnd: evt => {
          if (evt.oldIndex === evt.newIndex) {
            return
          }
          const currRow = this.quickCommentList.splice(evt.oldIndex, 1)[0]
          this.quickCommentList.splice(evt.newIndex, 0, currRow)
          this.quickCommentList.forEach((item, index) => {
            item.sortOrder = index
          })
          this.sortDirty = true
        }
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        content: null,
        sortOrder: 0
      }
      this.resetForm('form')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加一键评论'
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getQuickComment(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改一键评论'
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        const data = {
          ...this.form,
          content: String(this.form.content).trim()
        }
        if (data.id != null) {
          updateQuickComment(data).then(() => {
            this.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        } else {
          addQuickComment(data).then(() => {
            this.msgSuccess('新增成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除选中的一键评论？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delQuickComment(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleSaveSort() {
      const payload = this.quickCommentList.map((item, index) => ({
        id: item.id,
        sortOrder: index
      }))
      this.sortLoading = true
      sortQuickComment(payload).then(() => {
        this.msgSuccess('排序保存成功')
        this.sortDirty = false
        this.getList()
      }).finally(() => {
        this.sortLoading = false
      })
    }
  }
}
</script>
