<template>
  <div class="carousel-container">
    <el-card shadow="hover">
      <!-- 搜索区域 -->
      <transition
        :enter-active-class="proxy?.animate.searchAnimate.enter"
        :leave-active-class="proxy?.animate.searchAnimate.leave"
      >
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
              <el-form-item label="广告名称" prop="title">
                <el-input
                  v-model="queryParams.title"
                  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>
          </el-card>
        </div>
      </transition>

      <!-- 操作栏 -->
      <el-row :gutter="10" class="mb8">
        <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
      </el-row>

      <!-- 表格标题 -->
      <div class="table-title mb-[10px]">
        <span>轮播广告信息列表</span>
      </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" 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="carouselFormRef" :model="form" :rules="rules" label-width="100px">
        <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="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-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <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-col>
          <el-col :span="12">
            <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-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="背景色" prop="color">
              <el-color-picker v-model="form.color" show-alpha />
            </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" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="链接" prop="link">
          <el-input v-model="form.link" 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="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
        </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="GiftCarousel" 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 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,
  title: '',
  adType: 'gift_banner',
  startTime: '',
  endTime: ''
});

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

const carouselFormRef = ref<ElFormInstance>();

const initFormData = {
  id: undefined as number | undefined,
  adType: 'gift_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.title,
    adType: queryParams.value.adType
  };
  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.title = '';
  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: 'gift_banner',
    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-container {
  height: 100%;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}
</style>

