<template>
  <div class="icon-edit-page">
    <!-- Header -->
    <div class="header">
      <div class="logo">
        <img src="@/assets/images/home/logo@2x.png" alt="STORLEAD" />
      </div>
      <div class="user-info">
        <img src="@/assets/images/home/Group@2x.png" alt="User" class="user-avatar" />
        <span class="username">祝小清</span>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <div class="section" v-for="app in appList" :key="app.appId">
        <h2 class="section-title">{{ app.appName }}</h2>
        <div class="icon-grid">
          <div
            class="icon-item"
            v-for="page in app.appPages"
            :key="page.pageId"
            @click="handleIconClick(page)"
          >
            <div class="icon-wrapper">
              <img
                :src="getIconPath(page.iconName || getDefaultIcon(page.appName))"
                :alt="page.appName"
              />
              <div class="edit-overlay">
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </div>
            </div>
            <span class="icon-label">{{ page.appName }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Icon Select Dialog -->
    <HomeIconSelect
      v-model="iconSelectVisible"
      :current-icon="currentIconName"
      @confirm="handleIconConfirm"
    />
  </div>
</template>

<script setup name="IconEdit" lang="ts">
import { ref, onMounted } from 'vue';
import { Edit } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getHomeApp, updateIcon } from '@/api/app';
import HomeIconSelect from '@/components/HomeIconSelect/index.vue';
import { getIconPath as getIconPathUtil } from '@/assets/homeIcon/iconUtils';

interface AppPage {
  pageId: number;
  appName: string;
  iconName?: string;
}

interface AppInfo {
  appId: number;
  appName: string;
  appPages: AppPage[];
}

const appList = ref<AppInfo[]>([]);
const iconSelectVisible = ref(false);
const currentEditingPage = ref<AppPage | null>(null);
const currentIconName = ref<string>('');

// 默认图标映射（中文名称到英文图标名称）
const defaultIconMap: Record<string, string> = {
  '我的目标': 'my_goals',
  '我的任务': 'my_tasks',
  '@我的任务': 'at_my_tasks',
  '我的简报': 'my_briefing',
  '简报草稿': 'briefing_draft',
  '个人绩效': 'personal_performance',
  '我的线索': 'my_leads',
  '公共线索': 'public_leads',
  '全部客户': 'all_customers',
  '公海客户': 'public_sea_customers',
  '重点客户': 'key_customers',
  '跟进记录': 'follow_up_records',
  '联系人': 'contacts',
  '我的商机': 'my_opportunities',
  '我的订单': 'my_orders',
  '全部任务': 'all_tasks',
  '工资条': 'payslip',
  '月考勤报表': 'monthly_attendance_report',
  '假期余额': 'leave_balance',
  '社保缴纳记录': 'social_security_payment_records',
  '公积金缴纳记录': 'provident_fund_payment_records',
  '指挥中心': 'command_center',
  '数据中心': 'data_center',
  '任务': 'tasks',
  '测试': 'test',
  '我的项目': 'my_projects',
  '采购管理': 'procurement_management'
};

// 获取默认图标名称
const getDefaultIcon = (appName: string): string => {
  return defaultIconMap[appName] || 'my_goals';
};

// 获取图标路径
const getIconPath = (iconName: string): string => {
  return getIconPathUtil(iconName);
};

// 点击图标
const handleIconClick = (page: AppPage) => {
  currentEditingPage.value = page;
  currentIconName.value = page.iconName || getDefaultIcon(page.appName);
  iconSelectVisible.value = true;
};

// 确认选择图标
const handleIconConfirm = async (iconName: string) => {
  if (!currentEditingPage.value) return;

  try {
    await updateIcon({
      id: currentEditingPage.value.pageId,
        iconName: iconName
    });

    // 更新本地数据
    if (currentEditingPage.value) {
      currentEditingPage.value.iconName = iconName;
    }

    ElMessage.success('图标更新成功');
    iconSelectVisible.value = false;
    currentEditingPage.value = null;
  } catch (error) {
    console.error('更新图标失败:', error);
    ElMessage.error('图标更新失败');
  }
};

// 初始化数据
const initData = async () => {
  try {
    const res = await getHomeApp();
    if (res.result) {
      appList.value = res.result;
    }
  } catch (error) {
    console.error('Failed to get home app list:', error);
  }
};

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

<style scoped lang="scss">
.icon-edit-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #F5F7FA 0%, #FFFFFF 100%);
  overflow-y: scroll;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  background: linear-gradient(90deg, #1E88E5 0%, #42A5F5 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .logo {
    img {
      height: 32px;
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 12px;
    color: white;
    cursor: pointer;

    .user-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      border: 2px solid rgba(255, 255, 255, 0.3);
    }

    .username {
      font-size: 14px;
      font-weight: 500;
    }
  }
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 92px 20px 40px 20px;
}

.section {
  margin-bottom: 48px;

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 24px;
    padding-left: 12px;
    border-left: 4px solid #1E88E5;
  }

  .icon-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 32px 24px;
    background: white;
    padding: 32px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

    @media (max-width: 768px) {
      grid-template-columns: repeat(4, 1fr);
      gap: 24px 16px;
      padding: 24px;
    }

    @media (max-width: 480px) {
      grid-template-columns: repeat(3, 1fr);
      gap: 20px 12px;
      padding: 20px;
    }
  }

  .icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:hover {
      transform: translateY(-4px);

      .icon-wrapper {
        .edit-overlay {
          opacity: 1;
        }
      }
    }

    .icon-wrapper {
      width: 64px;
      height: 64px;
      border-radius: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      img {
        width: 64px;
        height: 64px;
        object-fit: contain;
      }

      .edit-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.6);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: white;
        opacity: 0;
        transition: opacity 0.3s ease;
        border-radius: 16px;

        .el-icon {
          font-size: 20px;
          margin-bottom: 4px;
        }

        span {
          font-size: 12px;
        }
      }
    }

    .icon-label {
      font-size: 14px;
      color: #666;
      text-align: center;
      font-weight: 500;
      white-space: nowrap;
    }
  }
}
</style>

