<template>
  <div class="carousel-page">
    <div class="carousel-container">
      <!-- 搜索区域（独立卡片） -->
      <div class="search-card">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="广告名称" prop="adName">
            <el-input
              v-model="queryParams.adName"
              placeholder="请输入广告名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="起始时间" prop="dateRange">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" plain icon="Plus" @click="handleAdd">添加广告</el-button>
          </el-form-item>
        </el-form>
        <div class="toolbar">
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </div>
      </div>

      <!-- 表格区域（独立卡片） -->
      <div class="table-card">
        <!-- 表格标题 -->
        <div class="table-title">轮播广告信息列表</div>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="carouselList" border>
        <el-table-column label="广告图片" align="center" width="120">
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              fit="cover"
              style="width: 80px; height: 60px; border-radius: 4px"
              lazy
            />
          </template>
        </el-table-column>
        <el-table-column label="广告名称" align="center" prop="title" :show-overflow-tooltip="true" min-width="200" />
        <el-table-column label="时间" align="center" width="280">
          <template #default="scope">
            <div>开始时间：{{ scope.row.startTime }}</div>
            <div>到期时间：{{ scope.row.endTime }}</div>
          </template>
        </el-table-column>
        <el-table-column label="上线/下线" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ 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" prop="link" :show-overflow-tooltip="true" min-width="200" />
        <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="600px" append-to-body @close="cancel">
      <el-form ref="carouselFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="广告名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入广告名称" />
        </el-form-item>
        <el-form-item label="广告图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="date"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="date"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="链接地址" prop="link">
          <el-input v-model="form.link" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">上线</el-radio>
            <el-radio :value="0">下线</el-radio>
          </el-radio-group>
        </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="IndustrialCarousel" lang="ts">
import { listAdContent, addAdContent, updateAdContent, delAdContent } from '@/api/ad/content';
import dayjs from 'dayjs';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const carouselList = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);
const showSearch = ref(true);
const dateRange = ref<[string, string]>(['', '']);

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  adName: '',
  startTime: '',
  endTime: ''
});

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

const carouselFormRef = ref<ElFormInstance>();

const initFormData = {
  id: undefined as number | undefined,
  adType: 'industrial_banner',
  title: '',
  imageUrl: '',
  startTime: '',
  endTime: '',
  link: '',
  color: '#ffffff',
  remark: '',
  extJson: '{}',
  sort: 0,
  status: 1
};

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

const rules = reactive({
  title: [{ required: true, message: '广告名称不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }]
});

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const params: any = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    title: queryParams.value.adName,
    adType: 'industrial_banner'
  };
  if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
    params.startTime = dateRange.value[0];
    params.endTime = dateRange.value[1];
  }
  const res = await listAdContent(params);
  carouselList.value = res.rows || [];
  total.value = res.total || 0;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryParams.value.adName = '';
  queryParams.value.startTime = '';
  queryParams.value.endTime = '';
  handleQuery();
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  carouselFormRef.value?.resetFields();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  const today = dayjs().format('YYYY-MM-DD');
  const future = dayjs().add(30, '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: 'industrial_banner',
    imageUrl: row.imageUrl || '',
    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 = () => {
  carouselFormRef.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();
    });
  });
};

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

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

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

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

  .el-form { flex: 1; }
  .toolbar { flex-shrink: 0; }
}

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

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

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