<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
                  v-model="formData.projectImage"
                  type="text"
                  class="input-field"
                  required
                  placeholder="请输入项目图片URL"
              >
            </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"
                class="input-field"
                required
                placeholder="请输入结算周期"
            >
          </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"
                class="input-field"
                required
                placeholder="请输入最大人数"
            >
          </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>
            <textarea
                v-model="formData.projectDescription"
                class="textarea-field"
                placeholder="请输入详细的项目描述..."
            ></textarea>
          </label>
        </div>

        <div class="input-group">
          <label class="input-label">
            <span class="label-text">结算说明</span>
            <div class="rich-text-editor">
              <QuillEditor
                  v-model:content="formData.settlementDesc"
                  contentType="html"
                  :options="editorOptions"
                  @change="onContentChange"
              />
            </div>
          </label>
        </div>

        <div class="input-group">
          <label class="input-label">
            <span class="label-text">项目说明</span>
            <div class="rich-text-editor">
              <QuillEditor
                  v-model:content="formData.projectDesc"
                  contentType="html"
                  :options="editorOptions"
                  @change="onContentChange"
              />
            </div>
          </label>
        </div>

        <div class="input-group">
          <label class="input-label">
            <span class="label-text">项目流程</span>
            <div class="rich-text-editor">
              <QuillEditor
                  v-model:content="formData.projectFlow"
                  contentType="html"
                  :options="editorOptions"
                  @change="onContentChange"
              />
            </div>
          </label>
        </div>

        <div class="input-group">
          <label class="input-label">
            <span class="label-text">申请推广码说明</span>
            <div class="rich-text-editor">
              <QuillEditor
                  v-model:content="formData.applyPromoCodeDesc"
                  contentType="html"
                  :options="editorOptions"
                  @change="onContentChange"
              />
            </div>
          </label>
        </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 } from 'vue';
import axios from 'axios';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import myAxios from "../../api/myAxios.ts";
import router from "../../router";

// 添加 Quill 配置类型
interface QuillOptions {
  theme: string;
  modules: {
    toolbar: Array<any[] | object>;
  };
  placeholder?: string;
}

// 定义富文本编辑器配置
const editorOptions: QuillOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ header: 1 }, { header: 2 }],
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }],
      ['link', 'image', 'video'],
      ['clean']
    ]
  },
  placeholder: '请输入内容...'
};

// 接口定义
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 formData = reactive<ProjectForm>({
  projectName: '',
  projectSettlementCycle: 2,
  maxPromoterCount: 200,
  projectStatus: 'running',
  projectDescription: '',
  settlementDesc: '',
  projectDesc: '',
  projectFlow: '',
  applyPromoCodeDesc: '',
  projectImage: ''
});

// 内容变化处理
const onContentChange = () => {
  // 更新预览内容
  const phoneContent = document.querySelector('.phone-content');
  if (phoneContent) {
    // 添加平滑滚动效果
    phoneContent.scrollTo({
      top: phoneContent.scrollHeight,
      behavior: 'smooth'
    });
  }
};

// 生命周期钩子
onMounted(() => {
  // 初始处理
  nextTick(() => {
    // 为手机预览添加初始样式
    const phoneScreen = document.querySelector('.phone-screen');
    if (phoneScreen) {
      // 添加阴影和动画效果
      phoneScreen.classList.add('animate-fade-in');
    }
  });
});

const handleSubmit = async () => {
  try {
    const storedToken = localStorage.getItem('token');
    console.log(formData.valueOf())

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

    if (res.code === 1) {
      alert('项目创建成功！');
      router.back();

      Object.assign(formData, {
        projectName: '',
        projectSettlementCycle: 2,
        maxPromoterCount: 200,
        projectStatus: 'running',
        projectDescription: '',
        settlementDesc: '',
        projectDesc: '',
        projectFlow: '',
        applyPromoCodeDesc: '',
        projectImage: ''
      });
    } else {
      alert(`创建失败：${res.data.message}`);
    }
  } catch (error) {
    console.error('请求失败：', error);
    if (axios.isAxiosError(error)) {
      // 显示详细错误信息
      const msg = error.response?.data?.message || error.message;
      alert(`请求错误（${error.response?.status}）：${msg}`);
    } else {
      alert('未知错误');
    }
  }
};
</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;
}

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

.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-editor {
  border: 2px solid #e2e8f0;
  border-radius: 0.75rem;
  overflow: hidden;
  transition: all 0.3s ease;
}

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

.ql-toolbar {
  border-top-left-radius: 0.75rem;
  border-top-right-radius: 0.75rem;
  background: #f8fafc;
}

.ql-container {
  border-bottom-left-radius: 0.75rem;
  border-bottom-right-radius: 0.75rem;
  min-height: 150px;
}

.ql-editor {
  font-family: inherit;
  font-size: 1rem;
}

.ql-editor.ql-blank::before {
  color: #94a3b8;
  font-style: normal;
}

/* 手机预览样式 */
.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;
}

/* 动画效果 */
.animate-fade-in {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>