<template>
  <div class="title-container">
    <el-card shadow="hover">
      <!-- 顶部操作 -->
      <div class="action-bar mb-[10px]">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        <el-button icon="Refresh" @click="getList">刷新</el-button>
      </div>

      <!-- 表格标题 -->
      <div class="table-title mb-[10px]">
        <span>福礼标题信息列表</span>
      </div>

      <!-- 表格 -->
      <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" />
        <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" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </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"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <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';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(false);
const total = ref(0);
const titleList = ref<any[]>([]);
const navTypeOptions = [
  { label: '首页导航', value: '首页导航' },
  { label: '其他导航', value: '其他导航' }
];

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(() => {
  getList();
});
</script>

<style scoped lang="scss">
.title-container {
  height: 100%;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding: 0 4px;
}
</style>

