<template>
  <form @submit.prevent="handleSubmit" class="modern-form">
    <h2 class="form-title">新建推广项目</h2>

    <div class="form-grid">
      <!-- 左列 - 手机预览区域 -->
      <div class="form-column phone-preview-container">
        <div class="phone-frame">
          <div class="phone-header">
            <div class="phone-camera"></div>
            <div class="phone-speaker"></div>
          </div>

          <div class="phone-screen">
            <div class="phone-content">
              <!-- 项目信息 -->
              <div class="phone-project-info">
                <h2 class="phone-project-title">{{ formData.projectName }}</h2>
                <div class="phone-project-image" :style="{ backgroundImage: `url(${formData.projectImage})` }"></div>
                <p class="phone-project-desc">{{ formData.projectDescription }}</p>
              </div>

              <!-- 富文本内容区域 -->
              <div class="phone-sections">
                <!-- 结算说明 -->
                <div class="phone-section">
                  <h3 class="phone-section-title">结算说明</h3>
                  <div class="phone-section-content" v-html="formData.settlementDesc"></div>
                </div>

                <!-- 项目说明 -->
                <div class="phone-section">
                  <h3 class="phone-section-title">项目说明</h3>
                  <div class="phone-section-content" v-html="formData.projectDesc"></div>
                </div>

                <!-- 项目流程 -->
                <div class="phone-section">
                  <h3 class="phone-section-title">项目流程</h3>
                  <div class="phone-section-content" v-html="formData.projectFlow"></div>
                </div>

                <!-- 申请推广码说明 -->
                <div class="phone-section">
                  <h3 class="phone-section-title">申请推广码说明</h3>
                  <div class="phone-section-content" v-html="formData.applyPromoCodeDesc"></div>
                </div>
              </div>
            </div>
          </div>

          <div class="phone-home-button"></div>
        </div>
      </div>

      <!-- 右列 - 富文本编辑区域 -->
      <div class="form-column">
        <div class="input-group">
          <label class="input-label">
            <span class="label-text">项目名称</span>
            <input
                v-model="formData.projectName"
                type="text"
                class="input-field"
                required
                placeholder="请输入项目名称"
            >
          </label>
        </div>

        <div class="input-group">
          <label class="input-label">
            <span class="label-text">项目图片</span>
            <div class="file-upload">
              <input
                  type="file"
                  class="file-input"
                  accept="image/*"
                  @change="handleFileUpload"
                  ref="fileInput"
              >
              <div class="upload-button">
                <span v-if="!formData.projectImage">点击上传图片</span>
                <span v-else class="file-name">已选择：{{ fileName }}</span>
              </div>
            </div>
          </label>
        </div>

        <div class="input-group">
          <label class="input-label">
            <span class="label-text">结算周期（天）</span>
            <input
                v-model.number="formData.projectSettlementCycle"
                type="number"
                min="1"
                max="10"
                class="input-field"
                required
                placeholder="请输入结算周期(1-10)"
                @input="limitSettlementCycle"
                @keypress="filterNumericInput"
            >
          </label>
        </div>

        <div class="input-group">
          <label class="input-label">
            <span class="label-text">最大推广人数</span>
            <input
                v-model.number="formData.maxPromoterCount"
                type="number"
                min="1"
                max="999999"
                class="input-field"
                required
                placeholder="请输入最大人数(1-999999)"
                @input="limitPromoterCount"
                @keypress="filterNumericInput"
            >
          </label>
        </div>

        <div class="input-group">
          <label class="input-label">
            <span class="label-text">项目状态</span>
            <div class="select-wrapper">
              <select
                  v-model="formData.projectStatus"
                  class="select-field"
              >
                <option value="running">运行中</option>
                <option value="full">人数已满</option>
                <option value="paused">已暂停</option>
              </select>
              <div class="select-arrow">▼</div>
            </div>
          </label>
        </div>
        <div class="input-group">
          <label class="input-label">
            <span class="label-text">项目简介</span>
            <div class="relative">
<textarea
    v-model="formData.projectDescription"
    class="textarea-field"
    placeholder="请输入项目简介..."
    maxlength="30"
></textarea>
              <div class="absolute right-2 bottom-2 text-xs text-gray-500">
                {{ formData.projectDescription.length }}/30
              </div>
            </div>
          </label>
        </div>
      </div>
    </div>

    <div class="rich-text-container">
      <div class="rich-text-columns">

        <div class="rich-text-group">
          <span class="label-text">结算说明</span>
          <RichTextEditor
              v-model="formData.settlementDesc"
              :disable="false"
              @content-change="(html:any) => formData.settlementDesc = html"
          />
        </div>

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

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

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

    <button type="submit" class="submit-button">
      <span>立即创建</span>
      <div class="button-sparkles"></div>
    </button>
  </form>
</template>


