<!-- 公众号推送列表 -->
<template>
  <div class="gyq_container">
    <div class="gyq_content">
      <div class="row">
        <el-form inline>
          <el-form-item>
            <el-select v-model="querForm.status" style="width: 300px;">
              <el-option value="" label="全部"></el-option>
              <el-option v-for="item in statusList" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getTableData">搜索</el-button>
            <el-button type="warning" icon="Refresh" :loading="tableData.loading"
              @click="reseQueryHandle">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button type="primary" icon="Plus" @click="addTaskRef?.show()">添加任务</el-button>
      </div>
      <div class="row">
        <el-table :data="tableData.list" stripe border v-loading="tableData.loading">
          <el-table-column label="ID" prop="id" width="80"></el-table-column>
          <el-table-column label="推送任务" min-width="300">
            <template #default="scope">
              <div class="column">
                <div>商家名称：{{ scope.row.shopName }}</div>
                <div>活动描述：{{ scope.row.activityDetail }}</div>
                <div>开始时间：{{ scope.row.activityTime }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="优惠券信息" prop="coupon" width="160">
            <template #default="scope">
              <div class="column" v-if="scope.row.coupon">
                <div v-for="item in JSON.parse(scope.row.coupon)" :key="item.id">
                  <el-tag effect="dark" round disable-transitions :type="getRandomStatus()">
                    {{ item.title }} x{{ item.num }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="发送对象" prop="userType" width="100">
            <template #default="scope">
              {{ userTypeFilters(scope.row.userType).label }}
            </template>
          </el-table-column>
          <el-table-column label="发送人数「预计」" prop="estimateNum" width="150"></el-table-column>
          <el-table-column label="发送时间" prop="sendTime" width="200"></el-table-column>
          <el-table-column label="状态" prop="status" width="100">
            <template #default="scope">
              <el-tag disable-transitions :type="statusListFilter(scope.row.status).type">
                {{ statusListFilter(scope.row.status).label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="200"></el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button link type="primary" v-if="scope.row.status != 2 && scope.row.status != 1"
                @click="addTaskRef.show(scope.row)">编辑</el-button>
              <el-popconfirm title="确认要删除吗？" @confirm="deleteHandle(scope.row)"
                v-if="scope.row.status != 2 && scope.row.status != 1">
                <template #reference>
                  <el-button type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="row">
        <el-pagination v-model:current-page="tableData.page" v-model:page-size="tableData.size"
          :page-sizes="[100, 200, 300, 400]" background layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <addTask ref="addTaskRef" @success="getTableData" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import addTask from './components/addTask.vue';
import { acPushEventGet, acPushEventDel } from '@/api/coupon'

function getRandomStatus() {
  const statusList = ['primary', 'success', 'warning', 'danger'];
  // 生成0到数组长度之间的随机整数索引
  const randomIndex = Math.floor(Math.random() * statusList.length);
  // 返回随机索引对应的元素
  return statusList[randomIndex];
}

const addTaskRef = ref(null)

const tableData = reactive({
  loading: false,
  page: 1,
  size: 10,
  list: []
})

// 发送对象
function userTypeFilters(status) {
  const m = [
    {
      value: 1,
      label: '全部用户',
    },
    {
      value: 2,
      label: '范围用户',
    },
    {
      value: 3,
      label: '指定用户',
    },
  ]
  return m.find(item => item.value == status)
}

const querForm = ref({
  status: ''
})

// 重置
function reseQueryHandle() {
  querForm.value.status = ''
  getTableData()
}

// 状态列表
const statusList = ref([
  {
    value: 0,
    label: '待发送',
    type: 'info'
  },
  {
    value: 1,
    label: '发送中...',
    type: 'warning'
  },
  {
    value: 2,
    label: '发送成功',
    type: 'success'
  },
  {
    value: -1,
    label: '失败 ',
    type: 'danger'
  },
])

// 筛选状态
function statusListFilter(status) {
  return statusList.value.find(item => item.value == status)
}

// 删除
async function deleteHandle(row) {
  try {
    tableData.loading = true;
    await acPushEventDel(row.id);
    ElNotification({
      title: '注意',
      message: '已删除',
      type: 'success'
    })
    getTableData();
  } catch (err) {
    console.log(err);
  }
}

// 分页大小发生变化
function handleSizeChange(e) {
  tableData.pageSize = e;
  getTableData();
}

// 分页发生变化
function handleCurrentChange(e) {
  tableData.page = e;
  getTableData();
}

// 获取列表
const getTableData = async () => {
  try {
    tableData.loading = true;
    const res = await acPushEventGet({
      page: tableData.page,
      size: tableData.size,
      status: querForm.value.status
    });
    tableData.list = res.records;
    tableData.total = res.totalRow;
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false;
  }, 500);
}

// 添加模板，并且默认选中模板
function useTemplate(item) {
  addTaskRef.value?.show(null, item)
}

defineExpose({
  useTemplate
})

onMounted(() => {
  getTableData();
});
</script>

<style scoped lang="scss">
.gyq_container {
  padding: 14px;

  .gyq_content {
    padding: 14px;
    background-color: #fff;
    border-radius: 8px;
  }
}

.row {
  padding-top: 14px;
}

.column {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
</style>