<template>
  <div class="solution-container">
    <el-card shadow="hover">
      <!-- 标题区域（可点击编辑） -->
      <div class="solution-header" @click="handleEditHeader">
        <div class="header-left">
          <span class="solution-title">{{ headerConfig.title }}</span>
          <span class="solution-subtitle">{{ headerConfig.subtitle }}</span>
        </div>
        <div class="header-right">
          <span class="more-link" @click.stop="handleLinkClick">{{ headerConfig.linkText }}></span>
        </div>
      </div>

      <!-- 方案卡片网格（和商城一模一样） -->
      <div class="solution-grid">
        <div
          v-for="item in solutionList"
          :key="item.id"
          class="solution-card"
          @click="handleUpdate(item)"
        >
          <!-- 标题 -->
          <div class="card-title">{{ item.title }}</div>
          <!-- 描述 -->
          <div class="card-desc">{{ item.description }}</div>
          <!-- 图片 -->
          <div class="card-image">
            <el-image :src="item.imageUrl" fit="contain" lazy class="solution-image">
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && solutionList.length === 0" description="暂无方案数据" />
    </el-card>

    <!-- 编辑标题对话框 -->
    <el-dialog v-model="headerDialog.visible" title="编辑标题" width="600px" append-to-body>
      <el-form :model="headerForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题名称" required>
              <el-input v-model="headerForm.title" placeholder="请输入标题名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题" required>
              <el-input v-model="headerForm.subtitle" placeholder="请输入副标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="链接文字">
              <el-input v-model="headerForm.linkText" placeholder="请输入链接文字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接">
              <el-input v-model="headerForm.linkUrl" placeholder="请输入链接地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="背景色">
              <el-color-picker v-model="headerForm.bgColor" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字体颜色">
              <el-color-picker v-model="headerForm.textColor" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveHeaderConfig">确 认</el-button>
        <el-button @click="headerDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" append-to-body @close="cancel">
      <el-form ref="solutionFormRef" :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="description">
          <el-input v-model="form.description" type="textarea" :rows="3" 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="sort">
          <el-input-number v-model="form.sort" :min="0" controls-position="right" />
        </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="Solution" lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import { getDecorationSectionByType, addDecorationSection, updateDecorationSection } from '@/api/decoration/section';
import { listAdContent, updateAdContent } from '@/api/ad/content';
import { listByIds } from '@/api/system/oss';

const adType = 'decoration_solution';



// 标题配置
const headerConfig = ref({
  id: null as number | null,
  title: '热门方案',
  subtitle: '为采购人提供"业务+服务"的项目解决方案',
  linkText: '更多方案',
  linkUrl: '',
  bgColor: '#ffffff',
  textColor: '#303133'
});

const headerDialog = reactive({ visible: false });
const headerForm = reactive({
  id: null as number | null,
  title: '',
  subtitle: '',
  linkText: '',
  linkUrl: '',
  bgColor: '#ffffff',
  textColor: '#303133'
});

// 加载标题配置
const loadHeaderConfig = async () => {
  try {
    const res = await getDecorationSectionByType('solution');
    if (res.rows && res.rows.length > 0) {
      const data = res.rows[0];
      headerConfig.value = {
        id: data.id,
        title: data.title || '热门方案',
        subtitle: data.subtitle || '为采购人提供"业务+服务"的项目解决方案',
        linkText: data.linkText || '更多方案',
        linkUrl: data.linkUrl || '',
        bgColor: data.bgColor || '#ffffff',
        textColor: data.textColor || '#303133'
      };
    }
  } catch (error) {
    console.error('加载标题配置失败', error);
  }
};

const handleEditHeader = () => {
  Object.assign(headerForm, headerConfig.value);
  headerDialog.visible = true;
};

