<script setup>
import { ElMessageBox, ElMessage } from 'element-plus'
import LiveProductCategory from '@/components/LiveProductCategory.vue'
import { getProductList, deleteProduct } from '../api'

const appList = ref(null)
// 刷新
const handleRefresh = () => {
  appList.value?.refetch()
}

const listParams = reactive({ name: '', live_commodity_type_id: '' })

// 列表配置
const listOptions = computed(() => {
  return {
    remote: {
      httpRequest: getProductList,
      params: listParams,
      beforeRequest(params, isReset) {
        if (isReset) listParams.live_commodity_type_id = ''
        params.live_commodity_type_id = listParams.live_commodity_type_id
        return params
      },
      callback(data) {
        const list = data.list?.map((item) => {
          item.picture_addreses = JSON.parse(item.picture_addreses)
          item.picture_url = item.picture_addreses[0]?.url
          item.picture_url_list = item.picture_addreses?.filter((i) => i).map((i) => i.url)
          return item
        })
        return { ...data, list }
      },
    },
    filters: [
      { label: '商品品类', prop: 'live_commodity_type_id', slots: 'filter-category' },
      { label: '商品名称', prop: 'title', type: 'input' },
    ],
    columns: [
      { label: '序号', type: 'index', width: 60 },
      { label: '商品主图', prop: 'picture_addreses', slots: 'table-picture', width: 140 },
      { label: '商品标题', prop: 'title' },
      { label: '所属商品品类', prop: 'live_commodity_type_full_name' },
      { label: '更新时间', prop: 'updated_time' },
      { label: '操作', slots: 'table-x', width: 200 },
    ],
  }
})

const handleRemove = async (row) => {
  await ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示')
  await deleteProduct({ id: row.id })
  ElMessage.success('删除成功')
  appList.value?.refetch()
}
</script>

<template>
  <AppCard title="商品管理">
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-button type="primary">
          <router-link to="management/add">添加商品</router-link>
        </el-button>
      </template>
      <template #filter-category>
        <LiveProductCategory v-model="listParams.live_commodity_type_id" @change="handleRefresh"></LiveProductCategory>
      </template>
      <template #table-picture="{ row }">
        <el-image
          fit="cover"
          preview-teleported
          :src="row.picture_url"
          :previewSrcList="row.picture_url_list"
          style="width: 100px; height: 100px"></el-image>
      </template>
      <template #table-x="{ row }">
        <el-button text type="primary">
          <router-link :to="{ path: 'management/view', query: { id: row.id } }">查看</router-link>
        </el-button>
        <el-button text type="primary">
          <router-link :to="{ path: 'management/update', query: { id: row.id } }">编辑</router-link>
        </el-button>
        <el-button text type="primary" @click="handleRemove(row)">删除</el-button>
      </template>
    </AppList>
  </AppCard>
</template>