<script setup lang="ts">
import { reactive, onMounted, nextTick,ref } from 'vue';
import RichTextEditor from '../components/RichTextEditor.vue';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import myAxios from "../../api/myAxios.ts";
import router from "../../router";


interface ProjectForm {
  projectName: string;
  projectImage: string;
  projectSettlementCycle: number;
  maxPromoterCount: number;
  projectStatus: 'running' | 'full' | 'paused';
  projectDescription: string;
  settlementDesc: string;
  projectDesc: string;
  projectFlow: string;
  applyPromoCodeDesc: string;
}

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 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) {
      formData.projectImage = res.data;
      fileName.value = file.name;
    }
  } catch (error) {
    console.error('上传失败：', error);
    alert('文件上传失败');
  }
};

// 响应式表单数据
const formData = reactive<ProjectForm>({
  projectName: '',
  projectSettlementCycle: 2,
  maxPromoterCount: 200,
  projectStatus: 'running',
  projectDescription: '',
  settlementDesc: '',
  projectDesc: '',
  projectFlow: '',
  applyPromoCodeDesc: '',
  projectImage: ''
});

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


onMounted(() => {
  nextTick(() => {
    const phoneScreen = document.querySelector('.phone-screen');
    if (phoneScreen) {
      phoneScreen.classList.add('animate-fade-in');
    }
  });
});

const encryptValue = (value: any, key: string): any => {
  if (key === 'projectStatus') {
    return value;
  }

  if (key === 'projectSettlementCycle' || key === 'maxPromoterCount' || key === 'projectImage' || key === 'projectName') {
    return value;
  }

  try {

    const valueString = typeof value === 'object'
        ? JSON.stringify(value)
        : String(value);

    // 使用Base64编码数据
    return encode64(valueString);
  } catch (error) {
    console.error('Base64编码失败:', error);
    return value; // 编码失败返回原始值
  }
};

const handleSubmit = async () => {
  try {
    // 表单验证
    if (!validateForm()) {
      alert('请填写所有必填字段');
      return;
    }

    const storedToken = localStorage.getItem('token');

    const encryptedFormData: Record<string, any> = {};

    console.log("===== 字段Base64编码结果 =====");
    Object.entries(formData).forEach(([key, value]) => {

      if (value === null || value === undefined || value === '') return;

      // 对字段值进行Base64编码
      encryptedFormData[key] = encryptValue(value, key);

      // 打印编码结果
      console.log(`字段: ${key}`);
      console.log(`原始值: ${value}`);
      console.log(`编码值: ${encryptedFormData[key]}`);
      console.log(`类型: ${typeof encryptedFormData[key]}`);
      console.log('----------------------');
    });
    console.log("=======================");

    // 发送Base64编码后的数据
    const res: any = await myAxios.post(`/project/add`, encryptedFormData, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': storedToken
      }
    });
    if (res.code === 1) {
      alert('项目创建成功！');
      // 重置表单
      Object.assign(formData, {
        projectName: '',
        projectSettlementCycle: '',
        maxPromoterCount: '',
        projectStatus: 'running',
        projectDescription: '',
        settlementDesc: '',
        projectDesc: '',
        projectFlow: '',
        applyPromoCodeDesc: '',
        projectImage: ''
      });
      fileName.value = ''; // 重置文件名
      router.push('/project');
    } else {
      alert(`创建失败：${res.message}`);
    }
  } catch (error) {
    console.error('请求失败：', error);
    alert('提交失败，请检查控制台获取详细信息');
  }
};

const validateForm = (): boolean => {
  const requiredFields: (keyof ProjectForm)[] = [
    'projectName',
    'projectImage',
    'projectSettlementCycle',
    'maxPromoterCount',
    'projectStatus',
    'projectDescription',
    'settlementDesc',
    'projectDesc',
    'projectFlow',
    'applyPromoCodeDesc'
  ];

  return requiredFields.every(field => {
    const value = formData[field];
    return value !== '' && value !== null && value !== undefined;
  });
};
const filterNumericInput = (event: KeyboardEvent) => {
  const key = event.key;
  // 只允许数字输入
  if (!/^\d$/.test(key)) {
    event.preventDefault();
  }
};

const limitSettlementCycle = (event: Event) => {
  const input = event.target as HTMLInputElement;
  let value = parseInt(input.value);

  if (isNaN(value)) {
    formData.projectSettlementCycle = 1;
    return;
  }

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

  formData.projectSettlementCycle = value;
};

const limitPromoterCount = (event: Event) => {
  const input = event.target as HTMLInputElement;
  let value = parseInt(input.value);

  if (isNaN(value)) {
    formData.maxPromoterCount = 1;
    return;
  }

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

  formData.maxPromoterCount = value;
};
</script>


