<template>
  <div class="train-form bg-white p-6 rounded h-full overflow-y-auto">
    <div class="form-breadcrumb mb-4 text-gray-400 text-sm">
      课程管理 / 培训课程 / {{ initialData ? '编辑' : '新增' }}{{ type === 'video' ? '视频' : '线下' }}培训
    </div>
    <div class="form-header flex items-center mb-8">
      <span class="font-bold text-xl">{{ initialData ? '编辑' : '新增' }}{{ type === 'video' ? '视频培训' : '线下培训' }}</span>
    </div>

    <div class="form-wrapper border-2 border-blue-500 rounded-lg p-10 bg-white relative">
      <div class="section-title font-bold mb-8 text-base">基础信息</div>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="培训名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入培训名称" style="width: 400px" />
        </el-form-item>

        <template v-if="type === 'video'">
          <el-form-item label="培训封面" prop="thumbnail" required>
            <div class="thumbnail-uploader">
              <el-upload
                class="avatar-uploader"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
              >
                <img v-if="form.thumbnail" :src="form.thumbnail" class="avatar-preview" />
                <el-icon v-else class="avatar-uploader-icon"><i-ep-plus /></el-icon>
              </el-upload>
              <div class="upload-hint text-gray-400 text-xs mt-2">
                建议尺寸640*320，小于10M的JPG、PNG格式图片
              </div>
            </div>
          </el-form-item>

          <el-form-item label="课程描述" prop="description" required>
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="从零开始学西班牙语，直达欧标B2水平！"
              style="width: 500px"
            />
          </el-form-item>

          <el-form-item label="课程类型" prop="videoList" required>
            <el-button type="primary" size="small" @click="handleUploadVideo">
              <el-icon class="mr-1"><i-ep-plus /></el-icon>
              上传视频
            </el-button>
            <div class="upload-hint text-gray-400 text-xs mt-1 mb-2">
              支持mp4、avi、wmv、mov、flv、rmvb、3gp、m4v、mkv格式；单个文件最大不超过10G
            </div>
            <el-table :data="form.videoList" size="small" class="video-table mt-2 border">
              <el-table-column label="视频信息" prop="name" min-width="150">
                <template #default="scope">
                  <div class="flex items-center">
                    <el-icon class="mr-2 text-blue-500"><i-ep-video-play /></el-icon>
                    <span class="text-blue-500 underline cursor-pointer">{{ scope.row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="视频大小" prop="size" width="100" />
              <el-table-column label="视频类型" prop="type" width="80" />
              <el-table-column label="视频时长" prop="duration" width="100" />
              <el-table-column label="操作" width="80" align="center">
                <template #default="scope">
                  <el-link type="primary" :underline="false" @click="removeVideo(scope.$index)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>

        <template v-else-if="type === 'offline'">
          <el-form-item label="培训描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="从零开始学西班牙语，直达欧标B2水平！"
              style="width: 500px"
            />
          </el-form-item>
        </template>

        <div class="flex flex-wrap items-center">
          <el-form-item label="岗位级别" prop="jobLevel" required>
            <el-select v-model="form.jobLevel" multiple collapse-tags placeholder="请选择" style="width: 180px">
              <el-option label="A1" value="A1" />
              <el-option label="A2" value="A2" />
              <el-option label="B1" value="B1" />
              <el-option label="B2" value="B2" />
            </el-select>
          </el-form-item>
          <el-form-item label="岗位" prop="job" required class="ml-4">
            <el-select v-model="form.job" placeholder="审计" style="width: 180px">
              <el-option label="审计" value="审计" />
              <el-option label="会计" value="会计" />
            </el-select>
          </el-form-item>
        </div>

        <el-form-item label="岗位类型" prop="jobType" required>
          <el-select v-model="form.jobType" placeholder="全职" style="width: 180px">
            <el-option label="全职" value="全职" />
            <el-option label="兼职" value="兼职" />
            <el-option label="实习" value="实习" />
          </el-select>
        </el-form-item>

        <template v-if="type === 'video'">
          <el-form-item label="排序号" prop="sortOrder">
            <el-input v-model="form.sortOrder" placeholder="请输入" style="width: 320px" />
          </el-form-item>
        </template>

        <template v-if="type === 'offline'">
          <el-form-item label="培训地址" prop="address" required>
            <div class="flex gap-2 mb-2">
              <el-select v-model="form.city" placeholder="上海市" style="width: 120px">
                <el-option label="上海市" value="shanghai" />
              </el-select>
              <el-select v-model="form.area" placeholder="黄浦区" style="width: 120px">
                <el-option label="黄浦区" value="huangpu" />
              </el-select>
            </div>
            <el-input v-model="form.addressDetail" placeholder="请输入具体地址" style="width: 400px" />
          </el-form-item>

          <el-form-item label="培训时间" prop="timeRange" required>
            <el-date-picker
              v-model="form.timeRange"
              type="datetimerange"
              range-separator="-"
              start-placeholder="YYYY-MM-DD HH:mm:ss"
              end-placeholder="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 400px"
            />
          </el-form-item>

          <el-form-item label="报名时间" prop="applyRange" required>
            <el-date-picker
              v-model="form.applyRange"
              type="datetimerange"
              range-separator="-"
              start-placeholder="YYYY-MM-DD HH:mm:ss"
              end-placeholder="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 400px"
            />
          </el-form-item>

          <el-form-item label="主办单位" prop="organizer">
            <el-input v-model="form.organizer" placeholder="主办单位AAAAA" style="width: 320px" />
          </el-form-item>

          <el-form-item label="标签" prop="tags">
            <div class="flex items-center gap-2">
              <el-tag
                v-for="tag in form.tags"
                :key="tag"
                closable
                @close="handleCloseTag(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputTagVisible"
                ref="inputTagRef"
                v-model="inputTagValue"
                size="small"
                style="width: 80px"
                @keyup.enter="handleInputTagConfirm"
                @blur="handleInputTagConfirm"
              />
              <el-button v-else size="small" @click="showInputTag">
                <el-icon><i-ep-plus /></el-icon>
                标签
              </el-button>
            </div>
          </el-form-item>
        </template>

        <div class="flex gap-6 mt-12">
          <el-button type="primary" class="submit-btn" @click="handleSubmit">提交</el-button>
          <el-button class="back-btn" @click="$emit('cancel')">返回</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';

const props = defineProps<{
  initialData?: any;
  type: string;
}>();

const emit = defineEmits(['cancel', 'submit']);

const formRef = ref<FormInstance>();
const form = reactive({
  id: '',
  name: '',
  thumbnail: '',
  description: '',
  videoList: [] as any[],
  jobLevel: [] as string[],
  job: '',
  jobType: '',
  sortOrder: '',
  city: 'shanghai',
  area: 'huangpu',
  addressDetail: '',
  timeRange: [],
  applyRange: [],
  organizer: '',
  tags: [] as string[],
  status: true
});

const regionOptions = [
  {
    value: 'shanghai',
    label: '上海市',
    children: [
      { value: 'huangpu', label: '黄浦区' },
      { value: 'xuhui', label: '徐汇区' }
    ]
  }
];

const inputTagVisible = ref(false);
const inputTagValue = ref('');
const inputTagRef = ref();

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入培训名称', trigger: 'blur' }],
  thumbnail: [{ required: true, message: '请上传培训封面', trigger: 'change' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  videoList: [{ required: true, type: 'array', min: 1, message: '请上传视频', trigger: 'change' }],
  jobLevel: [{ required: true, type: 'array', min: 1, message: '请选择岗位级别', trigger: 'change' }],
  job: [{ required: true, message: '请选择岗位', trigger: 'change' }],
  jobType: [{ required: true, message: '请选择岗位类型', trigger: 'change' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  timeRange: [{ required: true, type: 'array', min: 2, message: '请选择培训时间', trigger: 'change' }],
  applyRange: [{ required: true, type: 'array', min: 2, message: '请选择报名时间', trigger: 'change' }]
});

onMounted(() => {
  if (props.initialData) {
    Object.assign(form, props.initialData);
    if (props.type === 'video' && !props.initialData.videoList) {
      form.videoList = [{ name: '西班牙系列课程1', size: '100.0MB', type: 'MP4', duration: '00:09:00' }];
    }
  } else {
    // Default values for new form
    if (props.type === 'video') {
      form.name = '西班牙语0-B2高级直达';
      form.thumbnail = 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=320&h=160&fit=crop';
    }
  }
});

const handleUploadVideo = () => {
  form.videoList.push({ name: '新增视频' + (form.videoList.length + 1), size: '50.0MB', type: 'MP4', duration: '00:05:00' });
};

const removeVideo = (index: number) => {
  form.videoList.splice(index, 1);
};

const handleCloseTag = (tag: string) => {
  form.tags = form.tags.filter(t => t !== tag);
};

const showInputTag = () => {
  inputTagVisible.value = true;
  nextTick(() => {
    inputTagRef.value?.focus();
  });
};

const handleInputTagConfirm = () => {
  if (inputTagValue.value) {
    form.tags.push(inputTagValue.value);
  }
  inputTagVisible.value = false;
  inputTagValue.value = '';
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid) => {
    if (valid) {
      emit('submit', { ...form });
    }
  });
};
</script>

<style scoped lang="scss">
.train-form {
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
  padding: 40px;

  .form-breadcrumb {
    margin-bottom: 20px;
  }

  .form-header {
    margin-bottom: 30px;
  }

  .form-wrapper {
    max-width: 1000px;
    margin: 0 auto;
    background-color: #fff;
    padding: 60px;
    border: 2px solid #409eff;
    border-radius: 4px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }

  .submit-btn {
    padding: 0 30px;
    height: 36px;
    background-color: #409eff;
    border-color: #409eff;
  }

  .back-btn {
    padding: 0 30px;
    height: 36px;
    color: #606266;
  }

  .thumbnail-uploader {
    .avatar-uploader {
      width: 160px;
      height: 80px;
      border: 1px dashed #d9d9d9;
      border-radius: 4px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #409eff;
      }
    }

    .avatar-preview {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .avatar-uploader-icon {
      font-size: 20px;
      color: #8c939d;
    }
  }

  .video-table {
    :deep(.el-table__header) {
      background-color: #f7f8fa;
    }
  }

  :deep(.el-form-item__label) {
    color: #4e5969;
    font-weight: 500;
  }
}
</style>

