<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"
              @search="(val) => getData(1, val)"
              @reset="getData(1)"
            >
              <template #custom="{ data }">
                <el-form-item label="价格区间">
                  <div class="range-input-group">
                    <el-input v-model="data.priceMin" placeholder="最低价格" clearable />
                    <span class="range-separator">至</span>
                    <el-input v-model="data.priceMax" placeholder="最高价格" clearable />
                  </div>
                </el-form-item>
              </template>
            </sa-search-simple>
          </div>
          <el-tabs class="sa-tabs" v-model="currentStatus" @tab-change="handleTabChange">
            <el-tab-pane label="全部(100)" name="all"></el-tab-pane>
            <el-tab-pane label="已上架(200)" name="up"></el-tab-pane>
            <el-tab-pane label="已下架(300)" name="down"></el-tab-pane>
            <el-tab-pane label="已删除(400)" name="deleted"></el-tab-pane>
          </el-tabs>
          <div class="sa-title sa-flex sa-row-between">
            <div class="label sa-flex">
              <span class="left">商品列表</span>
            </div>
            <div>
              <el-button
                class="sa-button-refresh"
                icon="RefreshRight"
                @click="getData()"
              ></el-button>
              <el-button icon="Plus" type="primary" @click="addRow">新建</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-dblclick="editRow"
              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="商品编号"
                min-width="100"
              ></el-table-column>
              <el-table-column label="商品信息" min-width="300">
                <template #default="scope">
                  <div class="sa-flex sa-row-center">
                    <el-image
                      :src="scope.row.image"
                      style="width: 60px; height: 60px; margin-right: 12px"
                      fit="cover"
                    />
                    <div>
                      <div class="goods-title">{{ scope.row.title }}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                sortable="custom"
                prop="price"
                label="价格"
                min-width="150"
                align="center"
              >
                <template #default="scope">
                  <div>原价: {{ scope.row.original_price || '৳1,999' }}</div>
                  <div>在线价格: {{ scope.row.current_price || '৳1,000' }}</div>
                </template>
              </el-table-column>
              <el-table-column label="状态" min-width="100" align="center">
                <template #default="scope">
                  <el-tag :type="statusList.color[scope.row.status]">
                    {{ scope.row.status_text }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="sku_id"
                label="货号"
                min-width="100"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="stock"
                label="库存"
                min-width="100"
                align="center"
              ></el-table-column>
              <el-table-column
                sortable="custom"
                prop="sales"
                label="销量"
                min-width="100"
                align="center"
              ></el-table-column>
              <el-table-column label="供应商" min-width="120" align="center">
                <template #default="scope">
                  <div>{{ scope.row.supplier || '商家科技有限公司' }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="150" fixed="right">
                <template #default="scope">
                  <div class="sa-flex">
                    <el-button class="is-link" type="primary" @click="editRow(scope.row)"
                      >编辑</el-button
                    >
                    <el-popconfirm
                      width="fit-content"
                      confirm-button-text="确认"
                      cancel-button-text="取消"
                      title="确认删除这条记录?"
                      @confirm="deleteRow(scope.row.id)"
                    >
                      <template #reference>
                        <el-button class="is-link sa-m-l-12" type="danger"> 删除 </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="getData" />
        </template>
      </sa-view-bar>
    </el-footer>
  </el-container>
</template>
<script>
  export default {
    name: 'shop.admin.goods.goods',
  };
</script>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { api } from '../goods.service';
  import { ElMessageBox } from 'element-plus';
  import { ArrowUp } from '@element-plus/icons-vue';
  import { useModal, usePagination } from '@/sheep/hooks';

  import GoodsEdit from './edit.vue';

  // getType
  const statusList = reactive({
    data: [],
    color: {
      all: '',
      up: 'success',
      down: 'danger',
      hidden: 'info',
    },
  });
  async function getType() {
    const { data } = await api.goods.getType();
    // 设置分类数据
    if (data.categories) {
      searchFields.category_id.options = data.categories.map((cat) => ({
        label: cat.name,
        value: cat.id,
      }));
    }
    statusList.data = data.status;
  }

  // 搜索字段配置
  const searchFields = reactive({
    title: {
      type: 'input',
      label: '商品名称',
      placeholder: '请输入商品名称',
      width: 200,
    },
    category_id: {
      type: 'select',
      label: '商品分类',
      placeholder: '请选择商品分类',
      options: [],
      width: 200,
    },
  });

  // 默认搜索值
  const defaultSearchValues = reactive({
    title: '',
    category_id: '',
    status: '',
    supplier: '',
    create_time: [],
    priceMin: '',
    priceMax: '',
  });

  // 搜索可见性控制

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

  // 标签切换处理
  const handleTabChange = (status) => {
    currentStatus.value = status;
    getData(1, { status: status === 'all' ? '' : status });
  };

  const loading = ref(true);

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

  const { pageData } = usePagination();

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

      // 处理搜索参数
      let search = {};
      if (Object.keys(searchParams).length > 0) {
        // 处理价格区间
        if (searchParams.priceMin || searchParams.priceMax) {
          const min = searchParams.priceMin || '0';
          const max = searchParams.priceMax || '999999';
          search.price = `${min} - ${max}`;
        }

        // 处理其他搜索参数
        Object.keys(searchParams).forEach((key) => {
          if (key !== 'priceMin' && key !== 'priceMax' && searchParams[key]) {
            search[key] = searchParams[key];
          }
        });
      }

      const response = await api.goods.list({
        page: pageData.page,
        list_rows: pageData.list_rows,
        ...search,
        order: table.order,
        sort: table.sort,
      });

      console.log('API 响应:', response);

      if (response && response.error === 0 && response.data) {
        table.data = response.data.data || [];
        pageData.page = response.data.current_page || 1;
        pageData.list_rows = response.data.per_page || 10;
        pageData.total = response.data.total || 0;
      } else {
        table.data = [];
        console.error('获取商品数据失败:', response);
      }
    } catch (error) {
      console.error('API 调用异常:', error);
      table.data = [];
    }
    loading.value = false;
  }

  // table 字段排序
  function fieldFilter({ prop, order }) {
    table.order = order == 'ascending' ? 'asc' : 'desc';
    table.sort = prop;
    getData();
  }

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

  // 批量操作
  const batchHandleTools = [
    {
      type: 'up',
      label: '批量上架',
      auth: 'shop.admin.goods.goods.edit',
      class: 'success',
    },
    {
      type: 'down',
      label: '批量下架',
      auth: 'shop.admin.goods.goods.edit',
      class: 'danger',
    },
    {
      type: 'delete',
      label: '批量删除',
      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('此操作将删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          deleteRow(ids.join(','));
        });
        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(id) {
    await api.goods.delete(id);
    getData();
  }

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

  onMounted(() => {
    getType();
    getData();
  });
</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>