<style scoped>
.modern-form {
  max-width: 90%;
  margin: 2rem auto;
  padding: 2.5rem;
  background: white;
  border-radius: 1.5rem;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
  font-family: 'Segoe UI', system-ui, sans-serif;
}

.form-title {
  text-align: center;
  font-size: 1.8rem;
  color: #2c3e50;
  margin-bottom: 2rem;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

.input-group {
  margin-bottom: 1.5rem;
}

.input-label {
  display: block;
}

.label-text {
  display: block;
  margin-bottom: 0.6rem;
  color: #4a5568;
  font-size: 0.9rem;
  font-weight: 500;
}

.input-field,
.select-wrapper,
.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;
}

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

.file-upload {
  position: relative;
  display: inline-block;
  width: 100%;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
  z-index: 2; /* 确保文件输入在按钮上方 */
}


.upload-button {
  position: relative;
  z-index: 1;
  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;
}

.select-wrapper {
  position: relative;
}

.select-field {
  appearance: none;
  width: 100%;
  background: transparent;
  border: none;
  padding-right: 2rem;
}

.select-arrow {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #94a3b8;
  pointer-events: none;
}

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

.submit-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 1rem;
  margin-top: 1.5rem;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: 0.75rem;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.submit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(99, 102, 241, 0.3);
}

.button-sparkles {
  position: absolute;
  width: 20px;
  height: 20px;
  background: rgba(255,255,255,0.4);
  border-radius: 50%;
  animation: sparkle 1.5s infinite;
}

@keyframes sparkle {
  0% { transform: scale(0) translate(0,0); }
  50% { transform: scale(1) translate(100px, -50px); }
  100% { transform: scale(0) translate(200px, -100px); }
}

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

  .modern-form {
    padding: 1.5rem;
    margin: 1rem;
  }
}

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

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


/* 响应式调整 */
@media (max-width: 1440px) {
  .rich-text-columns {
    gap: 0.8rem;
  }
}

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

.rich-text-group {
  border: 2px solid #e2e8f0;
  border-radius: 0.75rem;
  overflow: hidden;
  transition: all 0.3s ease;
  min-height: 320px;
  height: auto;
  flex-grow: 1;

  &:focus-within {
    border-color: #6366f1 !important;
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
  }
}


.rich-text-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  height: 100%;
  border-radius: 15px;

  &:focus-within .label-text {
    color: #6366f1;
    transition: color 0.3s ease;

  }
}

.rich-text-group .label-text {
  font-size: 0.95rem;
  font-weight: 600;
  color: #3b4151;
  padding-left: 0.2rem;
  transition: color 0.3s ease;
}


.phone-preview-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.phone-frame {
  position: relative;
  width: 320px;
  height: 640px;
  background: #000;
  border-radius: 40px;
  padding: 15px;
  box-shadow: 0 0 0 12px #1f1f1f, 0 0 30px rgba(0,0,0,0.3);
}

.phone-header {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 180px;
  height: 25px;
  background: #000;
  border-radius: 12px;
}

.phone-camera {
  position: absolute;
  top: 50%;
  left: 20px;
  transform: translateY(-50%);
  width: 10px;
  height: 10px;
  background: #15294c;
  border-radius: 50%;
}

.phone-speaker {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 6px;
  background: #1f1f1f;
  border-radius: 3px;
}

.phone-screen {
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  border-radius: 28px;
  overflow: hidden;
  position: relative;
}

.phone-content {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.phone-home-button {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #1f1f1f;
  cursor: pointer;
}

.phone-project-info {
  margin-bottom: 20px;
}

.phone-project-title {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 10px;
  color: #2c3e50;
}

.phone-project-image {
  width: 100%;
  height: 180px;
  background-size: cover;
  background-position: center;
  border-radius: 12px;
  margin-bottom: 10px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.phone-project-desc {
  font-size: 0.9rem;
  color: #4a5568;
  line-height: 1.4;
}

.phone-sections {
  margin-top: 20px;
}

.phone-section {
  margin-bottom: 20px;
}

.phone-section-title {
  font-size: 1rem;
  font-weight: 600;
  margin-bottom: 8px;
  color: #2c3e50;
  border-bottom: 1px solid #e2e8f0;
  padding-bottom: 5px;
}

.phone-section-content {
  font-size: 0.9rem;
  color: #4a5568;
  line-height: 1.6;
}

.phone-section-content * {
  max-width: 100%;
}

.phone-section-content img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 10px 0;
}

.phone-section-content h1,
.phone-section-content h2,
.phone-section-content h3 {
  color: #2c3e50;
  margin-top: 15px;
  margin-bottom: 10px;
}

.phone-section-content p {
  margin-bottom: 10px;
}

.phone-section-content ul,
.phone-section-content ol {
  margin-left: 20px;
  margin-bottom: 10px;
}



@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
.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;
}
</style>