<script setup lang="ts">
import { useRoute } from "vue-router";
import { onMounted, ref } from "vue";
import myAxios from "../../api/myAxios";
import { message } from "ant-design-vue";
import { QuillEditor } from '@vueup/vue-quill';

interface ProjectDetail {
  id: number;
  projectName: string;
  projectImage: string;
  projectSettlementCycle: number;
  maxPromoterCount: number;
  projectStatus: string;
  projectDescription: string;
  settlementDesc: string;
  projectDesc: string;
  projectFlow: string;
  applyPromoCodeDesc: string;
}

const route = useRoute();
const loading = ref(false);
const projectData = ref<ProjectDetail>({
  id: 0,
  projectName: '',
  projectImage: '',
  projectSettlementCycle: 0,
  maxPromoterCount: 0,
  projectStatus: '',
  projectDescription: '',
  settlementDesc: '',
  projectDesc: '',
  projectFlow: '',
  applyPromoCodeDesc: ''
});
const projectId = ref<string | null>(null);
const isEditing = ref(false);

// 状态映射
// const statusMap = {
//   running: { text: '运行中', color: '#52c41a' },
//   full: { text: '人数已满', color: '#f5222d' },
//   paused: { text: '已暂停', color: '#faad14' }
// };

if (typeof route.query.id === 'string') {
  projectId.value = route.query.id;
}

onMounted(() => {
  if(projectId.value !== null) {
    handleIdSearch(projectId.value);
  }
});

const handleIdSearch = async (id: string) => {
  if (!id) return message.warning("请输入项目ID");
  if (!/^\d+$/.test(id)) return message.warning("ID必须为数字");

  loading.value = true;
  try {
    const storedToken = localStorage.getItem('token');
    if (!storedToken) throw new Error('未找到登录信息');

    const res:any = await myAxios.post("/project/queryById",
        { id: parseInt(id) },
        { headers: { Authorization: storedToken } }
    );

    if (res.code === 1 && res.data) {
      console.log('Received project data:', res.data);
      projectData.value = res.data;
    } else {
      message.error(res.message || '查询失败');
    }
  } catch (error) {
    console.error("查询失败:", error);
    message.error('项目查询失败');
  } finally {
    loading.value = false;
  }
};

const updateProject = () => {
  if (!projectData.value) {
    message.warning('项目数据尚未加载完成，请稍后再试');
    return;
  }
  isEditing.value = true;
};

const finishEditing = async () => {
  isEditing.value = false;

  // 发送更新请求
  try {
    const storedToken = localStorage.getItem('token');
    if (!storedToken) throw new Error('未找到登录信息');

    const res:any = await myAxios.post("/project/update",
        projectData.value,
        { headers: { Authorization: storedToken } }
    );

    if (res.code === 1) {
      message.success('项目更新成功');
    } else {
      message.error(res.message || '更新失败');
    }
  } catch (error) {
    console.error("更新失败:", error);
    message.error('项目更新失败');
  }
};

// 图片上传相关方法
const handlePreview = (file:any) => {
  window.open(file.url || file.thumbUrl);
};

const handleChange = ({ fileList }:any) => {
  if (fileList.length > 0 && fileList[0].response?.url) {
    projectData.value.projectImage = fileList[0].response.url;
  }
};
</script>


<template>
  <div class="project-detail-container">

    <!-- 加载中 -->
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 详情页 -->
    <div v-if="projectData && !isEditing" class="detail-card">
      <!-- 头部区域 -->
      <div class="header-section">
        <h1 class="project-title">{{ projectData.projectName }}</h1>
