<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.name }}</h2>
                <div class="phone-project-image" :style="{ backgroundImage: `url(${formData.image})` }"></div>
                <div class="phone-prices">
                  <span class="origin-price">¥{{ formData.originPrice }}</span>
                  <span class="discount-price">¥{{ formData.discountPrice }}</span>
                </div>
              </div>

              <!-- 富文本内容区域 -->
              <div class="phone-sections">
                <!-- 课程详情 -->
                <div class="phone-section">
                  <h3 class="phone-section-title">课程详情</h3>
                  <div class="phone-section-content" v-html="formData.detail"></div>
                </div>

                <!-- 推广码说明 -->
                <div class="phone-section">
                  <h3 class="phone-section-title">推广码说明</h3>
                  <div class="phone-section-content" v-html="formData.promoCodeDesc"></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.name"
                type="text"
                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.type"
                  class="select-field"
                  required
              >
                <option value="">请选择课程类型</option>
                <option value="考公考研">考公考研</option>
                <option value="自媒体">自媒体</option>
                <option value="财经">财经</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="file-upload">
              <input
                  type="file"
                  class="file-input"
                  accept="image/*"
                  @change="handleFileUpload"
                  ref="fileInput"
              >
              <div class="upload-button">
                <span v-if="!formData.image">点击上传图片</span>
                <span v-else class="file-name">已选择：{{ fileName }}</span>
              </div>
            </div>
          </label>
        </div>

        <div class="price-group">
          <div class="input-group">
            <label class="input-label">
              <span class="label-text">原价（元）</span>
              <input
                  v-model.number="formData.originPrice"
                  type="number"
                  min="0"
                  class="input-field"
                  required
                  placeholder="请输入原价"
                  @input="validatePrices"
              >
            </label>
          </div>

          <div class="input-group">
            <label class="input-label">
              <span class="label-text">折扣价（元）</span>
              <input
                  v-model.number="formData.discountPrice"
                  type="number"
                  min="0"
                  class="input-field"
                  required
                  placeholder="请输入折扣价"
                  @input="validatePrices"
              >
            </label>
          </div>
        </div>

        <div class="commission-group">
          <div class="input-group">
            <label class="input-label">
              <span class="label-text">一级佣金比例（%）</span>
              <input
                  v-model.number="formData.firstLevelRate"
                  type="number"
                  min="1"
                  max="99"
                  class="input-field"
                  required
                  placeholder="1-99"
                  @input="validateRates"
              >
            </label>
          </div>

          <div class="input-group">
            <label class="input-label">
              <span class="label-text">二级佣金比例（%）</span>
              <input
                  v-model.number="formData.secondLevelRate"
                  type="number"
                  min="1"
                  max="99"
                  class="input-field"
                  required
                  placeholder="1-99"
                  @input="validateRates"
              >
            </label>
          </div>
        </div>
      </div>
    </div>

    <!-- 富文本编辑器区域 - 修改为50%宽度 -->
    <div class="rich-text-container">
      <div class="rich-text-columns">
        <div class="rich-text-group">
          <span class="label-text">课程详情</span>
          <RichTextEditor
              v-model="formData.detail"
              :disable="false"
              @content-change="(html:any) => formData.detail = html"
          />
        </div>

        <div class="rich-text-group">
          <span class="label-text">推广码说明</span>
          <RichTextEditor
              v-model="formData.promoCodeDesc"
              :disable="false"
              @content-change="(html:any) => formData.promoCodeDesc = 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, 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 CourseForm {
  name: string;
  type: string;
  image: string;
  detail: string;
  promoCodeDesc: string;
  originPrice: number;
  discountPrice: number;
  firstLevelRate: number;
  secondLevelRate: number;
}

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

const formData = reactive<CourseForm>({
  name: '',
  type: '',
  image: '',
  detail: '',
  promoCodeDesc: '',
  originPrice: 0,
  discountPrice: 0,
  firstLevelRate: 0,
  secondLevelRate: 0
});

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

