<template>
  <div class="toolbar-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="categoryId">
          <el-select v-model="queryParams.categoryId" 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-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">搜索</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="toolbarList"
        @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="toolbar-info">
              <div class="toolbar-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="toolbar-details">
                <div class="toolbar-title">
                  <span class="label">工具栏名称:</span>
                  <span class="value">{{ scope.row.name || '-' }}</span>
                </div>
                <div class="toolbar-category">
                  <span class="label">所属分类:</span>
                  <span class="value">{{ getCategoryName(scope.row.categoryId) }}</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="status-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="handleEdit(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>
      
      <pagination
        v-show="total > 0"
        :total="total"
        :page="queryParams.pageNum"
        :limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

         <!-- 编辑/添加对话框 -->
     <el-dialog 
       v-model="dialogVisible" 
       :title="dialogTitle" 
       width="720px"
       class="toolbar-dialog"
     >
       <el-form 
         ref="formRef" 
         :model="form" 
         :rules="rules" 
         label-width="120px"
       >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工具栏名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入工具栏名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option label="行前必备" :value="1" />
                <el-option label="游玩工具" :value="2" />
                <el-option label="出行保障" :value="3" />
                <el-option label="公共服务" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="工具栏图标" prop="pic">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :on-success="handleImageSuccess"
          >
            <img v-if="form.pic" :src="form.pic" class="image-preview" />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸 80x80</div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
                         <el-form-item label="跳转类型" prop="jumpType">
               <el-select v-model="form.jumpType" placeholder="请选择跳转类型" style="width: 100%">
                 <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-select>
             </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortNum">
              <el-input-number v-model="form.sortNum" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="跳转路径" prop="jumpPath">
          <el-input v-model="form.jumpPath" placeholder="请输入跳转路径" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="0">正常</el-radio>
                <el-radio :value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示标志" prop="showFlag">
              <el-radio-group v-model="form.showFlag">
                <el-radio :value="0">显示</el-radio>
                <el-radio :value="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
             <template #footer>
         <span class="dialog-footer">
           <el-button @click="dialogVisible = false">取消</el-button>
           <el-button type="primary" @click="handleSubmit" :loading="submitting">
             确定
           </el-button>
         </span>
       </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">
           <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 name="NavServiceToolbar">
import { listNavServiceToolbar, getNavServiceToolbar, delNavServiceToolbar, addNavServiceToolbar, updateNavServiceToolbar } from "@/api/system/common/scenic/navServiceToolbar";
import { useUserStore } from "@/store/modules/user";
import { Picture, Plus, ArrowDown } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const { sys_user } = useUserStore();

const toolbarList = ref([]);
const dialogVisible = ref(false);
const detailOpen = ref(false);
const dialogTitle = ref('');
const submitting = ref(false);
const loading = ref(false);
const selectedIds = ref([]);
const total = ref(0);
const dateRange = ref([]);
const detailData = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    categoryId: null,
    status: null
  },
  rules: {
    name: [
      { required: true, message: "工具栏名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "分类不能为空", trigger: "change" }
    ],
    pic: [
      { required: true, message: "工具栏图标不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

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

// 获取分类名称
function getCategoryName(categoryId) {
  const categoryMap = {
    1: '行前必备',
    2: '游玩工具',
    3: '出行保障',
    4: '公共服务'
  };
  return categoryMap[categoryId] || '-';
}

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

// 格式化日期
function formatDate(date) {
  if (!date) return '-';
  const d = new Date(date);
  if (isNaN(d.getTime())) return '-';
  return d.toLocaleDateString('zh-CN');
}

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

/** 查询服务区工具栏列表 */
function getList() {
  loading.value = true;
  listNavServiceToolbar(proxy.addDateRange(queryParams.value, dateRange)).then(response => {
    toolbarList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  Object.assign(form.value, {
    id: null,
    name: null,
    type: null,
    pic: null,
    jumpType: 1,
    jumpPath: null,
    categoryId: 1,
    sortNum: 100,
    status: 0,
    showFlag: 0,
    remark: null
  });
  // 清除表单验证
  if (proxy.$refs.formRef) {
    proxy.$refs.formRef.clearValidate();
  }
}

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

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  // 清除查询表单验证
  if (proxy.$refs.queryRef) {
    proxy.$refs.queryRef.clearValidate();
  }
  // 重置查询参数
  Object.assign(queryParams.value, {
    pageNum: 1,
    pageSize: 10,
    name: null,
    categoryId: null,
    status: null
  });
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.id);
}

// 处理编辑
function handleEdit(item) {
  reset();
  const formData = {
    id: item.id,
    name: item.name,
    pic: item.pic,
    jumpType: item.jumpType || 1,
    jumpPath: item.jumpPath,
    categoryId: item.categoryId,
    sortNum: item.sortNum,
    status: item.status,
    showFlag: item.showFlag,
    remark: item.remark || ''
  };
  Object.assign(form.value, formData);
  dialogVisible.value = true;
  dialogTitle.value = '修改工具栏';
}

// 处理添加
function handleAdd() {
  reset();
  dialogVisible.value = true;
  dialogTitle.value = '添加工具栏';
}

// 处理提交
async function handleSubmit() {
  try {
    await proxy.$refs["formRef"].validate();
    submitting.value = true;
    
    const payload = {
      id: form.value.id,
      name: form.value.name,
      pic: form.value.pic,
      jumpType: form.value.jumpType,
      jumpPath: form.value.jumpPath,
      categoryId: form.value.categoryId,
      sortNum: form.value.sortNum,
      status: form.value.status,
      showFlag: form.value.showFlag,
      remark: form.value.remark
    };
    
    let response;
    if (form.value.id) {
      response = await updateNavServiceToolbar(payload);
    } else {
      response = await addNavServiceToolbar(payload);
    }
    
    if (response.code === 200) {
      proxy.$modal.msgSuccess(form.value.id ? '修改成功' : '添加成功');
      dialogVisible.value = false;
      getList();
    } else {
      proxy.$modal.msgError(response.msg || '操作失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    proxy.$modal.msgError('操作失败');
  } finally {
    submitting.value = false;
  }
}

/** 批量操作 */
async function handleCommand(command, row) {
  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() {
  proxy.$modal.confirm(`是否确认删除选中的${selectedIds.value.length}个工具栏？`, '提示').then(function() {
    return delNavServiceToolbar(selectedIds.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("批量删除成功");
  }).catch(() => {});
}

// 处理删除
async function handleDelete(item) {
  try {
    await proxy.$modal.confirm('确认删除该工具栏吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await delNavServiceToolbar(item.id);
    if (response.code === 200) {
      proxy.$modal.msgSuccess('删除成功');
      getList();
    } else {
      proxy.$modal.msgError(response.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      proxy.$modal.msgError('删除失败');
    }
  }
}

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

/** 导出按钮操作 */
function handleExport() {
  proxy.download('scenic/navServiceToolbar/export', {
    ...queryParams.value
  }, `navServiceToolbar_${new Date().getTime()}.xlsx`);
}

// 图片上传前验证
function beforeImageUpload(file) {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    proxy.$modal.msgError('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    proxy.$modal.msgError('图片大小不能超过 2MB!');
    return false;
  }
  return true;
}

// 图片上传成功
function handleImageSuccess(response) {
  if (response.code === 200) {
    form.value.pic = response.data;
    proxy.$modal.msgSuccess('图片上传成功');
  } else {
    proxy.$modal.msgError(response.msg || '图片上传失败');
  }
}

getList();
</script>

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

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

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

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

.mb8 {
  margin-bottom: 8px;
}

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

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

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

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

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

.toolbar-title,
.toolbar-category {
  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,
.status-info {
  font-size: 13px;
  line-height: 1.5;
  padding: 8px 0;
}

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

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

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

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

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

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

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

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

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

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

.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;
}
</style> 