<template>
    <div class="p-2">
      <transition enter-active-class="animate__animated animate__fadeInDown" leave-active-class="animate__animated animate__fadeOutUp">
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
              <el-form-item label="店铺" prop="shopId">
                <el-select v-model="queryParams.shopId" placeholder="请选择店铺">
                  <el-option v-for="item in shopList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商家编码" prop="itemNumber">
                <el-input v-model="queryParams.itemNumber" placeholder="请输入编码" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>
  
      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['zhishu:shopGoodsPublished:remove']">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>
  
        <el-table v-loading="loading" :data="shopGoodsPublishedList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="图示" align="center" prop="bookPic" :show-overflow-tooltip="true">
            <template #default="{ row }">
              <el-image
                style="width: 50px;height: 50px"
                :src="row.bookPic"
                fit="scale-down"
                :preview-src-list="[row.bookPic]"
                preview-teleported
              >
                <template #error>
                  <div class="image-slot">
                    暂无
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="商家编码" align="left" prop="itemNumber"/>
  
          <el-table-column label="线上商品名称" align="left" prop="goodsName" :show-overflow-tooltip="true">
            <template #default="{ row }">
              <div class="truncate-cell">
                <el-link
                  v-if="row.shopType === 1"
                  type="primary"
                  :href="`https://mobile.yangkeduo.com/goods.html?goods_id=${row.onlineId}`"
                  target="_blank"
                  :underline="false"
                >
                  {{ row.goodsName }}
                </el-link>
  
                <el-link
                  v-else-if="row.shopType === 2"
                  type="primary"
                  :href="`https://book.kongfz.com/${row.mallId}/${row.onlineId}`"
                  target="_blank"
                  :underline="false"
                >
                  {{ row.goodsName }}
                </el-link>
              </div>
            </template>
          </el-table-column>
  
          <el-table-column label="店铺" align="left" prop="shopName"/>
  
          <el-table-column label="线上商品/规格ID" align="left" prop="onlineId"/>
  
          <el-table-column label="状态" align="left" prop="status">
            <template #default="{ row }">
              <span v-if="row.status==0">在售</span>
              <span v-else>未售</span>
            </template>
          </el-table-column>
  
        </el-table>
  
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
  
    </div>
  </template>
  
  <script setup name="ShopGoodsPublished">
  import { getShopGoodsPublishedList, deleteShopGoodsPublished } from '@/api/modules/shopGoodsPublished';
  import { getListShop } from '@/api/zhishu/shop';
  import { ref, reactive, toRefs, onMounted } from 'vue';
  import { depotNameList } from '@/api/zhishu/shelves';
  import { ElMessage, ElMessageBox } from 'element-plus';
  
  // 响应式数据
  const shopGoodsPublishedList = ref([]);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  
  const queryFormRef = ref();
  
  const initFormData = {
    id: undefined,
    shopGoodsId: undefined,
    shopId: undefined,
    goodsName: undefined,
    shopName: undefined,
    platformId: undefined,
    status: undefined,
    itemNumber: undefined,
    bookPic: undefined,
    isbn: undefined,
    conditionCode: undefined,
    price: undefined,
    createTime: undefined,
    updateTime: undefined
  }
  
  const data = reactive({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      shopGoodsId: undefined,
      shopId: undefined,
      goodsName: undefined,
      shopName: undefined,
      platformId: undefined,
      status: undefined,
      itemNumber: undefined,
      bookPic: undefined,
      isbn: undefined,
      conditionCode: undefined,
      price: undefined,
      createTime: undefined,
      updateTime: undefined,
      depotId: undefined,
      params: {}
    },
    rules: {
      id: [
        { required: true, message: "主键不能为空", trigger: "blur" }
      ],
    }
  });
  
  const { queryParams, form, rules } = toRefs(data);
  
  // 查询记录发布数据列表
  const getList = async () => {
    loading.value = true;
    try {
      const res = await getShopGoodsPublishedList(queryParams.value);
      shopGoodsPublishedList.value = res.data.rows || res.rows || [];
      total.value = res.data.total || res.total || 0;
    } catch (error) {
      console.error('获取列表失败:', error);
      ElMessage.error('获取列表失败');
    } finally {
      loading.value = false;
    }
  }
  
  const depotList = ref([]);
  const selectedId = ref(null);
  
  const handleDepotChange = (val) => {
    queryParams.value.depotId = val?.id || null;
  }
  
  const loadData = async () => {
    loading.value = true;
    try {
      const res = await depotNameList();
      depotList.value = res.rows || [];
    } catch (error) {
      console.error('加载数据失败:', error);
    } finally {
      loading.value = false;
    }
  }
  
  const conditionCodeTypes = [
    { value: '1', label: '一品' },
    { value: '2', label: '二品' },
    { value: '3', label: '三品' },
    { value: '4', label: '四品' },
    { value: '5', label: '五品' },
    { value: '6', label: '六品' },
    { value: '6.5', label: '六五品' },
    { value: '7', label: '七品' },
    { value: '7.5', label: '七五品' },
    { value: '8', label: '八品' },
    { value: '8.5', label: '八五品' },
    { value: '9', label: '九品' },
    { value: '9.5', label: '九五品' },
    { value: '10', label: '全新' }
  ];
  
  // 搜索按钮操作
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }
  
  // 重置按钮操作
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }
  
  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  
  // 删除按钮操作
  const handleDelete = async (row) => {
    const _ids = row?.id || ids.value;
    try {
      await ElMessageBox.confirm('是否确认删除记录发布数据编号为"' + _ids + '"的数据项？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      
      await deleteShopGoodsPublished(_ids);
      ElMessage.success("删除成功");
      await getList();
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error);
        ElMessage.error('删除失败');
      }
    } finally {
      loading.value = false;
    }
  }
  
  // 店铺列表
  const shopList = ref([]);
  
  const getShopList = async () => {
    try {
      const res = await getListShop();
      const data = res.data || res;
      
      if (!data || data.length === 0) {
        shopList.value = [];
      } else {
        shopList.value = data.map(item => ({
          value: item.id,
          label: item.shopName
        }));
      }
    } catch (error) {
      console.error('获取店铺列表失败:', error);
      ElMessage.error('获取店铺列表失败');
    }
  }
  
  onMounted(() => {
    getList();
    loadData();
    getShopList();
  });
  </script>
  
  <style scoped>
  /* 调整表头字体大小 */
  :deep(.el-table__header) th .cell {
    font-size: 18px;
    font-weight: bold;
  }
  
  /* 调整表格内容字体大小 */
  .el-table {
    font-size: 17px !important;
  }
  
  .truncate-cell {
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 12px;
  }
  </style>