<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';
import {Form} from 'ant-design-vue'

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 fileInput = ref<HTMLInputElement | null>(null);
const fileName = ref('');


// 图片上传处理逻辑
const handleFileUpload = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];

  if (!file) return;

  try {
    // 本地预览
    const reader = new FileReader();
    reader.onload = (e) => {
      projectData.value.projectImage = e.target?.result as string;
    };
    reader.readAsDataURL(file);

    // 上传服务器
    const uploadFormData = new FormData();
    uploadFormData.append('biz', 'project');
    uploadFormData.append('file', file);

    const storedToken = localStorage.getItem('token');
    const res: any = await myAxios.post('/file/upload', uploadFormData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': storedToken
      }
    });

    if (res.code === 1) {
      // 替换为服务器返回的正式地址
      projectData.value.projectImage = `${myAxios.defaults.baseURL}/file/get/${res.data}`;
      fileName.value = file.name;
      message.success('图片上传成功');
    }
  } catch (error) {
    console.error('上传失败：', error);
    message.error('文件上传失败');
    projectData.value.projectImage = '';
  }
};
const formRef = ref<typeof Form>(); // 添加表单引用

// 添加数字输入校验方法
const handleNumberInput = (e: KeyboardEvent) => {
  const allowedKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'];
  if (!allowedKeys.includes(e.key)) {
    e.preventDefault();
  }
};

// 添加粘贴校验方法
const handlePaste = (e: ClipboardEvent) => {
  const pasteData = e.clipboardData?.getData('text/plain');
  if (pasteData && !/^\d+$/.test(pasteData)) {
    e.preventDefault();
    message.error('只能粘贴数字');
  }
};

// 更新项目时提交处理
const finishEditing = async () => {
  //isEditing.value = false;

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

    // 转换富文本内容为字符串
    const payload = {
      ...projectData.value,
      settlementDesc: String(projectData.value.settlementDesc),
      projectDesc: String(projectData.value.projectDesc),
      projectFlow: String(projectData.value.projectFlow),
      applyPromoCodeDesc: String(projectData.value.applyPromoCodeDesc)
    };

    const res:any = await myAxios.post("/project/update",
        JSON.stringify(payload),
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': storedToken
          }
        }
    );
    console.log(res)
    if (res.code === 1) {
      message.success('项目更新成功');
      // 重新加载数据
      projectId.value && handleIdSearch(projectId.value);

    }
  } catch (error) {
    console.error("更新失败:", error);

    message.error('项目更新失败');
    return;
  }

};



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;
};


</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 class="custom-button" @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 ref="formRef" :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="结算周期（天）"
                  name="projectSettlementCycle"
                  :rules="[{
                required: true,
                type: 'number',
                min: 0,
                message: '请输入有效的正整数'
              }]"
              >
                <a-input-number
                    v-model:value="projectData.projectSettlementCycle"
                    style="width: 100%"
                    :min="0"
                    @keypress="handleNumberInput"
                    @paste="handlePaste"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                  label="最大推广人数"
                  name="maxPromoterCount"
                  :rules="[{
                required: true,
                type: 'number',
                min: 0,
                message: '请输入有效的正整数'
              }]"
              >
                <a-input-number
                    v-model:value="projectData.maxPromoterCount"
                    style="width: 100%"
                    :min="0"
                    @keypress="handleNumberInput"
                    @paste="handlePaste"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="项目图片">
            <div class="file-upload">
              <input
                  type="file"
                  class="file-input"
                  accept="image/*"
                  @change="handleFileUpload"
                  ref="fileInput"
              >
              <div class="upload-button" @click="fileInput?.click()">
                <span v-if="!projectData.projectImage">点击上传图片</span>
                <span v-else class="file-name">已选择：{{ fileName }}</span>
              </div>
              <div v-if="projectData.projectImage" class="preview-image">
                <img :src="projectData.projectImage" alt="项目封面预览">
              </div>
            </div>
          </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 class="custom-button" 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 #ffa940;
  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 #ffa940;
  padding-left: 0.8rem;
}

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

.ql-container {
  min-height: 120px;
}
.preview-image {
  margin-top: 1rem;
}

.preview-image img {
  max-width: 200px;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 保持原有上传样式 */
.file-upload {
  position: relative;
}

.file-input {
  opacity: 0;
  position: absolute;
  width: 1px;
  height: 1px;
}

.upload-button {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0.8rem 1.5rem;
  background: #f8fafc;
  border: 2px dashed #cbd5e1;
  border-radius: 0.75rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-button:hover {
  background: #f1f5f9;
  border-color: #94a3b8;
}

.file-name {
  color: #64748b;
  font-size: 0.9rem;
}

/*橙色按钮*/

.custom-button {
  background-color: #ffa940;
  border-color: #ffa940;
  color: #fff;
}

.custom-button:hover,
.custom-button:focus {
  background-color: #ffa940;
  border-color: #ffa940;
  color: #fff;
}

.custom-button[disabled] {
  background-color: #ffa940;
  border-color: #ffa940;
  opacity: 0.6;
  color: #fff;
}

/* 危险按钮样式 */
.custom-button.ant-btn-dangerous {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.custom-button.ant-btn-dangerous:hover,
.custom-button.ant-btn-dangerous:focus {
  background-color: #ff7875;
  border-color: #ff7875;
}

/* 保持原有的其他样式不变 */
.search-box {
  margin-bottom: 10px;
}

.custom-search :deep(.ant-input-search-button) {
  background-color: #ffa940;
  border-color: #ffa940;
}

.custom-search :deep(.ant-input-search-button:hover),
.custom-search :deep(.ant-input-search-button:focus) {
  background-color: #fa8c16;
  border-color: #fa8c16;
}

/* 保持输入框原有样式不变 */
.custom-search :deep(.ant-input) {
  border-right-color: #ffa940;
}
</style>