<template>
  <div class="icon-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="iconList" border>
        <el-table-column label="分类标题" align="center" prop="title" min-width="160" />
        <el-table-column label="封面图片" align="center" width="140">
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              fit="cover"
              style="width: 64px; height: 64px"
              lazy
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="链接地址" align="center" prop="link" :show-overflow-tooltip="true" min-width="220">
          <template #default="scope">
            <span class="link-text">{{ scope.row.link || '#' }}</span>
          </template>
        </el-table-column>
        <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="iconFormRef" :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="sort">
              <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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-col>
        </el-row>

        <el-form-item label="封面图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" :limit="1" />
        </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="GiftIcon" 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 iconList = ref<any[]>([]);

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

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

const iconFormRef = ref<ElFormInstance>();

const initFormData = {
  id: undefined as number | undefined,
  adType: 'gift_icon',
  title: '',
  imageUrl: '',
  link: '',
  sort: 0,
  status: 1,
  color: '#ffffff',
  remark: '',
  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
  });
  iconList.value = res.rows || [];
  total.value = res.total || 0;
  loading.value = false;
};

const reset = () => {
  form.value = { ...initFormData };
  iconFormRef.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;
  dialog.visible = true;
  dialog.title = '新增图标广告';
};

const handleUpdate = (row: any) => {
  reset();
  form.value = {
    ...row,
    adType: 'gift_icon',
    status: row.status ?? 1,
    color: row.color || '#ffffff',
    remark: row.remark || '',
    extJson: row.extJson || '{}',
    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 = () => {
  iconFormRef.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">
.icon-container {
  height: 100%;
}

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

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

.image-slot {
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #c0c4cc;
  border-radius: 4px;
}

.link-text {
  color: #409eff;
}
</style>

