<!-- 拼团活动 -->
<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-date-picker style="width: 300px" v-model="times" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
            @change="selectTimeChange"></el-date-picker>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="queryForm.wareName" 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="商品图片">
          <template v-slot="scope">
            <div class="wareImgs">
              <el-image :src="scope.row.wareImgs.split(',')[0]" style="width: 100%;height: 100%;" fit="cover"
                :preview-src-list="scope.row.wareImgs.split(',')" :initial-index="0" preview-teleported></el-image>
              <div class="num" v-if="scope.row.wareImgs.split(',').length > 1">
                +{{ scope.row.wareImgs.split(',').length }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="wareName"></el-table-column>
        <el-table-column label="原价（元）" prop="originalPrice"></el-table-column>
        <el-table-column label="拼团价（元）" prop="groupPrice"></el-table-column>
        <el-table-column label="成团期限（小时）" prop="groupTimeoutHour"></el-table-column>
        <el-table-column label="成团人数" prop="groupPeopleNum"></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)"></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-popconfirm title="确认要删除吗？" @confirm="delHandle(scope.row)">
                  <template #reference>
                    <el-button type="danger" link>删除</el-button>
                  </template>
                </el-popconfirm>
              </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 dayjs from 'dayjs';
import { ref, reactive } from 'vue'
import addGroupGoods from './addGroupGoods.vue';
import { getGbWarePage, editOnlineStatus, deleteGbWare } 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 times = ref([])

const selectTimeChange = (value) => {
  if (value && value.length === 2) {
    queryForm.startTime = dayjs(value[0]).format('YYYY-MM-DD 00:00:00');
    queryForm.endTime = dayjs(value[1]).format('YYYY-MM-DD 23:59:59');
  } else {
    queryForm.startTime = '';
    queryForm.endTime = '';
  }
};

const queryForm = reactive({
  onlineStatus: '',
  startTime: '',
  endTime: '',
  wareName: ''
})

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

// 重置搜索
function refreshHandle() {
  times.value = []
  queryForm.onlineStatus = ''
  queryForm.startTime = ''
  queryForm.endTime = ''
  queryForm.wareName = ''
  searchHandle()
}

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

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

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

// 拼团商品-列表
async function getGbWarePageAjax(page = tableData.page) {
  try {
    tableData.loading = true
    const res = await getGbWarePage({
      page: tableData.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 editOnlineStatus(row)
    getGbWarePageAjax()
  } catch (error) {
    console.log(error);
  }
}

// 删除
async function delHandle(row) {
  try {
    await deleteGbWare(row.id)
    getGbWarePageAjax()
  } catch (error) {
    console.log(error);
  }
}

defineExpose({
  getGbWarePageAjax
})

onMounted(() => {
  shopInfo.value = JSON.parse(localStorage.getItem('userInfo'))
  getGbWarePageAjax()
})
</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>