<template>
  <div class="title-page">
    <div class="title-container">
      <!-- 标题栏（独立卡片） -->
      <div class="header-card">
        <div class="table-title">福礼标题信息列表</div>
        <div class="action-btns">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          <el-button icon="Refresh" @click="getList">刷新</el-button>
        </div>
      </div>

      <!-- 表格区域（独立卡片） -->
      <div class="table-card">
        <!-- 表格 -->
        <el-table v-loading="loading" :data="titleList" border>
        <el-table-column label="标题名称" align="center" prop="title" min-width="140" />
        <el-table-column label="导航类型" align="center" prop="remark" min-width="120">
          <template #default="scope">
            {{ navTypeMap[scope.row.remark] || scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column label="链接地址" align="center" prop="link" :show-overflow-tooltip="true" min-width="240" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="80" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <span class="action-link primary" @click="handleUpdate(scope.row)">编辑</span>
            <span class="action-link danger" @click="handleDelete(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="620px" append-to-body @close="cancel">
      <el-form ref="titleFormRef" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标题链接" prop="link">
              <el-input v-model="form.link" placeholder="请输入标题链接" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="导航类型" prop="remark">
              <el-select v-model="form.remark" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in navTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="显示"
            inactive-text="隐藏"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GiftTitle" lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { ElFormInstance } from 'element-plus';
import dayjs from 'dayjs';
import { listAdContent, addAdContent, updateAdContent, delAdContent } from '@/api/ad/content';
import { listNavigation } from '@/api/system/navigation';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(false);
const total = ref(0);
const titleList = ref<any[]>([]);
const navTypeOptions = ref<{ label: string; value: string }[]>([]);

// 导航类型映射
const navTypeMap: Record<string, string> = {
  home: '首页导航',
  inner: '内页导航',
  search: '搜索导航',
  footer: '底部导航',
  float: '浮动导航'
};

// 加载导航类型选项
const loadNavTypeOptions = async () => {
  try {
    const res = await listNavigation({ pageNum: 1, pageSize: 100 });
    const list = res.rows || res.data || [];
    // 提取navType并去重
    const typeSet = new Set<string>();
    list.forEach((item: any) => {
      if (item.navType) {
        typeSet.add(item.navType);
      }
    });
    // 转换为下拉选项
    navTypeOptions.value = Array.from(typeSet).map((type) => ({
      label: navTypeMap[type] || type,
      value: type
    }));
  } catch (error) {
    console.error('获取导航类型失败', error);
    // 接口失败时使用默认选项
    navTypeOptions.value = [
      { label: '首页导航', value: 'home' },
      { label: '内页导航', value: 'inner' },
      { label: '搜索导航', value: 'search' },
      { label: '底部导航', value: 'footer' },
      { label: '浮动导航', value: 'float' }
    ];
  }
};

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  adType: 'gift_title',
  title: ''
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const titleFormRef = ref<ElFormInstance>();

const initFormData = {
  id: undefined as number | undefined,
  adType: 'gift_title',
  title: '',
  remark: '',
  link: '',
  imageUrl: '', // 后端校验需要，标题广告可用占位
  sort: 0,
  status: 1,
  color: '#ffffff',
  extJson: '{}',
  startTime: '',
  endTime: ''
};

const form = ref({ ...initFormData });

const rules = reactive({
  title: [{ required: true, message: '标题名称不能为空', trigger: 'blur' }]
});

const getList = async () => {
  loading.value = true;
  const res = await listAdContent({
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    adType: queryParams.value.adType,
    title: queryParams.value.title
  });
  titleList.value = res.rows || [];
  total.value = res.total || 0;
  loading.value = false;
};

const reset = () => {
  form.value = { ...initFormData };
  titleFormRef.value?.resetFields();
};

const handleAdd = () => {
  reset();
  const today = dayjs().format('YYYY-MM-DD');
  const future = dayjs().add(365, 'day').format('YYYY-MM-DD');
  form.value.startTime = today;
  form.value.endTime = future;
  form.value.imageUrl = form.value.imageUrl || 'https://via.placeholder.com/1x1';
  dialog.visible = true;
  dialog.title = '新增标题';
};

const handleUpdate = (row: any) => {
  reset();
  form.value = {
    ...row,
    adType: 'gift_title',
    status: row.status ?? 1,
    remark: row.remark || '',
    color: row.color || '#ffffff',
    extJson: row.extJson || '{}',
    imageUrl: row.imageUrl || 'https://via.placeholder.com/1x1',
    startTime: row.startTime ? dayjs(row.startTime).format('YYYY-MM-DD') : '',
    endTime: row.endTime ? dayjs(row.endTime).format('YYYY-MM-DD') : ''
  };
  dialog.visible = true;
  dialog.title = '编辑标题';
};

const submitForm = () => {
  titleFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      const api = form.value.id ? updateAdContent : addAdContent;
      api(form.value).then(() => {
        proxy?.$modal.msgSuccess(form.value.id ? '修改成功' : '新增成功');
        dialog.visible = false;
        getList();
      });
    }
  });
};

const handleDelete = (row: any) => {
  proxy
    ?.$modal.confirm(`是否确认删除标题名称为"${row.title}"的数据项?`)
    .then(() => delAdContent(row.id))
    .then(() => {
      proxy?.$modal.msgSuccess('删除成功');
      getList();
    });
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

onMounted(() => {
  loadNavTypeOptions();
  getList();
});
</script>

<style scoped lang="scss">
.title-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.title-container {
  max-width: 1200px;
  margin: 0 auto;
}

.header-card {
  background: #fff;
  border-radius: 4px;
  padding: 15px 20px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .table-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .action-btns {
    display: flex;
    gap: 10px;
  }
}

.table-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;

  .table-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .action-btns {
    display: flex;
    gap: 10px;
  }
}

.action-link {
  cursor: pointer;
  margin: 0 8px;
  
  &.primary {
    color: #409eff;
    &:hover { color: #66b1ff; }
  }
  
  &.danger {
    color: #f56c6c;
    &:hover { color: #f78989; }
  }
}
</style>

