<template>
  <el-container class="goods-select">
    <el-container>
      <el-header class="goods-search">
        <sa-search-simple :searchFields="searchFields" :defaultValues="defaultSearchValues"
          v-model="currentSearchParams" @search="handleSearch" @reset="handleReset" />
      </el-header>
      <el-main v-loading="loading">
        <el-table class="sa-table" ref="multipleTableRef" :data="table.list" @select="selectRow" @select-all="selectAll"
          stripe>
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column v-if="modal.params.multiple" type="selection" width="48"></el-table-column>
          <el-table-column prop="id" :label="t('modules.goods.goodsNumber')" align="center" />
          <el-table-column :label="t('modules.goods.goodsInfo')">
            <template #default="scope">
              <div class="sa-flex">
                <el-image :src="scope.row.image" class="goods-image" fit="cover" />
                <div>
                  <div class="goods-title">{{ scope.row.storeName }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="t('form.price')" align="center">
            <template #default="scope">
              <div>{{ t('modules.goods.originalPrice') }}: ৳{{ scope.row.otPrice }}</div>
              <div>{{ t('modules.goods.onlinePrice') }}: ৳{{ scope.row.price }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="stock" :label="t('modules.goods.goodsStock')" min-width="100" align="center">
            <template #default="scope">
              {{ scope.row.stock || 0 }}
            </template>
          </el-table-column>
          <el-table-column v-if="!modal.params.multiple" :label="t('common.actions')" width="80">
            <template #default="scope">
              <template v-if="modal.params.ftype == 'score_shop'">
                <span v-if="scope.row.is_score_shop">{{ t('modules.goods.alreadyJoined') }}</span>
                <el-button v-if="!scope.row.is_score_shop" link type="primary" @click="singleSelect(scope.row.id)">{{
                  t('modules.goods.join') }}</el-button>
              </template>
              <template v-else>
                <el-button link type="primary" @click="singleSelect(scope.row.id)">{{
                  t('common.select')
                }}</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="sa-footer--submit" :class="modal.params.multiple ? 'sa-row-between' : 'sa-row-right'">
        <sa-pagination :pageData="pageData" layout="total, prev, pager, next" @updateFn="getData" />
        <el-button v-if="modal.params.multiple" type="primary" @click="confirm">{{
          t('common.confirm')
        }}</el-button>
      </el-footer>
    </el-container>
  </el-container>
</template>

<script setup>
/**@property {Array} ids - 已经选中
 * @param {Boolean} multiple - 是否多选
 * @param {Number} max - 多选时最大数量(0 代表限制数量)
 * @param {String} ftype - 打开来源(score_shop)
 */
import { nextTick, onMounted, reactive, ref } from 'vue';
import { api } from '../goods.service';
import { ElMessage } from 'element-plus';
import { usePagination } from '@/sheep/hooks';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const { pageData } = usePagination();

const emit = defineEmits(['modalCallBack']);
const props = defineProps(['modal']);

// 搜索字段配置
const searchFields = reactive({
  storeName: {
    type: 'input',
    get label() {
      return t('modules.goods.goodsName');
    },
    get placeholder() {
      return t('form.inputNameOrNumber');
    },
    width: 200,
  },
});

// 默认搜索值
const defaultSearchValues = reactive({
  storeName: '',
});

// 当前搜索条件 - 使用 ref 支持双向绑定
const currentSearchParams = ref({});

const loading = ref(true);
const table = reactive({
  list: [],
  ids: (props.modal.params.ids || []).map(id => Number(id)), // 确保ID为数字类型
  selectedGoods: new Map(), // 使用Map存储选中的商品完整数据，key为商品id
  preloadedGoods: new Map(), // 存储预加载的商品数据
});
async function getData(page, searchParams = null) {
  if (page) pageData.page = page;
  loading.value = true;

  try {
    // 构建请求参数 - 优先使用传入的参数，否则使用双向绑定的搜索条件
    const finalSearchParams = searchParams !== null ? searchParams : currentSearchParams.value;

    const params = {
      page: pageData.page,
      size: 20,
      isShow: 1,
      ...finalSearchParams,
    };
    const { code, data } = await api.goods.list(params);
    if (code == '200') {
      table.list = data.list || [];
      pageData.page = data.pageNum;
      pageData.size = data.pageSize;
      pageData.total = data.total;

      nextTick(() => {
        setDefaultSelected();
        // 初始化当前页面的选中商品数据
        initSelectedGoods();
      });
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    table.list = []; // 确保出错时也有默认值
  } finally {
    loading.value = false;
  }
}

// 搜索处理函数
function handleSearch(searchParams) {
  // 由于使用了 v-model，currentSearchParams 会自动更新
  // 直接调用 getData，会自动使用当前的搜索条件
  getData(1);
}

// 重置搜索参数处理函数
function handleReset() {
  // 手动清空搜索参数
  currentSearchParams.value = {};
  // 传递空参数重新请求数据
  getData(1, {});
}

// 设置默认选中
function setDefaultSelected() {
  // 确保 table.list 存在且为数组
  if (!table.list || !Array.isArray(table.list)) {
    console.warn('table.list is not available or not an array:', table.list);
    return;
  }

  table.list.forEach((item) => {
    const itemId = Number(item.id);
    if (table.ids?.includes(itemId)) {
      multipleTableRef.value?.toggleRowSelection(item, true);
      toggleRowSelection('row', [item], item);
    }
  });
}

const multipleTableRef = ref();
function selectRow(selection, row) {
  const rowId = Number(row.id);
  if (
    !props.modal.params.max ||
    (props.modal.params.max && props.modal.params.max > table.ids.length)
  ) {
    if (table.ids.includes(rowId)) {
      let index = table.ids.findIndex((id) => id === rowId);
      table.ids.splice(index, 1);
      // 从选中商品数据中移除
      table.selectedGoods.delete(rowId);
    } else {
      table.ids.push(rowId);
      // 添加到选中商品数据中
      addToSelectedGoods(row);
    }
  }
  toggleRowSelection('row', selection, row);
}
function selectAll(selection) {
  if (
    !props.modal.params.max ||
    (props.modal.params.max && props.modal.params.max > table.ids.length + selection.length)
  ) {
    if (selection.length == 0) {
      // 取消全选：移除当前页面的所有选中项
      table.list.forEach((l) => {
        const lId = Number(l.id);
        if (table.ids.includes(lId)) {
          let index = table.ids.findIndex((id) => id === lId);
          table.ids.splice(index, 1);
          // 从选中商品数据中移除
          table.selectedGoods.delete(lId);
        }
      });
    } else {
      // 全选：添加当前页面的所有项
      table.list.forEach((l) => {
        const lId = Number(l.id);
        if (!table.ids.includes(lId)) {
          table.ids.push(lId);
          // 添加到选中商品数据中
          addToSelectedGoods(l);
        }
      });
    }
  }
  toggleRowSelection('all', selection);
}

function toggleRowSelection(type, selection, row) {
  // 限制数量
  if (props.modal.params.max && props.modal.params.max < selection.length) {
    if (type == 'row') {
      multipleTableRef.value.toggleRowSelection(row, false);
    } else if (type == 'all') {
      multipleTableRef.value?.clearSelection();
      table.list.forEach((l) => {
        const lId = Number(l.id);
        if (table.ids?.includes(lId)) {
          multipleTableRef.value?.toggleRowSelection(l, true);
        }
      });
    }
    ElMessage({
      type: 'warning',
      message: t('message.selectionLimitReached'),
    });
    return false;
  }
}

// 添加商品到选中数据集合
function addToSelectedGoods(item) {
  const goodsData = {
    id: Number(item.id),
    title: item.title || item.storeName,
    image: item.image,
    price: item.price || item.current_price || item.original_price || item.otPrice,
    stock: item.stock,
  };
  table.selectedGoods.set(Number(item.id), goodsData);
}

// 初始化时添加已选中的商品数据
function initSelectedGoods() {
  table.list.forEach((item) => {
    const itemId = Number(item.id);
    // 只添加还未在selectedGoods中的商品,避免覆盖预加载的数据
    if (table.ids.includes(itemId) && !table.selectedGoods.has(itemId)) {
      addToSelectedGoods(item);
    }
  });
}

// 预加载所有已选中商品的完整数据
async function preloadSelectedGoods() {
  if (!table.ids.length) return;

  try {
    // 批量获取已选中商品的详细信息
    const promises = table.ids.map(async (id) => {
      try {
        const { code, data } = await api.goods.info(id);
        if (code === '200' && data) {
          // 直接添加到selectedGoods中,确保所有已选中的商品都被保存
          const goodsData = {
            id: Number(data.id),
            title: data.title || data.storeName,
            image: data.image,
            price: data.price || data.current_price || data.original_price || data.otPrice,
            stock: data.stock,
          };
          table.selectedGoods.set(Number(id), goodsData);
          table.preloadedGoods.set(Number(id), data);
        } else {
          // 即使接口失败,也保留ID的占位信息
          console.warn(`商品${id}详情获取失败,保留占位信息`);
          table.selectedGoods.set(Number(id), {
            id: Number(id),
            title: `商品 ${id}`,
            image: '',
            price: 0,
            stock: 0,
          });
        }
      } catch (error) {
        console.warn(`获取商品${id}详情失败:`, error);
        // 即使接口失败,也保留ID的占位信息
        table.selectedGoods.set(Number(id), {
          id: Number(id),
          title: `商品 ${id}`,
          image: '',
          price: 0,
          stock: 0,
        });
      }
    });

    await Promise.allSettled(promises);
    console.log('预加载完成,已选商品数量:', table.selectedGoods.size, '已选ID:', Array.from(table.selectedGoods.keys()));
  } catch (error) {
    console.error('预加载选中商品数据失败:', error);
  }
}

function singleSelect(id) {
  // 找到对应的商品数据
  const selectedItem = table.list.find((item) => item.id === id);
  if (selectedItem) {
    const goodsData = {
      id: selectedItem.id,
      title: selectedItem.title || selectedItem.storeName,
      image: selectedItem.image,
      price:
        selectedItem.price ||
        selectedItem.current_price ||
        selectedItem.original_price ||
        selectedItem.otPrice,
      stock: selectedItem.stock,
    };

    emit('modalCallBack', {
      event: 'confirm',
      data: goodsData,
    });
  }
}

function confirm() {
  // 将Map转换为数组，获取所有选中的商品数据
  const selectedGoodsData = Array.from(table.selectedGoods.values());

  console.log('提交商品数据:', {
    总数: selectedGoodsData.length,
    IDs: selectedGoodsData.map(g => g.id),
    原始IDs: table.ids
  });

  emit('modalCallBack', {
    event: 'confirm',
    data: selectedGoodsData,
  });
}

onMounted(async () => {
  // 先预加载已选中的商品数据
  await preloadSelectedGoods();
  // 再获取第一页数据
  getData();
});
</script>
<style lang="scss" scoped>
.goods-select {
  .goods-search {
    --el-header-height: auto;
    padding-top: var(--sa-padding);
  }

  .sa-footer--submit {
    height: auto;
    padding: 16px;
    border-top: 1px solid var(--sa-border);
    background: #fff;
  }

  .title {
    height: 16px;
    line-height: 16px;
    font-size: 12px;
    font-weight: 400;
    color: var(--sa-subtitle);
  }

  .price {
    line-height: 16px;
    font-size: 12px;
    font-weight: 400;
    color: #ff4d4f;
  }

  .goods-title {
    font-size: 14px;
    color: #333;
    line-height: 1.4;
    word-break: break-word;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .goods-image {
    width: 60px;
    height: 60px;
    margin-right: 12px;
    border-radius: 6px;
    overflow: hidden;
    flex-shrink: 0;
    object-fit: cover;
    aspect-ratio: 1 / 1;
  }

  .sa-footer--submit {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    --el-footer-height: auto;
    min-height: 60px;
  }
}

@media only screen and (max-width: 768px) {
  .goods-price {
    display: none;
  }
}
</style>
