<template>
  <el-container class="group-view panel-block">
    <el-container class="group-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">
            </sa-search-simple>
          </div>
          <el-tabs class="sa-tabs" v-model="currentStatus" @tab-change="handleTabChange">
            <el-tab-pane :label="t('common.all')" name=""></el-tab-pane>
            <el-tab-pane :label="t('modules.marketing.pending')" name="0"></el-tab-pane>
            <el-tab-pane :label="t('modules.marketing.ongoing')" name="1"></el-tab-pane>
            <el-tab-pane :label="t('modules.marketing.ended')" name="2"></el-tab-pane>
          </el-tabs>
          <div class="sa-title sa-flex sa-row-between">
            <div class="label sa-flex">
              <span class="left">{{ t('modules.marketing.groupActivityList') }}</span>
            </div>
            <div>
              <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
              <el-button icon="Plus" type="primary" @click="addRow">{{ t('modules.marketing.addActivity') }}</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" align="center"></el-table-column>
              <el-table-column sortable="custom" prop="id" :label="t('modules.marketing.activityId')"
                align="center"></el-table-column>
              <el-table-column :label="t('modules.marketing.activityTitle')" prop="name" width="150px" />
              <el-table-column :label="t('modules.marketing.activityStatus')" align="center">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.activeState)">
                    {{ getStatusText(scope.row.activeState) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.marketing.groupConfig')" align="center" width="280">
                <template #default="scope">
                  <div class="group-config">
                    <div class="config-item">
                      <span class="config-label">{{ t('modules.marketing.defaultGroupSize') }}：</span>
                      <span class="config-value">{{ getGroupNumber(scope.row.content) }}{{
                        t('modules.marketing.personGroup') }}</span>
                    </div>
                    <div class="config-item mt-6px">
                      <span class="config-label">{{ t('modules.marketing.countdownEnd') }}：</span>
                      <span class="config-value">{{ getCountdownTime(scope.row.content) }}{{
                        t('modules.marketing.hours') }}</span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column sortable="custom" prop="startTime" :label="t('modules.marketing.startTime')"
                align="center">
                <template #default="scope">
                  {{ scope.row.startTime || '--' }}
                </template>
              </el-table-column>
              <el-table-column sortable="custom" prop="endTime" :label="t('modules.marketing.endTime')" align="center">
                <template #default="scope">
                  {{ scope.row.endTime || '--' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('common.createTime')" align="center">
                <template #default="scope">
                  {{ scope.row.createTime || '--' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('common.actions')" fixed="right">
                <template #default="scope">
                  <div class="sa-flex">
                    <el-button v-if="scope.row.activeState !== 2" link type="primary" @click="editRow(scope.row)">
                      {{ t('common.edit') }}
                    </el-button>
                    <el-button v-if="scope.row.activeState !== 2" link class="sa-m-l-12" type="success"
                      @click="setGoods(scope.row)">
                      {{ t('modules.marketing.setGoods') }}
                    </el-button>
                    <el-popconfirm width="fit-content" :confirm-button-text="t('common.confirm')"
                      :cancel-button-text="t('common.cancel')" :title="t('common.confirmDelete')"
                      @confirm="deleteRow(scope.row.id)">
                      <template #reference>
                        <el-button link 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="group-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.marketing.group',
};
</script>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useModal, usePagination } from '@/sheep/hooks';
import { api } from '../marketing.service';
import groupEdit from './edit.vue';
import GoodsSelect from '@/app/shop/admin/goods/goods/select.vue';

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

// 当前状态Tab
const currentStatus = ref('');

// 状态配置
const statusConfig = {
  0: { text: () => t('modules.marketing.pending'), type: 'warning' },
  1: { text: () => t('modules.marketing.ongoing'), type: 'success' },
  2: { text: () => t('modules.marketing.ended'), type: 'info' },
};

// 获取状态显示
const getStatusType = (status) => statusConfig[status]?.type || 'info';
const getStatusText = (status) => statusConfig[status]?.text() || t('common.unknown');

// 安全解析 content 字段
const parseContent = (content) => {
  if (!content || content === '') {
    return {};
  }
  try {
    return JSON.parse(content);
  } catch (e) {
    console.warn('Failed to parse content:', content, e);
    return {};
  }
};

// 获取成团人数
const getGroupNumber = (content) => {
  const parsed = parseContent(content);
  return parsed?.groupNumber || '--';
};

// 获取倒计时时间
const getCountdownTime = (content) => {
  const parsed = parseContent(content);
  return parsed?.countdownTime || '--';
};

// 搜索字段配置 - 使用computed确保语言切换时更新
const searchFields = computed(() => ({
  name: {
    type: 'input',
    label: t('modules.marketing.activityTitle'),
    placeholder: t('modules.marketing.enterActivityTitle'),
    width: 200,
  },
  id: {
    type: 'input',
    label: t('modules.marketing.activityId'),
    placeholder: t('modules.marketing.enterActivityId'),
    width: 200,
  },
}));

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

// 当前搜索条件 - 使用 ref 支持双向绑定
const currentSearchParams = ref({});
// 列表
const table = reactive({
  data: [],
  order: '',
  sort: '',
  selected: [],
});
const loading = ref(true);

// 获取数据
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: pageData.size,
      activeState: parseInt(currentStatus.value) ?? null,
      ...finalSearchParams,
    };


    // 使用 CRUD 的 list 方法
    const { code, data, message } = await api.group.list(params);

    if (code === '200') {
      table.data = data.list || data || [];
      pageData.total = data.total || 0;
    } else {
      ElMessage.error(message || t('common.fetchDataFailed'));
      table.data = [];
      pageData.total = 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error(t('common.fetchDataFailed'));
    table.data = [];
    pageData.total = 0;
  } finally {
    loading.value = false;
  }
}

// Tab切换处理
const handleTabChange = (tabName) => {
  currentStatus.value = tabName;
  // 直接调用 getData，会自动使用当前的搜索条件和状态
  getData(1);
};

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

// 重置搜索
const handleReset = () => {
  // 手动清空搜索参数
  currentSearchParams.value = {};
  // 传递空参数重新请求数据
  getData(1, {});
};
// 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: 'delete',
  //   label: '删除',
  //   auth: 'shop.admin.marketing.group.delete',
  //   class: 'danger',
  // },
];
function addRow() {
  useModal(
    groupEdit,
    { title: t('modules.marketing.createGroupActivity'), type: 'add' },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

function editRow(row) {
  useModal(
    groupEdit,
    {
      title: t('modules.marketing.editGroupActivity'),
      type: 'edit',
      id: row.id,
    },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

// 设置商品
async function setGoods(row) {
  const { code, data } = await api.group.getActivityProductIds(row.id);
  if (code == '200') {
    useModal(
      GoodsSelect,
      {
        title: '选择商品',
        multiple: true,
        ids: data.map((item) => String(item)) || [], // 已选择的商品ID
      },
      {
        confirm: (res) => {
          // 更新活动的商品列表
          updateActivityGoods(row.id, res.data);
        },
      },
    );
  }
}

// 更新活动商品
async function updateActivityGoods(activityId, goodsList) {
  try {
    // 使用 CRUD 的 edit 方法更新活动商品
    const productIds = goodsList.map((item) => ({ productId: item.id }));

    const { code, data, message } = await api.group.addActivityProduct(activityId, {
      list: productIds,
    });

    if (code === '200') {
      // 检查是否有商品冲突
      if (data && typeof data === 'string' && data.trim() !== '') {
        // 处理商品冲突情况，直接使用返回的字符串
        const conflictMessage = t('modules.marketing.goodsConflictError', {
          ids: data
        });

        await ElMessageBox.alert(conflictMessage, t('common.warning'), {
          confirmButtonText: t('common.confirm'),
          type: 'warning',
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
        });
      } else {
        ElMessage.success(t('message.updateSuccess'));
        getData(); // 刷新列表
      }
    } else {
      ElMessage.error(message || t('modules.marketing.setGoodsFailed'));
    }
  } catch (error) {
    console.error('设置商品失败:', error);
    ElMessage.error(t('modules.marketing.setGoodsFailed'));
  }
}

// 删除单条记录
async function deleteRow(id) {
  console.log(api.group);
  try {
    const { code, message } = await api.group.delete({ id });
    if (code === '200') {
      ElMessage.success(t('message.deleteSuccess'));
      getData();
    } else {
      ElMessage.error(message || t('message.deleteFailed'));
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error(t('message.deleteFailed'));
  }
}
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(() => {
        batchDeleteRows(ids);
      });
      break;
    default:
      // 其他批量操作可以在这里添加
      ElMessage.info('该功能暂未实现');
  }
}

// 批量删除方法
async function batchDeleteRows(ids) {
  try {
    const { code, message } = await api.group.batchDelete(ids);
    if (code === '200') {
      ElMessage.success('批量删除成功');
      getData();
      table.selected = []; // 清空选中项
    }
  } catch (error) {
    console.error('批量删除失败:', error);
    ElMessage.error('批量删除失败');
  }
}

onMounted(() => {
  getData();
});
</script>
<style lang="scss" scoped>
.group-view {
  height: 100%;

  .group-index-main {
    height: 100%;
  }

  .group-index-footer {
    height: auto;
  }

  .el-header {
    height: auto;
  }

  .el-main {
    .sa-table-wrap {
      height: 100%;
    }
  }

  .search-container {
    margin-bottom: 16px;
  }

  .sa-tabs {
    margin-bottom: 16px;
  }

  .sa-table-line-1 {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    line-clamp: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
  }

  .activity-info {
    display: flex;
    align-items: center;
  }

  .group-config {
    .config-item {
      display: flex;
      align-items: center;
      justify-content: center;
      white-space: nowrap;
      margin-bottom: 4px;

      .config-label {
        flex-shrink: 0;
        margin-right: 4px;
      }

    }

    .config-item:last-child {
      margin-bottom: 0;
    }
  }

  // 英文环境下的特殊样式
  [data-locale="en-US"] .group-config {
    .config-item {
      .config-label {
        font-size: 11px;
        margin-right: 2px;
      }

      .config-value {
        font-size: 11px;
      }
    }
  }
}
</style>
