<template>
  <div class="container-wrapper">
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="auto"
      style="margin-top: 0.5rem;"
    >
      <ColumnItem title="文章编辑">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="formData.categoryId" placeholder="请选择文章分类" clearable style="width: 100%">
                <el-option
                  v-for="item in articleCategoryList"
                  :key="item.ID"
                  :label="item.name"
                  :value="item.ID"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="讲师" prop="teacherId">
              <el-input v-model="formData.teacherName" readonly placeholder="点击选择讲师" @click="() => userDialogRef.open()" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否免费" prop="isFree">
              <el-radio-group v-model="formData.isFree">
                <el-radio :label="1">免费</el-radio>
                <el-radio :label="0">付费</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="formData.isFree === 0">
          <el-col :span="12">
            <el-form-item label="价格(元)" prop="price">
              <el-input v-model="formData.price" type="number" placeholder="请输入价格，单位：元" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="封面图片" prop="coverImg">
              <SelectImage v-model="formData.coverImg" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 文章介绍（放在文章详情上方，使用富文本） -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="文章介绍" prop="desc">
              <RichEdit style="width: 100%" v-model="formData.desc"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="文章详情" prop="content">
              <RichEdit style="width: 100%" v-model="formData.content"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 定时发布选项 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="定时发布">
              <el-switch
                v-model="formData.isScheduled"
                active-text="启用"
                inactive-text="禁用"
                @change="handleScheduledChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.isScheduled">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="formData.publishTime"
                type="datetime"
                placeholder="选择发布时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </ColumnItem>
    </el-form>
    <div class="gva-table-box footer-box">
      <el-button @click="$router.back()">返回</el-button>
      <el-button type="primary" @click="submit(ruleFormRef)">提交</el-button>
    </div>
  </div>
  <!--    选择人员弹窗-->
  <userChoose
    ref="userDialogRef"
    @getRecipientInfo="getStaffInfo"
    title="讲师人员"
  />
</template>
<script setup>
  import SelectImage from '@/components/selectImage/selectImage.vue'
  import {onMounted, ref, computed } from 'vue'
  import userChoose from '@/components/userChoose/index.vue'
  import { useRouter, useRoute} from 'vue-router'
  import { add, detail, edit } from '@/api/goods/index.js'
  import { getCategoryList } from '@/api/category/category.js'
  import ColumnItem from '@/components/columnItem/ColumnItem.vue'
  import { ElMessage } from 'element-plus'
  import RichEdit from '@/components/richtext/rich-edit.vue'

  const router = useRouter()
  const route = useRoute()
  const userDialogRef = ref()
  const isEdit = ref(false)
  const categoryList = ref([])

  const ruleFormRef = ref(null), formData = ref({
    isFree: 0, // 默认付费
    price: 0,
    isScheduled: false, // 定时发布开关
    publishTime: '' // 发布时间
  }), rules = ref({
    title: [
      { required: true, message: '请输入文章标题', trigger: 'blur' }
    ],
    categoryId: [
      { required: true, message: '请选择文章分类', trigger: 'change' }
    ],
    teacherId: [
      { required: true, message: '请选择讲师', trigger: 'blur' }
    ],
    isFree: [
      { required: true, message: '请选择是否免费', trigger: 'change' }
    ],
    price: [
      {
        required: true,
        message: '请输入价格',
        trigger: 'blur',
        validator: (rule, value, callback) => {
          if (formData.value.isFree === 0 && (!value || value <= 0)) {
            callback(new Error('付费文章请输入大于0的价格'))
          } else {
            callback()
          }
        }
      }
    ],
    coverImg: [
      { required: true, message: '请上传封面', trigger: 'blur' }
    ],
    // 文章介绍改为富文本，也做必填校验
    desc: [
      { required: true, message: '请输入文章介绍', trigger: 'blur' }
    ],
    content: [
      { required: true, message: '请输入文章内容', trigger: 'blur' }
    ],
    publishTime: [
      {
        required: true,
        message: '请选择发布时间',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (formData.value.isScheduled && (!value || value === '')) {
            callback(new Error('启用定时发布时，请选择发布时间'))
          } else {
            callback()
          }
        }
      }
    ]
  })

  // 计算属性：筛选出文章分类（url字段为空的分类）
  const articleCategoryList = computed(() => {
    return categoryList.value.filter(item => !item.url || item.url === '')
  })

  onMounted(() => {
    console.log(route.query.id)
    getCategoryData()
    if(route.query.id) {
      isEdit.value = true
      getDetail()
    }
  })

  // 获取分类数据
  async function getCategoryData() {
    try {
      const res = await getCategoryList()
      if (res.code === 0) {
        categoryList.value = res.data.list || []
      }
    } catch (error) {
      console.error('获取分类数据失败:', error)
    }
  }

  async function getDetail() {
    const res = await detail(route.query.id)
    if(res.code === 0) {
      formData.value = res.data
      // 如果数据库存储的是分，转换为元显示
      if (formData.value.price) {
        formData.value.price = (formData.value.price / 100).toFixed(2)
      }
      // 确保isFree字段有值
      if (formData.value.isFree === undefined || formData.value.isFree === null) {
        formData.value.isFree = 0
      }
      // 处理定时发布字段
      if (formData.value.publishTime) {
        formData.value.isScheduled = true
      } else {
        formData.value.isScheduled = false
        formData.value.publishTime = ''
      }
    }
  }

  function getStaffInfo(data) {
    console.log(formData)
    formData.value.teacherId = data.id
    formData.value.teacherName = data.nick_name
  }

  // 处理定时发布开关变化
  function handleScheduledChange(value) {
    if (!value) {
      // 关闭定时发布时，清空发布时间
      formData.value.publishTime = ''
    } else {
      // 开启定时发布时，设置默认发布时间为当前时间
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      formData.value.publishTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }

  // 禁用过去的日期
  function disabledDate(time) {
    return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
  }

  function submit(formRef) {
    if(!formRef) return
    // 校验
    formRef.validate(async (valid) => {
      if(!valid) return
      let fn = isEdit.value ? edit : add

      // 处理价格字段
      if (formData.value.isFree === 1) {
        // 免费文章，价格设为0
        formData.value.price = 0
      } else {
        // 付费文章，价格转为分（数据库存储单位）
        if (formData.value.price) {
          formData.value.price = Math.round(Number(formData.value.price) * 100)
        }
      }

      // 处理定时发布参数
      const submitData = { ...formData.value }
      if (!submitData.isScheduled) {
        // 如果未启用定时发布，则不传递publishTime参数
        delete submitData.publishTime
      }
      delete submitData.isScheduled // 移除前端使用的开关字段

      const res = await fn(submitData)
      console.log(res)
      if(res.code === 0) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        router.back()
      } else {
        ElMessage({
          type: 'error',
          message: res.msg
        })
      }
    })
  }
</script>
<style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color) !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  :deep{
    .el-row {
      margin-bottom: 20px;
    }
    .el-form{
      flex: 1;
      background: white;
      overflow: hidden;
    }
    .el-form-item {
      margin-bottom: 18px;
    }
    .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }
  }
</style>
