<template>
  <div class="reward-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">添加</el-button>
        <el-button icon="el-icon-delete" type="danger" @click="handleDelete">批量删除</el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input v-model.trim="queryForm.name" clearable placeholder="请输入规则名称" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table v-loading="listLoading" :data="list" :element-loading-text="elementLoadingText" @selection-change="setSelectRows">
      <el-table-column align="center" show-overflow-tooltip type="selection" width="55" />
      <el-table-column align="center" label="应用ID" prop="appId" show-overflow-tooltip width="120" />
      <el-table-column align="center" label="规则名称" prop="name" show-overflow-tooltip min-width="150" />
      <el-table-column align="center" label="场景" prop="scene" show-overflow-tooltip width="120" />
      <el-table-column align="center" label="描述" prop="description" show-overflow-tooltip min-width="200" />

      <el-table-column align="center" label="奖励内容" width="150">
        <template #default="{ row }">
          <div v-if="row.gainPoints">积分: +{{ row.gainPoints }}</div>
          <div v-if="row.gainExp">经验: +{{ row.gainExp }}</div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="限制规则" width="150">
        <template #default="{ row }">
          <div>
            类型:
            <el-tag size="mini" v-if="row.limitType === 'daily'">每日</el-tag>
            <el-tag size="mini" type="success" v-else-if="row.limitType === 'weekly'">每周</el-tag>
            <el-tag size="mini" type="warning" v-else-if="row.limitType === 'lifetime'">终身</el-tag>
            <el-tag size="mini" type="info" v-else>无限制</el-tag>
          </div>
          <div v-if="row.limitType !== 'none'">次数: {{ row.limitCount === -1 ? '无限制' : row.limitCount }}</div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" prop="isEnabled" width="100">
        <template #default="{ row }">
          <el-switch v-model="row.isEnabled" @change="handleStatusChange(row)"></el-switch>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="createdAt" width="160">
        <template #default="{ row }">
          {{ formatTime(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" show-overflow-tooltip width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <edit ref="edit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { getRewardRuleList, doDelete, toggleEnable } from '@/api/system/reward'
  import { formatTime } from '@/utils'
  import Edit from './components/RewardManagementEdit'

  export default {
    name: 'RewardManagement',
    components: { Edit },
    data() {
      return {
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: [],
        elementLoadingText: '正在加载...',
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          name: '',
        },
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      formatTime,
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        if (row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: [row.id] })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids: ids.split(',') })
              this.$baseMessage(msg, 'success')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      async handleStatusChange(row) {
        try {
          const { msg } = await toggleEnable(row.id, row.isEnabled)
          this.$baseMessage(msg, 'success')
        } catch (error) {
          row.isEnabled = !row.isEnabled
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        try {
          const { data } = await getRewardRuleList(this.queryForm)
          this.list = data.list
          this.total = data.totalCount
        } catch (error) {
          console.error(error)
        } finally {
          this.listLoading = false
        }
      },
    },
  }
</script>

<style scoped>
  .reward-management-container {
    padding: 20px;
  }
</style>
