<template>
  <el-container class="goods-view panel-block">
    <el-container class="goods-index-main">
      <el-container>
        <el-header class="sa-header">
          <!-- 简化搜索组件 -->
          <div class="search-container">
            <sa-search-simple :searchFields="searchFields" :defaultValues="defaultSearchValues"
              v-model="currentSearchParams" @search="handleSearch" @reset="handleReset">
              <template #custom="{ data }">
                <el-form-item :label="t('form.priceRange')">
                  <div class="range-input-group">
                    <el-input v-model="data.minPrice" :placeholder="t('form.minPrice')" clearable />
                    <span class="range-separator">{{ t('common.to') }}</span>
                    <el-input v-model="data.maxPrice" :placeholder="t('form.maxPrice')" clearable />
                  </div>
                </el-form-item>
              </template>
            </sa-search-simple>
          </div>
          <el-tabs class="sa-tabs" v-model="currentStatus" @tab-click="handleTabClick">
            <el-tab-pane :label="`${t('common.all')}(${statusCounts.all})`" name="all"></el-tab-pane>
            <el-tab-pane :label="`${t('modules.goods.onSale')}(${statusCounts.alreadyListed})`" name="up"></el-tab-pane>
            <el-tab-pane :label="`${t('modules.goods.offSale')}(${statusCounts.removed})`" name="down"></el-tab-pane>
            <!-- <el-tab-pane :label="`已删除(${statusCounts.recycle})`" name="isRecycle"></el-tab-pane> -->
          </el-tabs>
          <div class="sa-title sa-flex sa-row-between">
            <div class="label sa-flex">
              <span class="left">{{ t('modules.goods.goodsList') }}</span>
            </div>
            <div>
              <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
              <el-button icon="Plus" type="primary" @click="addRow">{{
                t('common.create')
              }}</el-button>
            </div>
          </div>
        </el-header>

        <el-main class="sa-p-0">
          <div class="sa-table-wrap" v-loading="loading">
            <el-table height="100%" class="sa-table" :data="table.data" @selection-change="changeSelection"
              @sort-change="fieldFilter" row-key="id" stripe>
              <template #empty>
                <sa-empty></sa-empty>
              </template>
              <el-table-column type="selection" width="48" align="center"></el-table-column>
              <el-table-column sortable="custom" prop="id" :label="t('modules.goods.goodsId')"
                min-width="100"></el-table-column>
              <el-table-column :label="t('modules.goods.goodsInfo')" min-width="300">
                <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 sortable="custom" prop="price" :label="t('form.price')" min-width="150" align="center">
                <template #default="scope">
                  <div class="mb-6px">{{ t('modules.goods.salePrice') }}: ৳{{ scope.row.price }}</div>
                  <div>{{ t('modules.goods.marketPrice') }}: ৳{{ scope.row.otPrice }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('form.status')" min-width="100" align="center">
                <template #default="scope">
                  <el-tag :type="statusList.color[scope.row.isShow]">
                    {{
                      scope.row.isShow === 1
                        ? t('modules.goods.onSale')
                        : t('modules.goods.offSale')
                    }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="itemNumber" :label="t('modules.goods.goodsNumber')" min-width="100"
                align="center"></el-table-column>
              <el-table-column prop="stock" :label="t('form.stock')" min-width="100" align="center"></el-table-column>
              <el-table-column sortable="custom" prop="ficti" :label="t('modules.goods.sales')" min-width="100"
                align="center"></el-table-column>
              <el-table-column :label="t('modules.goods.goodsSupplier')" min-width="120" align="center">
                <template #default="scope">
                  <div>{{ scope.row.itemSupplier }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('common.actions')" min-width="150" fixed="right">
                <template #default="scope">
                  <div class="sa-flex">
                    <el-button class="is-link" type="primary" @click="editRow(scope.row)">
                      {{ t('common.edit') }}
                    </el-button>
                    <el-popconfirm width="fit-content" :confirm-button-text="t('common.confirm')"
                      :cancel-button-text="t('common.cancel')" :title="t('message.confirmDelete')"
                      @confirm="deleteRow(scope.row.id)">
                      <template #reference>
                        <el-button class="is-link sa-m-l-12" type="danger">
                          {{ t('common.delete') }}
                        </el-button>
                      </template>
                    </el-popconfirm>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <el-footer class="goods-index-footer">
      <sa-view-bar>
        <template #left>
          <sa-batch-handle :batchHandleTools="batchHandleTools" :selectedLeng="table.selected.length"
            @batchHandle="batchHandle"></sa-batch-handle>
        </template>
        <template #right>
          <sa-pagination :pageData="pageData" @updateFn="handlePageChange" />
        </template>
      </sa-view-bar>
    </el-footer>
  </el-container>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { api } from '../goods.service';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useModal, usePagination } from '@/sheep/hooks';
import { useI18n } from 'vue-i18n';

import GoodsEdit from './edit.vue';

// 多语言支持
const { t } = useI18n();

// getType
const statusList = reactive({
  data: [],
  color: {
    1: 'success',
    0: 'danger',
    all: '',
    up: 'success',
    down: 'danger',
    hidden: 'info',
  },
});
async function getType() {
  const { code, data } = await api.category.list({ size: 100 });
  // 设置分类数据
  if (code === '200') {
    searchFields.cateId.options = data.list.map((cat) => ({
      label: cat.name,
      value: cat.id,
    }));
  }
  statusList.data = data.status;
}

// 搜索字段配置
const searchFields = reactive({
  id: {
    type: 'input',
    get label() {
      return t('modules.goods.goodsId');
    },
    get placeholder() {
      return t('form.inputGoodsId');
    },
    width: 150,
  },
  storeName: {
    type: 'input',
    get label() {
      return t('modules.goods.goodsName');
    },
    get placeholder() {
      return t('form.inputName');
    },
    width: 200,
  },
  cateId: {
    type: 'select',
    get label() {
      return t('modules.goods.goodsCategory');
    },
    get placeholder() {
      return t('form.selectCategory');
    },
    options: [],
    width: 200,
  },
});

// 默认搜索值
const defaultSearchValues = reactive({
  id: '',
  storeName: '',
  cateId: '',
  status: '',
  supplier: '',
  create_time: [],
  minPrice: '',
  maxPrice: '',
});

// 搜索可见性控制

// 当前状态标签
const currentStatus = ref('all');

// 当前搜索条件
const currentSearchParams = ref({});

// 状态数量
const statusCounts = reactive({
  all: 0,
  alreadyListed: 0,
  removed: 0,
  recycle: 0,
});

// 标签点击处理（只在用户主动点击时触发）
const handleTabClick = (tab) => {
  const status = tab.props.name;
  currentStatus.value = status;
  // 直接调用 getData，会自动使用当前的搜索条件和状态
  getData(1);
};

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

// 重置处理
const handleReset = () => {
  // 完全清空搜索参数，只保留默认排序
  currentSearchParams.value = {
    sortway: 0 // 重置为默认排序
  };
  // 直接调用 getData，使用空的搜索条件
  getData(1, {});
};

// 获取状态数量
const getStatusCounts = async () => {
  try {
    const response = await api.goods.getStatusNum();
    if (response.code == '200') {
      Object.assign(statusCounts, response.data);
    }
  } catch (error) {
    console.error('获取状态数量失败:', error);
  }
};

const loading = ref(true);

// 表格
const table = reactive({
  data: [],
  order: 'desc',
  sort: 'id',
  selected: [],
});

const { pageData } = usePagination();

// 获取数据
async function getData(page, searchParams = null, refreshStatusCounts = true) {
  if (page) pageData.page = page;
  loading.value = true;

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

  // 根据当前状态添加筛选条件
  let statusParams = {};
  switch (currentStatus.value) {
    case 'up':
      statusParams.isShow = 1;
      break;
    case 'down':
      statusParams.isShow = 0;
      break;
    case 'isRecycle':
      statusParams.isRecycle = 1;
      break;
  }

  // 构建最终的请求参数
  const requestParams = {
    page: pageData.page,
    size: pageData.size,
    ...finalSearchParams,
    ...statusParams,
  };

  // 调试：打印请求参数
  console.log('商品列表请求参数:', requestParams);

  const { code, data } = await api.goods.list(requestParams);
  if (code == '200') {
    table.data = data.list;
    pageData.page = data.pageNum;
    pageData.size = data.pageSize;
    pageData.total = data.total;
  }
  loading.value = false;

  // 可选择性刷新状态数量
  if (refreshStatusCounts) {
    getStatusCounts();
  }
}

// 分页处理
function handlePageChange(page) {
  getData(page, null, false); // 分页时不需要刷新状态数量，使用双向绑定的搜索条件
}

// table 字段排序
function fieldFilter({ prop, order }) {
  // 根据排序字段和方向设置 sortway 参数
  let sortway = 0; // 默认排序

  if (prop === 'price') {
    // 价格排序
    sortway = order === 'ascending' ? 1 : 2; // 1=价格升序, 2=价格降序
  } else if (prop === 'ficti') {
    // 销量排序
    sortway = order === 'ascending' ? 3 : 4; // 3=销量升序, 4=销量降序
  }

  // 调试：打印排序信息
  console.log('表格排序:', { prop, order, sortway });

  // 更新当前搜索参数中的 sortway
  currentSearchParams.value = {
    ...currentSearchParams.value,
    sortway
  };

  // 重新获取数据
  getData(null, null, false); // 排序时不需要刷新状态数量，使用更新后的搜索参数
}

// table 批量选择
function changeSelection(row) {
  table.selected = row;
}

// 批量操作
const batchHandleTools = computed(() => [
  {
    type: 'up',
    label: t('modules.goods.batchOnSale'),
    auth: 'shop.admin.goods.goods.edit',
    class: 'success',
  },
  {
    type: 'down',
    label: t('modules.goods.batchOffSale'),
    auth: 'shop.admin.goods.goods.edit',
    class: 'danger',
  },
  {
    type: 'delete',
    label: t('modules.goods.batchDelete'),
    auth: 'shop.admin.goods.goods.delete',
    class: 'danger',
  },
]);
async function batchHandle(type) {
  let ids = [];
  table.selected.forEach((row) => {
    ids.push(row.id);
  });

  switch (type) {
    case 'delete':
      ElMessageBox.confirm(t('message.confirmBatchDelete'), t('message.tip'), {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
      }).then(() => {
        deleteRow(ids.join(','));
      });
      break;
    case 'up':
      ElMessageBox.confirm(t('message.confirmBatchOnSale'), t('message.tip'), {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
      }).then(() => {
        batchShowStatus(ids.join(','), 1);
      });
      break;
    case 'down':
      ElMessageBox.confirm(t('message.confirmBatchOffSale'), t('message.tip'), {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
      }).then(() => {
        batchShowStatus(ids.join(','), 0);
      });
      break;
    default:
      handleCommand({ id: ids.join(','), type: type });
  }
}

function addRow() {
  useModal(
    GoodsEdit,
    {
      title: '添加商品',
      type: 'add',
      width: '1200px',
    },
    {
      confirm: () => {
        getData();
      },
    },
  );
}


function editRow(row) {
  useModal(
    GoodsEdit,
    {
      title: '编辑',
      type: 'edit',
      id: row.id,
      width: '1200px',
    },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

async function deleteRow(ids) {
  // 支持单个ID或多个ID（逗号分隔）
  const idsParam = Array.isArray(ids) ? ids.join(',') : ids;
  await api.goods.delete({ ids: idsParam });
  getData();
}

// 批量上下架
async function batchShowStatus(ids, showStatus) {
  try {
    const response = await api.goods.batchShowStatus({
      ids: ids,
      showStatus: showStatus,
    });

    if (response.code == '200') {
      ElMessage.success(showStatus === 1 ? '批量上架成功' : '批量下架成功');
      getData(); // 刷新列表
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message);
  }
}

async function handleCommand(e) {
  await api.goods.edit(e.id, {
    status: e.type,
  });
  getData();
}

onMounted(() => {
  getType();
  getData(); // getData 内部会调用 getStatusCounts()，避免重复调用
});
</script>
<style lang="scss">
.goods-dropdown {
  .status-up {
    color: var(--el-color-success);
  }

  .status-down {
    color: var(--el-color-danger);
  }

  .status-hidden {
    color: var(--el-color-info);
  }
}
</style>
<style lang="scss" scoped>
.goods-view {
  .el-main {
    .sa-table-wrap {
      overflow: hidden;
      height: 100%;

      :deep() {
        .el-table__empty-text {
          margin-left: 0;
        }
      }

      .title {
        height: 20px;
        line-height: 20px;
        font-size: 14px;
        color: var(--sa-font);
      }

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

      .goods-tag {
        max-width: 76px;
        padding: 3px 8px;
        border-radius: 10px;
        line-height: 14px;
        font-size: 12px;
        font-weight: 400;
        margin-right: 8px;
        cursor: pointer;

        &:last-of-type {
          margin-right: 0;
        }

        &.promos-goods {
          color: #faad14;
          background: rgba(250, 173, 20, 0.16);
        }

        &.groupon_ladder-goods,
        &.groupon-goods {
          color: var(--el-color-primary);
          background: var(--t-bg-active);
        }

        &.seckill-goods {
          color: #ff4d4f;
          background: rgba(255, 77, 79, 0.16);
        }
      }

      .sku {
        width: fit-content;
        height: 20px;
        line-height: 1;
        display: inline-flex;
        align-items: center;
        padding: 0 8px;
        font-size: 12px;
        color: #fff;
        background: var(--el-color-primary);
        border-radius: 10px;
        cursor: pointer;
      }

      .stock {
        cursor: pointer;

        .add-stock {
          margin-left: 8px;
          color: var(--el-color-primary);
        }
      }

      .el-tag {
        padding: 0 8px;
        border: none;
        cursor: pointer;

        :deep() {
          .el-tag__content {
            display: flex;
            align-items: center;
          }
        }
      }
    }

    .sa-expand-table {
      :deep() {
        .el-table__header-wrapper {
          display: none;
        }
      }

      .sku-text {
        font-size: 12px;
        color: var(--sa-font);
      }
    }
  }

  .expand-arrow {
    color: #fff !important;
  }

  .goods-index-main {
    overflow: hidden;
  }

  .el-aside {
    --el-aside-width: 161px;
    border-right: 1px solid var(--sa-border);
    padding: 0 3px;
  }

  .el-aside .category-all {
    line-height: 48px;
    border-radius: 4px;
    padding: 0 12px;
    position: relative;
    cursor: pointer;
    font-size: 14px;
    color: var(--sa-title);
  }

  .el-aside .category-all span:last-child {
    color: var(--el-color-primary);
  }

  .el-aside .category-all:hover {
    background: var(--t-bg-hover);
  }

  .el-aside .category-all.is-active {
    background: var(--t-bg-active);
    color: var(--el-color-primary);
  }

  .el-aside .category-all::after {
    content: '';
    position: absolute;
    right: 9px;
    bottom: 0;
    width: 138px;
    height: 1px;
    background: var(--sa-space);
  }

  .el-aside .el-tree {
    --el-tree-node-content-height: 40px;
    --el-tree-node-hover-bg-color: var(--t-bg-hover);
  }

  .el-aside .el-tree>.el-tree-node>.el-tree-node__content {
    --el-tree-node-content-height: 54px;
    align-items: flex-start;
    position: relative;
  }

  .el-aside .el-tree>.el-tree-node>.el-tree-node__content::after {
    content: '';
    position: absolute;
    right: 9px;
    bottom: 0;
    width: 138px;
    height: 1px;
    background: var(--sa-space);
  }

  .el-aside .el-tree .el-tree-node__content {
    /* align-items: flex-start; */
    padding-top: 6px;
    border-radius: 4px;
  }

  .el-aside .el-tree .name {
    line-height: 20px;
    font-size: 12px;
    color: var(--sa-font);
  }

  .el-aside .el-tree .goods {
    line-height: 16px;
    font-size: 12px;
    color: var(--sa-subfont);
  }

  .el-aside .el-tree:not(.all) .el-tree-node.is-current>.el-tree-node__content {
    background: var(--t-bg-active);
  }

  .el-aside .el-tree:not(.all) .el-tree-node.is-current>.el-tree-node__content .el-tree-node__expand-icon {
    color: var(--el-color-primary);
  }

  .el-aside .el-tree:not(.all) .el-tree-node.is-current>.el-tree-node__content .name {
    color: var(--el-color-primary);
  }

  .el-aside .el-tree:not(.all) .el-tree-node.is-current>.el-tree-node__content .goods {
    color: var(--el-color-primary);
  }

  .goods-index-footer {
    --el-footer-height: fit-content;
  }

  .goods-title {
    font-size: 14px;
    font-weight: 500;
    color: var(--sa-font);
    margin-bottom: 4px;
    line-height: 1.4;
  }


  .goods-supplier {
    font-size: 12px;
    color: var(--sa-subfont);
    line-height: 1.2;
  }

  .search-container {
    .range-input-group {
      display: flex;
      align-items: center;
      gap: 8px;
      width: 100%;

      .el-input {
        flex: 1;
      }

      .range-separator {
        color: var(--el-text-color-regular);
        font-size: 14px;
        white-space: nowrap;
      }
    }
  }
}
</style>