const encryptValue = (value: any, key: string): any => {
  // 数值型字段直接返回，不加密
  if (key === 'originPrice' || key === 'discountPrice' ||
      key === 'firstLevelRate' || key === 'secondLevelRate' ||
      key === 'image' || key ==='name'||key === 'type') {
    return value;
  }

  try {
    const valueString = typeof value === 'object'
        ? JSON.stringify(value)
        : String(value);
    return encode64(valueString);
  } catch (error) {
    console.error('Base64编码失败:', error);
    return value;
  }
};

// 验证函数
const validatePrices = () => {
  if (formData.discountPrice >= formData.originPrice) {
    return false;
  }
  return true;
};

const validateRates = () => {
  if (formData.secondLevelRate >= formData.firstLevelRate) {
    return false;
  }
  return true;
};

const handleSubmit = async () => {
  // 验证价格和佣金比例
  const isPriceValid = validatePrices();
  const isRateValid = validateRates();

  let errorMessage = '';

  if (!isPriceValid) {
    errorMessage += '折扣价必须小于原价\n';
  }

  if (!isRateValid) {
    errorMessage += '二级佣金比例必须小于一级佣金比例\n';
  }

  if (errorMessage) {
    alert(errorMessage);
    return;
  }

  try {
    if (!validateForm()) {
      alert('请填写所有必填字段');
      return;
    }

    const storedToken = localStorage.getItem('token');
    const encryptedFormData: Record<string, any> = {};

    Object.entries(formData).forEach(([key, value]) => {
      if (value === null || value === undefined || value === '') return;
      encryptedFormData[key] = encryptValue(value, key);
    });

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

    if (res.code === 1) {
      alert('课程创建成功！');
      Object.assign(formData, {
        name: '',
        type: '',
        image: '',
        detail: '',
        promoCodeDesc: '',
        originPrice: 0,
        discountPrice: 0,
        firstLevelRate: 0,
        secondLevelRate: 0
      });
      fileName.value = '';
      router.push('/courseManagement');
    } else {
      alert(`创建失败：${res.message}`);
    }
  } catch (error) {
    console.error('请求失败：', error);
    alert('提交失败，请检查控制台获取详细信息');
  }
};

const validateForm = (): boolean => {
  const requiredFields: (keyof CourseForm)[] = [
    'name',
    'type',
    'image',
    'detail',
    'promoCodeDesc',
    'originPrice',
    'discountPrice',
    'firstLevelRate',
    'secondLevelRate'
  ];

  return requiredFields.every(field => {
    const value = formData[field];
    return value !== '' && value !== null && value !== undefined;
  });
};
</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;
}

.price-group,
.commission-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

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

.select-wrapper:hover {
  border-color: #cbd5e1;
}

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

.select-field {
  appearance: none;
  width: 100%;
  padding: 0.8rem 1.2rem;
  border: none;
  background: transparent;
  font-size: 1rem;
  color: #4a5568;
  cursor: pointer;
  outline: none;
  border-radius: 0.75rem;
  height: 44px; /* 与其他输入框高度一致 */
}

.select-field:focus {
  outline: none;
}

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

.select-wrapper:focus-within .select-arrow {
  transform: translateY(-50%) rotate(180deg);
}

/* 下拉选项样式 */
.select-field option {
  padding: 8px 12px;
  background: white;
  color: #4a5568;
}

.select-field option:hover {
  background: #f1f5f9;
}

.select-field option:checked {
  background: #6366f1;
  color: white;
}

/* 当选择框有值时改变样式 */
.select-field:not([value=""]) {
  color: #2c3e50;
  font-weight: 500;
}

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

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

  .price-group,
  .commission-group {
    grid-template-columns: 1fr;
  }
}

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

.rich-text-columns {
  display: grid;
  grid-template-columns: repeat(2, 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;
}

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

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

.rich-text-group .label-text {
  font-size: 0.95rem;
  font-weight: 600;
  color: #3b4151;
  padding: 12px 12px 0;
}

/* 手机预览样式 */
.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-prices {
  display: flex;
  gap: 10px;
  align-items: center;
}

.origin-price {
  text-decoration: line-through;
  color: #94a3b8;
  font-size: 0.9rem;
}

.discount-price {
  color: #ef4444;
  font-size: 1.1rem;
  font-weight: 600;
}

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

</style>