const saveHeaderConfig = async () => {
  try {
    const data = {
      ...headerForm,
      sectionType: 'solution'
    };
    if (headerForm.id) {
      await updateDecorationSection(data);
    } else {
      await addDecorationSection(data);
    }
    await loadHeaderConfig();
    headerDialog.visible = false;
    ElMessage.success('标题配置已保存');
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

const handleLinkClick = () => {
  if (headerConfig.value.linkUrl) {
    window.open(headerConfig.value.linkUrl, '_blank');
  }
};

const form = reactive({
  id: undefined as number | undefined,
  title: '',
  description: '',
  imageUrl: '',
  sort: 0,
  adType,
  status: 1
});

const rules = {
  title: [{ required: true, message: '方案标题不能为空', trigger: 'blur' }],
  description: [{ required: true, message: '方案描述不能为空', trigger: 'blur' }]
};

const dialog = reactive({ visible: false, title: '' });
const loading = ref(false);
const solutionList = ref<any[]>([]);
const solutionFormRef = ref();

// 获取方案列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await listAdContent({ adType });
    const rows = res.rows || [];
    // 收集所有ossId，批量查询真实URL
    const ossIds = rows.map((item: any) => item.imageUrl).filter((id: string) => id && /^\d+$/.test(id));
    if (ossIds.length > 0) {
      const ossRes = await listByIds(ossIds.join(','));
      const ossMap = new Map(ossRes.data.map((oss: any) => [String(oss.ossId), oss.url]));
      rows.forEach((item: any) => {
        // 保存原始ossId用于编辑回显
        item.imageOssId = item.imageUrl;
        if (item.imageUrl && ossMap.has(item.imageUrl)) {
          item.imageUrl = ossMap.get(item.imageUrl);
        }
      });
    }
    // 字段映射：remark -> description
    rows.forEach((item: any) => {
      item.description = item.remark || '';
    });
    solutionList.value = rows;
  } catch (error) {
    console.error('获取方案列表失败', error);
    solutionList.value = [];
  } finally {
    loading.value = false;
  }
};

const handleUpdate = (row: any) => {
  reset();
  Object.assign(form, {
    ...row,
    // 编辑时用ossId，这样image-upload组件才能正确回显
    imageUrl: row.imageOssId || row.imageUrl || '',
    description: row.description || row.remark || ''
  });
  dialog.visible = true;
  dialog.title = '编辑方案';
};

const submitForm = async () => {
  solutionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 字段映射：description -> remark
        const data = {
          ...form,
          adType,
          remark: form.description,
          status: 1
        };
        await updateAdContent(data);
        ElMessage.success('保存成功');
        dialog.visible = false;
        getList();
      } catch (error) {
        ElMessage.error('保存失败');
      }
    }
  });
};

const cancel = () => {
  dialog.visible = false;
  reset();
};

const reset = () => {
  Object.assign(form, { id: undefined, title: '', description: '', imageUrl: '', sort: 0 });
  solutionFormRef.value?.resetFields();
};

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

<style scoped lang="scss">
.solution-container {
  height: 100%;
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;

  :deep(.el-card) {
    background: #f5f5f5;
    border: none;
    box-shadow: none;
    max-width: 1100px;
    margin: 0 auto;
  }

  :deep(.el-card__body) {
    padding: 0;
  }
}

.solution-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  max-width: 1100px;
  margin: 0 auto 12px;

  &:hover {
    background: #fafafa;
  }

  .header-left {
    display: flex;
    align-items: baseline;
    gap: 12px;

    .solution-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .solution-subtitle {
      font-size: 12px;
      color: #999;
    }
  }

  .header-right {
    .more-link {
      font-size: 12px;
      color: #666;
      cursor: pointer;

      &:hover {
        color: #333;
      }
    }
  }
}

.solution-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  background: #f5f5f5;
  margin-top: 10px;
  padding: 5px;
  max-width: 1100px;
  margin: 0 auto;
}

.solution-card {
  flex: 1 0 calc(20% - 4px);
  max-width: calc(20% - 4px);
  padding: 20px 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  box-sizing: border-box;
  background: #fff;

  &:hover {
    background: #fafafa;
  }

  @media (max-width: 1200px) {
    flex: 1 0 calc(25% - 4px);
    max-width: calc(25% - 4px);
  }

  @media (max-width: 900px) {
    flex: 1 0 calc(33.33% - 4px);
    max-width: calc(33.33% - 4px);
  }

  .card-title {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-bottom: 6px;
  }

  .card-desc {
    font-size: 12px;
    color: #999;
    margin-bottom: 20px;
  }

  .card-image {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100px;

    .solution-image {
      width: 100%;
      height: 100px;

      :deep(img) {
        object-fit: contain !important;
        max-width: 100%;
        max-height: 100px;
      }
    }

    .image-slot {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80px;
      height: 80px;
      background: #f5f5f5;
      border-radius: 4px;
      color: #ccc;
      font-size: 24px;
    }
  }
}
</style>
