<template>
  <div class="banner-config">
    <!-- 搜索条件区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
        <el-form-item label="活动标题" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入活动标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="链接类型" prop="jumpType">
          <el-select v-model="queryParams.jumpType" placeholder="请选择链接类型" clearable style="width: 200px">
            <el-option label="跳转链接" :value="1" />
            <el-option label="不跳转" :value="2" />
            <el-option label="小程序内链" :value="3" />
            <el-option label="小程序外链" :value="4" />
            <el-option label="H5外链" :value="5" />
            <el-option label="公众号文章" :value="6" />
            <el-option label="公众号" :value="7" />
            <el-option label="电话拨号" :value="8" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option label="正常" :value="0" />
            <el-option label="停用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">Q 搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAdd">+ 添加轮播图</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-dropdown @command="handleCommand">
            <el-button>
              请选择批量处理<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="delete">批量删除</el-dropdown-item>
                <el-dropdown-item command="export">批量导出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-card>

    <!-- 轮播图列表 -->
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="bannerList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        
        <el-table-column label="基本信息" min-width="400">
          <template #default="scope">
            <div class="banner-info">
              <div class="banner-image">
                <img v-if="scope.row.pic" :src="scope.row.pic" :alt="scope.row.name" />
                <div v-else class="no-image">
                  <el-icon><Picture /></el-icon>
                </div>
              </div>
              <div class="banner-details">
                <div class="banner-title">
                  <span class="label">轮播图名称:</span>
                  <span class="value">{{ scope.row.name || '-' }}</span>
                </div>
                <div class="banner-module">
                  <span class="label">所属模块:</span>
                  <span class="value">轮播图</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="排序" align="center" width="80">
          <template #default="scope">
            <span class="sort-number">{{ scope.row.sortNum || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="链接类别" min-width="300">
          <template #default="scope">
            <div class="link-info">
              <div class="link-type">
                <span class="label">链接类别:</span>
                <span class="value">{{ getJumpTypeText(scope.row.jumpType) }}</span>
              </div>
              <div class="link-address">
                <span class="label">链接地址:</span>
                <span class="value">{{ scope.row.jumpPath || '-' }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" min-width="200">
          <template #default="scope">
            <div class="create-info">
              <div class="status">
                <span class="label">使用状态:</span>
                <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 0 ? '正常' : '停用' }}
                </el-tag>
              </div>
              <div class="create-time">
                <span class="label">创建时间:</span>
                <span class="value">{{ formatDate(scope.row.createTime) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                  <el-dropdown-item command="view">查看详情</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="720px" append-to-body>
      <el-form ref="bannerRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="轮播名称" prop="navName">
              <el-input v-model="form.navName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="navSort">
              <el-input-number v-model="form.navSort" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="轮播图片" prop="navIcon">
          <ImageSelector
            v-model="form.navIcon"
            placeholder="选择轮播图片"
            :width="750"
            :height="400"
            @change="handleImageChange"
          />
          <div class="upload-tip">建议尺寸 750x400</div>
        </el-form-item>

        <el-form-item label="跳转类型" prop="jumpType">
          <el-radio-group v-model="form.jumpType" @change="handleJumpTypeChange">
            <el-radio :value="1">跳转链接</el-radio>
            <el-radio :value="2">不跳转</el-radio>
            <el-radio :value="3">小程序内链</el-radio>
            <el-radio :value="4">小程序外链</el-radio>
            <el-radio :value="5">H5外链</el-radio>
            <el-radio :value="6">公众号文章</el-radio>
            <el-radio :value="7">公众号</el-radio>
            <el-radio :value="8">电话拨号</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="跳转链接" prop="navUrl">
          <el-input v-model="form.navUrl" placeholder="请输入跳转链接" :disabled="form.jumpType === 2" />
        </el-form-item>

        <el-form-item label="小程序AppID" prop="appId" v-if="form.jumpType === 4">
          <el-input v-model="form.appId" placeholder="请输入对方小程序的AppID" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="form.createTime"
                type="datetime"
                placeholder="请选择创建时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间">
              <el-date-picker
                v-model="form.updateTime"
                type="datetime"
                placeholder="请选择更新时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="navStatus">
          <el-radio-group v-model="form.navStatus">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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>

    <!-- 详情对话框 -->
    <el-dialog title="轮播图详情" v-model="detailOpen" width="600px" append-to-body>
      <div class="detail-content">
        <div class="detail-item">
          <span class="detail-label">轮播名称:</span>
          <span class="detail-value">{{ detailData.name || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">排序:</span>
          <span class="detail-value">{{ detailData.sortNum || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">轮播图片:</span>
          <div class="detail-image">
            <img v-if="detailData.pic" :src="detailData.pic" :alt="detailData.name" />
            <span v-else class="no-image-text">暂无图片</span>
          </div>
        </div>
        <div class="detail-item">
          <span class="detail-label">跳转类型:</span>
          <span class="detail-value">{{ getJumpTypeText(detailData.jumpType) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">跳转链接:</span>
          <span class="detail-value">{{ detailData.jumpPath || '-' }}</span>
        </div>
        <div class="detail-item" v-if="detailData.appId">
          <span class="detail-label">小程序AppID:</span>
          <span class="detail-value">{{ detailData.appId }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">状态:</span>
          <el-tag :type="detailData.status === 0 ? 'success' : 'danger'" size="small">
            {{ detailData.status === 0 ? '正常' : '停用' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">创建时间:</span>
          <span class="detail-value">{{ formatDateTime(detailData.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">更新时间:</span>
          <span class="detail-value">{{ formatDateTime(detailData.updateTime) }}</span>
        </div>
        <div class="detail-item" v-if="detailData.remark">
          <span class="detail-label">备注:</span>
          <span class="detail-value">{{ detailData.remark }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture, Plus, ArrowDown } from '@element-plus/icons-vue';
import { 
  listBannerNav, 
  addNavBottomMain, 
  updateNavBottomMain, 
  delNavBottomMain,
  type VsNavBottomMainVo,
  type VsNavBottomMainBo
} from '@/api/system/common/scenic/nav/index';
import ImageSelector from '@/components/ImageSelector/index.vue';

// 响应式数据
const loading = ref(false);
const title = ref('');
const open = ref(false);
const detailOpen = ref(false);
const bannerList = ref<VsNavBottomMainVo[]>([]);
const selectedIds = ref<number[]>([]);
const dateRange = ref<[Date, Date] | null>(null);
const detailData = ref<VsNavBottomMainVo>({} as VsNavBottomMainVo);

// 查询参数
const queryParams = reactive({
  name: '',
  jumpType: undefined as number | undefined,
  status: undefined as number | undefined,
  createTime: ''
});

const form = reactive<VsNavBottomMainBo & { 
  navStatus?: number;
  createTime?: string;
  updateTime?: string;
}>({
  navId: undefined,
  navName: '',
  navIcon: '',
  jumpType: 2,
  navUrl: '#',
  appId: '',
  navSort: 1,
  navStatus: 0,
  remark: '',
  createTime: '',
  updateTime: ''
});

const rules = {
  navName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  navIcon: [{ required: true, message: '请上传轮播图片', trigger: 'change' }],
  navSort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
};

// 上传相关
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadUrl = baseUrl + '/resource/oss/upload';
const headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token') || ''
};

// 初始化数据
onMounted(() => {
  getList();
});

/** 查询轮播图列表（type=3） */
async function getList() {
  loading.value = true;
  try {
    const response = await listBannerNav();
    if (response.code === 200 && response.data) {
      bannerList.value = response.data;
    } else {
      ElMessage.error(response.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = null;
  Object.assign(queryParams, {
    name: '',
    jumpType: undefined,
    status: undefined,
    createTime: ''
  });
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: VsNavBottomMainVo[]) {
  selectedIds.value = selection.map(item => item.navId!);
}

/** 排序变更 */
async function handleSortChange(row: VsNavBottomMainVo) {
  try {
    const response = await updateNavBottomMain({
      navId: row.navId,
      sortNum: row.sortNum,
      type: '3'
    });
    if (response.code === 200) {
      ElMessage.success('排序更新成功');
    } else {
      ElMessage.error(response.msg || '排序更新失败');
    }
  } catch (error) {
    ElMessage.error('排序更新失败');
  }
}

/** 批量操作 */
async function handleCommand(command: string, row?: VsNavBottomMainVo) {
  if (command === 'delete') {
    if (row) {
      await handleDelete(row);
    } else if (selectedIds.value.length > 0) {
      await handleBatchDelete();
    }
  } else if (command === 'export') {
    handleExport();
  } else if (command === 'view') {
    handleView(row!);
  }
}

/** 批量删除 */
async function handleBatchDelete() {
  await ElMessageBox.confirm(`是否确认删除选中的${selectedIds.value.length}个轮播图？`, '提示');
  // 这里需要实现批量删除接口
  ElMessage.success('批量删除成功');
  getList();
}

/** 导出 */
function handleExport() {
  ElMessage.info('导出功能待实现');
}

/** 查看详情 */
function handleView(row: VsNavBottomMainVo) {
  detailData.value = { ...row };
  detailOpen.value = true;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加轮播图';
}

/** 修改按钮操作 */
function handleUpdate(row: VsNavBottomMainVo) {
  reset();
  const item = row;
  const formData = {
    navId: item.navId,
    navName: item.name,
    navIcon: item.pic,
    jumpType: item.jumpType || 2,
    navUrl: item.jumpType === 2 ? item.jumpPath || '#' : item.jumpPath,
    appId: (item as any).appId,
    navSort: item.sortNum,
    navStatus: item.status,
    remark: item.remark || '',
    createTime: item.createTime,
    updateTime: item.updateTime
  };
  Object.assign(form, formData);
  open.value = true;
  title.value = '修改轮播图';
}

/** 提交按钮 */
async function submitForm() {
  try {
    const payload: any = {
      navId: form.navId,
      name: form.navName,
      pic: form.navIcon,
      jumpType: form.jumpType,
      jumpPath: form.jumpType === 2 ? form.navUrl || '#' : form.navUrl,
      appId: form.appId,
      sortNum: form.navSort,
      status: form.navStatus,
      remark: form.remark,
      createTime: form.createTime,
      updateTime: form.updateTime,
      type: '3' // 轮播图固定类型
    };

    let response;
    if (form.navId) {
      response = await updateNavBottomMain(payload);
    } else {
      response = await addNavBottomMain(payload);
    }
    if (response.code === 200) {
      ElMessage.success('保存成功');
      open.value = false;
      getList();
    } else {
      ElMessage.error(response.msg || '保存失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  }
}

/** 删除按钮操作 */
async function handleDelete(row: VsNavBottomMainVo) {
  const _navId = row.navId!;
  await ElMessageBox.confirm('是否确认删除该轮播图？', '提示');
  const response = await delNavBottomMain(_navId);
  if (response.code === 200) {
    ElMessage.success('删除成功');
    getList();
  } else {
    ElMessage.error(response.msg || '删除失败');
  }
}

/** 重置表单 */
function reset() {
  Object.assign(form, {
    navId: undefined,
    navName: '',
    navIcon: '',
    jumpType: 2,
    navUrl: '#',
    appId: '',
    navSort: 1,
    navStatus: 0,
    remark: '',
    createTime: '',
    updateTime: ''
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 上传前校验 */
function beforeBannerUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  return true;
}

/** 图片选择器回调 */
function handleImageChange(imageData: { url: string; width: number; height: number }) {
  form.navIcon = imageData.url;
}

/** 上传成功回调 */
function handleBannerSuccess(response: any) {
  if (response.code === 200) {
    form.navIcon = response.data.url;
    ElMessage.success('上传成功');
  } else {
    ElMessage.error(response.msg || '上传失败');
  }
}

// 跳转类型联动
function handleJumpTypeChange(value: number) {
  if (value === 2) {
    form.navUrl = '#';
  } else if (value === 4) {
    form.navUrl = '';
  }
}

// 获取跳转类型文本
function getJumpTypeText(type: number | undefined): string {
  const typeMap: Record<number, string> = {
    1: '跳转链接',
    2: '不跳转',
    3: '小程序内链',
    4: '小程序外链',
    5: 'H5外链',
    6: '公众号文章',
    7: '公众号',
    8: '电话拨号'
  };
  return typeMap[type || 2] || '不跳转';
}

// 格式化日期时间
function formatDateTime(dateStr: string | undefined): string {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

// 格式化日期
function formatDate(dateStr: string | undefined): string {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN');
}
</script>

<style scoped>
.banner-config {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.action-card {
  margin-bottom: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.banner-info {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 0;
}

.banner-image {
  width: 80px;
  height: 50px;
  border-radius: 6px;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.banner-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  color: #c0c4cc;
  font-size: 20px;
}

.banner-details {
  flex: 1;
  min-width: 0;
}

.banner-title,
.banner-module {
  margin-bottom: 6px;
  font-size: 13px;
  line-height: 1.4;
}

.label {
  color: #909399;
  margin-right: 6px;
  font-weight: normal;
}

.value {
  color: #333;
  font-weight: 500;
}

.link-info,
.time-info,
.create-info {
  font-size: 13px;
  line-height: 1.5;
  padding: 8px 0;
}

.link-type,
.link-address,
.activity-time,
.status,
.create-time {
  margin-bottom: 6px;
}

.activity-time .value {
  font-size: 12px;
  color: #606266;
}

.status {
  display: flex;
  align-items: center;
  gap: 6px;
}

.create-time {
  margin-top: 4px;
}

.sort-number {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.detail-content {
  padding: 20px;
}

.detail-item {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

.detail-label {
  width: 120px;
  font-weight: 600;
  color: #606266;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #333;
  word-break: break-all;
}

.detail-image {
  flex: 1;
}

.detail-image img {
  max-width: 200px;
  max-height: 120px;
  border-radius: 6px;
  object-fit: cover;
}

.no-image-text {
  color: #909399;
  font-style: italic;
}

.dialog-footer {
  text-align: right;
}

.banner-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.banner-uploader:hover {
  border-color: #409eff;
}

.banner-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.image-upload-container {
  display: inline-block;
}

.image-preview {
  position: relative;
  display: inline-block;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.image-preview img {
  max-width: 200px;
  max-height: 150px;
  display: block;
}

.image-actions {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-actions {
  opacity: 1;
}

.upload-placeholder {
  cursor: pointer;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  transition: border-color 0.3s;
  background: #fafafa;
  color: #909399;
}

.upload-placeholder:hover {
  border-color: #409eff;
}

.upload-placeholder .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}
</style> 