<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="voteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="选项A" align="center" prop="optionA" min-width="100" />
      <el-table-column label="选项B" align="center" prop="optionB" min-width="100" />
      <el-table-column label="可投票时间(分)" align="center" prop="duration" width="120" />
      <el-table-column label="下架时间" align="center" prop="hideAt" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.hideAt ? parseTime(scope.row.hideAt) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <span>{{ statusLabel(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="票数" align="center" width="120">
        <template slot-scope="scope">
          <span>A:{{ scope.row.voteACount || 0 }} / B:{{ scope.row.voteBCount || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获胜选项" align="center" prop="winner" width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.winner || (String(scope.row.status) === '2' ? '平局' : '-') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-if="String(scope.row.status) === '0'"
            size="mini"
            type="text"
            @click="handleStart(scope.row)"
          >开始</el-button>
          <el-button
            v-if="String(scope.row.status) === '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="String(scope.row.status) === '1'"
            size="mini"
            type="text"
            @click="handleEnd(scope.row)"
          >结束</el-button>
          <el-button
            v-if="String(scope.row.status) === '0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</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="520px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="投票描述" prop="description">
          <el-input v-model="form.description" maxlength="20" show-word-limit placeholder="请输入投票描述，最多20字" />
        </el-form-item>
        <el-form-item label="选项A" prop="optionA">
          <el-input v-model="form.optionA" maxlength="12" show-word-limit placeholder="请输入选项A，最多12字" />
        </el-form-item>
        <el-form-item label="选项B" prop="optionB">
          <el-input v-model="form.optionB" maxlength="12" show-word-limit placeholder="请输入选项B，最多12字" />
        </el-form-item>
        <el-form-item label="可投票时间" prop="duration">
          <el-input-number v-model="form.duration" :min="1" controls-position="right" />
          <span style="margin-left:8px;color:#909399">分钟</span>
        </el-form-item>
        <el-form-item label="结束后下架" prop="hideDuration">
          <el-input-number v-model="form.hideDuration" :min="0" controls-position="right" />
          <span style="margin-left:8px;color:#909399">分钟</span>
        </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 { listVote, getVote, addVote, updateVote, delVote, startVote, endVote } from '@/api/live/vote'

export default {
  name: 'LiveVote',
  data() {
    const lenValidator = (max, label) => (rule, value, callback) => {
      if (!value || !String(value).trim()) {
        callback(new Error(label + '不能为空'))
      } else if (String(value).trim().length > max) {
        callback(new Error(label + '不能超过' + max + '字'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      showSearch: true,
      total: 0,
      voteList: [],
      title: '',
      open: false,
      liveId: null,
      ids: [],
      multiple: true,
      statusMap: {
        0: '未开始',
        1: '进行中',
        2: '已结束'
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: null
      },
      form: {},
      rules: {
        description: [{ required: true, validator: lenValidator(20, '投票描述'), trigger: 'blur' }],
        optionA: [{ required: true, validator: lenValidator(12, '选项A'), trigger: 'blur' }],
        optionB: [{ required: true, validator: lenValidator(12, '选项B'), trigger: 'blur' }],
        duration: [{ required: true, message: '可投票时间不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.liveId = this.$route.params.liveId || this.$route.query.liveId
    this.queryParams.liveId = this.liveId
    this.getList()
  },
  methods: {
    statusLabel(status) {
      return this.statusMap[status] || '-'
    },
    getList() {
      this.loading = true
      listVote(this.queryParams).then(response => {
        this.voteList = response.rows || []
        this.total = response.total
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        liveId: this.liveId,
        description: null,
        optionA: null,
        optionB: null,
        duration: 5,
        hideDuration: 0
      }
      this.resetForm('form')
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加投票'
    },
    handleUpdate(row) {
      if (String(row.status) !== '0') {
        this.msgError('只能修改未开始的投票')
        return
      }
      this.reset()
      getVote(row.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,
          liveId: this.liveId,
          description: String(this.form.description).trim(),
          optionA: String(this.form.optionA).trim(),
          optionB: String(this.form.optionB).trim()
        }
        if (data.id != null) {
          updateVote(data).then(() => {
            this.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        } else {
          addVote(data).then(() => {
            this.msgSuccess('新增成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    handleStart(row) {
      this.$confirm('确认开始该投票？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return startVote(row.id)
      }).then(() => {
        this.msgSuccess('已开始')
        this.getList()
      }).catch(() => {})
    },
    handleEnd(row) {
      this.$confirm('确认结束该投票？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return endVote(row.id)
      }).then(() => {
        this.msgSuccess('已结束')
        this.getList()
      }).catch(() => {})
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 删除（单条/批量），仅未开始可删 */
    handleDelete(row) {
      const rows = row && row.id != null
        ? [row]
        : this.voteList.filter(item => this.ids.indexOf(item.id) > -1)
      if (!rows.length) {
        this.msgError('请选择要删除的数据')
        return
      }
      const invalid = rows.filter(item => String(item.status) !== '0')
      if (invalid.length) {
        this.msgError('只能删除未开始的投票，请取消选中进行中/已结束的项')
        return
      }
      const ids = rows.map(item => item.id)
      this.$confirm('是否确认删除投票编号为"' + ids.join(',') + '"的数据项？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delVote(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    }
  }
}
</script>
