<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import { onMounted, ref } from "vue";
import myAxios from "../../api/myAxios";
import { message } from "ant-design-vue";
import RichTextEditor from '../components/RichTextEditor.vue';
import {Form} from 'ant-design-vue'
import {downLoadImage} from "../../api/ImageUrl.ts";

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 editData = ref<ProjectDetail | null>(null);

const projectId = ref<string | null>(null);
const isEditing = ref(false);
const fileInput = ref<HTMLInputElement | null>(null);

function encode64(text: string): string {
  return btoa(encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, (_, p1) => {
    return String.fromCharCode(parseInt(p1, 16));
  }));
}

function decode64(text: string): string {
  return decodeURIComponent(
      Array.from(atob(text), char =>
          '%' + ('00' + char.charCodeAt(0).toString(16)).slice(-2)
      ).join('')
  );
}

const decryptProjectData = (data: ProjectDetail): ProjectDetail => {
  const decryptedData: ProjectDetail = { ...data };

  const fieldsToDecrypt: (keyof ProjectDetail)[] = [
    'projectName',
    'projectDescription',
    'settlementDesc',
    'projectDesc',
    'projectFlow',
    'applyPromoCodeDesc'
  ];

  fieldsToDecrypt.forEach(field => {
    const value = decryptedData[field];
    if (typeof value === 'string' && value) {
      try {
        (decryptedData as Record<keyof ProjectDetail, any>)[field] = decode64(value);
      } catch (error) {
        console.error(`Base64解码失败 (${field}):`, error);
        (decryptedData as Record<keyof ProjectDetail, any>)[field] = value;
      }
    }
  });

  return decryptedData;
};

// 图片上传处理逻辑
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) => {
      previewImage.value = 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 && res.data) {
      if (editData.value) {
        editData.value.projectImage = res.data;
      }
      message.success('图片上传成功');
    } else {
      throw new Error(res.message || '上传失败');
    }
  } catch (error) {
    console.error('上传失败：', error);
    message.error('文件上传失败');
    previewImage.value = '';
  } finally {
    if (input) input.value = '';
  }
};

const previewImage = ref('');

const formRef = ref<typeof Form>();



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

const finishEditing = async () => {
  try {
    if (!editData.value) {
      message.error('编辑数据不存在');
      return;
    }

    const storedToken = localStorage.getItem('token');
    if (!storedToken) {
      message.error('未找到登录信息');
      return;
    }

    const payload: Record<string, any> = { ...editData.value };

    const fieldsToEncode: (keyof ProjectDetail)[] = [
      'projectDescription',
      'settlementDesc',
      'projectDesc',
      'projectFlow',
      'applyPromoCodeDesc'
    ];

    fieldsToEncode.forEach(field => {
      const value = payload[field];
      if (typeof value === 'string' && value) {
        payload[field] = encode64(value);
      }
    });

    const res: any = await myAxios.post(
        "/project/update",
        JSON.stringify(payload),
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': storedToken
          }
        }
    );

    if (res.code === 1) {
      message.success('项目更新成功');
      projectData.value = editData.value;
      editData.value = null;
      router.push('/project')
    } else {
      message.error(res.message);
    }
  } catch (error) {
    console.error("更新失败:", error);
    message.error('项目更新失败');
  } finally {
    isEditing.value = false;
    previewImage.value = '';
  }
};

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) {
    message.warning("请输入项目ID");
    return;
  }

  if (!/^\d+$/.test(id)) {
    message.warning("ID必须为数字");
    return;
  }

  loading.value = true;
  try {
    const storedToken = localStorage.getItem('token');
    if (!storedToken) {
      message.error('未找到登录信息');
      return;
    }

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

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

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

const router = useRouter();

const goBack = () => {
  router.push('/project')
};

// 触发文件选择
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

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 limitSettlementCycle = (value: number) => {
  if (!editData.value) return;

  // 确保是数字
  if (isNaN(value)) {
    editData.value.projectSettlementCycle = 1;
    return;
  }

  // 限制在1-10之间
  if (value < 1) editData.value.projectSettlementCycle = 1;
  if (value > 10) editData.value.projectSettlementCycle = 10;
};

const limitPromoterCount = (value: number) => {
  if (!editData.value) return;

  // 确保是数字
  if (isNaN(value)) {
    editData.value.maxPromoterCount = 1;
    return;
  }

  // 限制在1-999999之间
  if (value < 1) editData.value.maxPromoterCount = 1;
  if (value > 999999) editData.value.maxPromoterCount = 999999;
};

// 添加输入时实时限制 - 立即修正值
const handleSettlementInput = (value: number) => {
  limitSettlementCycle(value);
};

const handlePromoterInput = (value: number) => {
  limitPromoterCount(value);
};
</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>
        <a-button class="custom-button" @click="updateProject">编辑项目</a-button>
        <a-button class="custom-button" @click="goBack">返回</a-button>
      </div>

      <!-- 基本信息 -->
      <div class="basic-info">
        <div class="project-image">
          <img :src="downLoadImage+projectData.projectImage" alt="项目封面图">
        </div>
        <div class="info-grid">
          <div class="info-item">
            <label>结算周期</label>
            <div class="value">T+{{ 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>

    <!-- 编辑页 -->
    <div v-if="isEditing && editData" class="add-project-container">
      <a-form ref="formRef" :model="editData" layout="vertical" @submit.prevent="finishEditing">
        <div class="form-section">
          <div class="form-header">
            <h2>项目基本信息</h2>
            <a-button class="custom-button" @click="isEditing = false">返回</a-button>
          </div>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="项目名称">
                <a-input v-model:value="editData.projectName" placeholder="请输入项目名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="项目状态">
                <a-select v-model:value="editData.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: 1,
          max: 10,
          message: '请输入1-10之间的数字'
        }]"
              >
                <a-input-number
                    v-model:value="editData.projectSettlementCycle"
                    style="width: 100%"
                    :min="1"
                    :max="10"
                    @keypress="handleNumberInput"
                    @paste="handlePaste"
                    @change="(val:any) => handleSettlementInput(val)"
                    placeholder="请输入1-10之间的数字"
                />
              </a-form-item>
            </a-col>

            <!-- 最大推广人数输入框 -->
            <a-col :span="12">
              <a-form-item
                  label="最大推广人数"
                  name="maxPromoterCount"
                  :rules="[{
          required: true,
          type: 'number',
          min: 1,
          max: 999999,
          message: '请输入1-999999之间的数字'
        }]"
              >
                <a-input-number
                    v-model:value="editData.maxPromoterCount"
                    style="width: 100%"
                    :min="1"
                    :max="999999"
                    @keypress="handleNumberInput"
                    @paste="handlePaste"
                    @change="(val:any) => handlePromoterInput(val)"
                    placeholder="请输入1-999999之间的数字"
                />
              </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-area" @click="triggerFileInput">
                <div class="upload-button">
                  <span>点击上传图片</span>
                  <div class="file-name">支持 JPG/PNG 格式，大小不超过 5MB</div>
                </div>
              </div>

              <div v-if="previewImage || editData.projectImage" class="preview-image">
                <img
                    v-if="previewImage"
                    :src="previewImage"
                    alt="上传预览"
                >
                <img
                    v-else
                    :src="downLoadImage + editData.projectImage"
                    alt="项目封面预览"
                >
              </div>
            </div>
          </a-form-item>

          <a-form-item label="项目描述">
            <textarea
                v-model="editData.projectDescription"
                class="textarea-field"
                placeholder="请输入项目简介..."
                maxlength="30"
            ></textarea>
            <div class="absolute right-2 bottom-2 text-xs text-gray-500">
              {{ editData.projectDescription.length }}/30
            </div>
          </a-form-item>
        </div>

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

          <div class="rich-text-container">
            <div class="rich-text-columns">
              <div class="rich-text-group">
                <span class="label-text">结算说明</span>
                <RichTextEditor
                    v-model="editData.settlementDesc"
                    :disable="false"
                    @content-change="(html: string) => { if (editData) editData.settlementDesc = html }"
                />
              </div>

              <div class="rich-text-group">
                <span class="label-text">项目说明</span>
                <RichTextEditor
                    v-model="editData.projectDesc"
                    :disable="false"
                    @content-change="(html: string) => { if (editData) editData.projectDesc = html }"
                />
              </div>

              <div class="rich-text-group">
                <span class="label-text">项目流程</span>
                <RichTextEditor
                    v-model="editData.projectFlow"
                    :disable="false"
                    @content-change="(html: string) => { if (editData) editData.projectFlow = html }"
                />
              </div>

              <div class="rich-text-group">
                <span class="label-text">申请推广码说明</span>
                <RichTextEditor
                    v-model="editData.applyPromoCodeDesc"
                    :disable="false"
                    @content-change="(html: string) => { if (editData) editData.applyPromoCodeDesc = html }"
                />
              </div>
            </div>
          </div>
        </div>

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