<!--        <div class="status-tag" :style="{ backgroundColor: statusMap[projectData.projectStatus]?.color }">-->
<!--          {{ statusMap[projectData.projectStatus]?.text }}-->
<!--        </div>-->
        <a-button type="primary" @click="updateProject">编辑项目</a-button>
      </div>

      <!-- 基本信息 -->
      <div class="basic-info">
        <div class="project-image">
          <img :src="projectData.projectImage" alt="项目封面图">
        </div>
        <div class="info-grid">
          <div class="info-item">
            <label>结算周期</label>
            <div class="value">{{ projectData.projectSettlementCycle }} 天</div>
          </div>
          <div class="info-item">
            <label>最大推广人数</label>
            <div class="value">{{ projectData.maxPromoterCount }}</div>
          </div>
        </div>
      </div>

      <!-- 项目简介 -->
      <div class="section">
        <h2 class="section-title">项目简介</h2>
        <div class="section-content">{{ projectData.projectDescription }}</div>
      </div>

      <!-- 富文本内容区块 -->
      <div class="rich-section" v-if="projectData.settlementDesc">
        <h2 class="section-title">结算说明</h2>
        <div class="rich-content" v-html="projectData.settlementDesc"></div>
      </div>

      <div class="rich-section" v-if="projectData.projectDesc">
        <h2 class="section-title">项目说明</h2>
        <div class="rich-content" v-html="projectData.projectDesc"></div>
      </div>

      <div class="rich-section" v-if="projectData.projectFlow">
        <h2 class="section-title">项目流程</h2>
        <div class="rich-content" v-html="projectData.projectFlow"></div>
      </div>

      <div class="rich-section" v-if="projectData.applyPromoCodeDesc">
        <h2 class="section-title">申请推广码说明</h2>
        <div class="rich-content" v-html="projectData.applyPromoCodeDesc"></div>
      </div>
    </div>

    <!-- ✅ 编辑页 - 使用 addProject.vue 结构 -->
    <div v-if="isEditing && projectData" class="add-project-container">
      <a-form :model="projectData" layout="vertical" @submit.prevent="finishEditing">
        <div class="form-section">
          <h2>项目基本信息</h2>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="项目名称">
                <a-input v-model:value="projectData.projectName" placeholder="请输入项目名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="项目状态">
                <a-select v-model:value="projectData.projectStatus" placeholder="请选择状态">
                  <a-select-option value="running">运行中</a-select-option>
                  <a-select-option value="full">人数已满</a-select-option>
                  <a-select-option value="paused">已暂停</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="结算周期（天）">
                <a-input-number v-model:value="projectData.projectSettlementCycle" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="最大推广人数">
                <a-input-number v-model:value="projectData.maxPromoterCount" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="项目图片">
            <a-upload
                list-type="picture-card"
                :file-list="projectData.projectImage ? [{ uid: '-1', url: projectData.projectImage }] : []"
                @preview="handlePreview"
                @change="handleChange"
                :showUploadList="{ showRemoveIcon: false }"
                :beforeUpload="() => false"
            >
              点击上传
            </a-upload>
          </a-form-item>

          <a-form-item label="项目描述">
            <a-textarea v-model:value="projectData.projectDescription" :rows="4" />
          </a-form-item>
        </div>

        <div class="form-section">
          <h2>富文本配置</h2>

          <a-form-item label="结算说明">
            <QuillEditor v-model:content="projectData.settlementDesc" content-type="html" />
          </a-form-item>

          <a-form-item label="项目说明">
            <QuillEditor v-model:content="projectData.projectDesc" content-type="html" />
          </a-form-item>

          <a-form-item label="项目流程">
            <QuillEditor v-model:content="projectData.projectFlow" content-type="html" />
          </a-form-item>

          <a-form-item label="申请推广码说明">
            <QuillEditor v-model:content="projectData.applyPromoCodeDesc" content-type="html" />
          </a-form-item>
        </div>

        <div class="form-actions">
          <a-button type="primary" htmlType="submit">完成编辑</a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>

<style scoped>
.project-detail-container {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.loading {
  text-align: center;
  font-size: 1.2rem;
  color: #666;
  padding: 2rem;
}

.detail-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  padding: 2rem;
}

.header-section {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
  gap: 1rem;
}

.project-title {
  font-size: 2rem;
  color: #1a1a1a;
  margin: 0;
}

.status-tag {
  padding: 4px 12px;
  border-radius: 16px;
  color: white;
  font-size: 0.9rem;
}

.basic-info {
  display: grid;
  grid-template-columns: 100px 1fr;
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.project-image img {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
}

.info-item {
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
}

.info-item label {
  display: block;
  color: #666;
  font-size: 0.85rem;
  margin-bottom: 0.4rem;
}

.info-item .value {
  font-size: 1rem;
  color: #1a1a1a;
  font-weight: 500;
}

.section {
  margin-bottom: 2.5rem;
}

.section-title {
  font-size: 1.4rem;
  color: #1a1a1a;
  border-left: 4px solid #1890ff;
  padding-left: 1rem;
  margin: 1.5rem 0;
}

.section-content {
  line-height: 1.6;
  color: #444;
}

.rich-section {
  margin-bottom: 2.5rem;
}

.rich-content {
  background: #f8f9fa;
  padding: 1.5rem;
  border-radius: 8px;
  line-height: 1.7;
}

.rich-content :deep(p) {
  margin: 0.8em 0;
}

.rich-content :deep(h2) {
  color: #1a1a1a;
  margin: 1.2em 0 0.8em;
}

.rich-content :deep(ul) {
  padding-left: 1.5em;
}

.rich-content :deep(li) {
  margin: 0.5em 0;
}

@media (max-width: 768px) {
  .basic-info {
    grid-template-columns: 1fr;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .project-title {
    font-size: 1.6rem;
  }
}


.form-group label {
  display: block;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 0.6rem;
  font-size: 1rem;
  border: 1px solid #ccc;
  border-radius: 6px;
  resize: vertical;
}

.form-group textarea {
  height: 100px;
}

.add-project-container {
  max-width: 960px;
  margin: 2rem auto;
  padding: 2rem;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.form-section {
  margin-bottom: 2.5rem;
}

.form-section h2 {
  font-size: 1.3rem;
  margin-bottom: 1.5rem;
  color: #1a1a1a;
  border-left: 4px solid #1890ff;
  padding-left: 0.8rem;
}

.form-actions {
  text-align: right;
}

.ql-container {
  min-height: 120px;
}
</style>