<!-- 拼团活动 -->
<template>
  <div>
    <div class="row">
      <el-form :model="queryForm" inline @submit.prevent>
        <el-form-item>
          <el-button type="primary" icon="Plus" @click="addGroupGoodsRef.show()">添加</el-button>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select v-model="queryForm.onlineStatus" style="width: 100px;">
            <el-option :label="item.label" :value="item.value" v-for="item in statusList" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐名称">
          <el-input v-model="queryForm.packageName" placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" :loading="tableData.loading" @click="searchHandle">搜索</el-button>
          <el-button icon="Refresh" :loading="tableData.loading" @click="refreshHandle">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="row">
      <el-table :data="tableData.list" stripe border v-loading="tableData.loading">
        <el-table-column label="套餐图片" width="120">
          <template v-slot="scope">
            <div class="wareImgs">
              <el-image :src="scope.row.images[0]" style="width: 100%;height: 100%;" fit="cover"
                :preview-src-list="scope.row.images" :initial-index="0" preview-teleported></el-image>
              <div class="num" v-if="scope.row.images.length > 1">
                +{{ scope.row.images.length }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="套餐名称" prop="packageName"></el-table-column>
        <el-table-column label="原价（元）" prop="originPrice"></el-table-column>
        <el-table-column label="价格（元）" prop="price"></el-table-column>
        <el-table-column label="分享期限（小时）" prop="expireHours"></el-table-column>
        <el-table-column label="可用时段" prop="useTimes">
          <template v-slot="scope">
            <div class="column">
              <span>{{ scope.row.useWeeks.join(',') }}</span>
              <span>{{ scope.row.useTimes }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="上架状态" prop="onlineStatus" width="100">
          <template v-slot="scope">
            <el-switch v-model="scope.row.onlineStatus" :active-value="1" :inactive-value="0"
              @change="editOnlineStatusAjax($event, scope.row)"
              :disabled="!(scope.row.shopId === shopInfo.id)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="200"></el-table-column>
        <el-table-column label="操作" width="150">
          <template v-slot="scope">
            <template v-if="scope.row.shopId === shopInfo.id">
              <template v-if="scope.row.onlineStatus">
                <el-button link type="primary" disabled>（下架后编辑/删除）</el-button>
              </template>
              <template v-else>
                <el-button link type="primary" @click="addGroupGoodsRef.show(scope.row)">编辑</el-button>
                <el-button link type="danger" @click="delHandle(scope.row)">删除</el-button>
              </template>
            </template>
            <template v-else>
              <el-button link type="primary" disabled>无权操作</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="row mt14">
      <el-pagination v-model:current-page="tableData.page" v-model:page-size="tableData.size"
        :page-sizes="[10, 20, 50, 100, 500]" background layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <addGroupGoods ref="addGroupGoodsRef" @success="searchHandle" />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import addGroupGoods from './addGroupGoods.vue';
import { packageGet, packageSureDel, packageOnline } from '@/api/market/ware'

const shopInfo = ref(null)

const addGroupGoodsRef = ref(null)

const statusList = ref([
  {
    label: '上架',
    value: 1,
    type: 'success'
  },
  {
    label: '下架',
    value: 0,
    type: 'info'
  },
])

const queryForm = reactive({
  onlineStatus: '',
  packageName: ''
})

// 搜索
function searchHandle() {
  tableData.page = 1
  packageGetAjax()
}

// 重置搜索
function refreshHandle() {
  queryForm.onlineStatus = ''
  queryForm.packageName = ''
  searchHandle()
}

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

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

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

// 拼团商品-列表
async function packageGetAjax(page = tableData.page) {
  try {
    tableData.loading = true
    const res = await packageGet({
      page: page,
      size: tableData.size,
      ...queryForm
    })
    tableData.list = res.records
    tableData.total = res.totalRow
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false
  }, 500);
}

// 修改状态
async function editOnlineStatusAjax(e, row) {
  try {
    await packageOnline({
      packageId: row.id,
      status: row.onlineStatus
    })
    packageGetAjax()
  } catch (error) {
    console.log(error);
  }
}

// 删除
function delHandle(row) {
  ElMessageBox.confirm('删除套餐推广所有未支付的订单都将自动取消，是否确定删除？', '注意', {
    confirmButtonText: '确认删除',
    type: 'danger'
  }).then(async () => {
    try {
      tableData.loading = true
      await packageSureDel(row.id)
      ElNotification({
        title: '注意',
        message: '已删除',
        type: 'success'
      })
      await packageGetAjax()
    } catch (error) {
      console.log(error);
    }
    tableData.loading = false
  }).catch(() => {
    form.value.isEnable = 1
  })
}

defineExpose({
  packageGetAjax
})

onMounted(() => {
  shopInfo.value = JSON.parse(localStorage.getItem('userInfo'))
  packageGetAjax()
})
</script>

<style scoped lang="scss">
.row {
  &.mt14 {
    margin-top: 14px;
  }
}

.wareImgs {
  position: relative;
  --size: 80px;
  width: var(--size);
  height: var(--size);
  border: 1px solid #ececec;
  border-radius: 4px;
  overflow: hidden;

  &:hover {
    cursor: pointer;
  }

  .num {
    padding: 0 4px;
    height: 16px;
    font-size: 10px;
    position: absolute;
    top: 0;
    right: 0;
    z-index: 10;
    border-radius: 0 0 0 4px;
    background-color: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(10px);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
  }
}
</style>