<style scoped>
.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.project-detail-container {
  width: 100%;
  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;
  flex-grow: 1;
}

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

  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
}

.add-project-container {
  width: 100%;
  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;
  margin-top: 2rem;
}

.ql-container {
  min-height: 120px;
}

.file-upload {
  position: relative;
  margin-top: 1rem;
}

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

.upload-area {
  cursor: pointer;
}

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

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

.upload-button span {
  font-weight: 500;
  color: #334155;
}

.file-name {
  color: #64748b;
  font-size: 0.85rem;
  margin-top: 0.5rem;
}

.preview-image {
  margin-top: 1rem;
  text-align: center;
}

.preview-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border: 1px solid #eee;
}

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

.custom-button:hover,
.custom-button:focus {
  background-color: #fa8c16;
  border-color: #fa8c16;
  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;
}

.rich-text-container {
  margin-top: 1.5rem;
}

.rich-text-columns {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 1rem;
  align-items: start;
}

.rich-text-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  height: 100%;
  border: 2px solid #e2e8f0;
  border-radius: 0.75rem;
  overflow: hidden;
  transition: all 0.3s ease;
  min-height: 320px;
  flex-grow: 1;
  padding: 10px;
  background: white;
}

.rich-text-group:focus-within {
  border-color: #6366f1;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.label-text {
  margin: 10px 0 0 5px;
  display: block;
  font-size: 0.95rem;
  font-weight: 600;
  color: #3b4151;
  padding-left: 0.2rem;
  transition: color 0.3s ease;
}

.rich-text-group:focus-within .label-text {
  color: #6366f1;
}

@media (max-width: 1280px) {
  .rich-text-columns {
    grid-template-columns: repeat(2, 1fr);
    gap: 1.2rem;
  }
}

@media (max-width: 768px) {
  .rich-text-columns {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
}

:deep(.ql-container) {
  height: 280px;
  border: none !important;
}

.textarea-field {
  min-height: 100px;
  resize: vertical;
}


.textarea-field:focus {
  border-color: #6366f1;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
  outline: none;
}


.textarea-field {
  width: 100%;
  padding: 0.8rem 1.2rem;
  border: 2px solid #e2e8f0;
  border-radius: 0.75rem;
  transition: all 0.3s ease;
  font-size: 1rem;
  background: white;
}
</style>