<script lang="ts" setup>
import AppUpload from '@/components/base/AppUpload.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useProjectList } from '@/composables/useGetProjectList'
import { createPosts, getConditionList } from '../api'
import { useMapStore } from '@/stores/map'
const store = useMapStore()
const typeList = store.getMapValuesByKey('learning_discussion_type')
const departmentList: any = useProjectList('', '79806610719731712').departmentList
const ruleFormRef = ref<FormInstance>()
const emit = defineEmits<Emits>()
const loading = ref(false)
defineProps({
  isShowAddDialog: {
    type: Boolean
  }
})
interface Emits {
  (e: 'update:isShowAddDialog', isShowAddDialog: boolean): void
  (e: 'create'): void
}
const form: any = reactive({
  organ_id: '',
  semester_id: '',
  class_id: '',
  course_id: '',
  chapter_id: '',
  type: '',
  title: '',
  content: '',
  files: []
})

const rules = reactive<FormRules>({
  organ_id: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
  semester_id: [{ required: true, message: '请选择所属学期', trigger: 'change' }],
  class_id: [{ required: true, message: '请选择所属班级', trigger: 'change' }],
  course_id: [{ required: true, message: '请选择所属课程', trigger: 'change' }],
  chapter_id: [{ required: true, message: '请选择所属章节', trigger: 'change' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  title: [{ required: true, message: '请填写标题', trigger: 'change' }],
  content: [{ required: true, message: '请填写正文内容', trigger: 'blur' }]
})
const semesterList: any = ref([])
const classList: any = ref([])
const courseList: any = ref([])
const chapterList: any = ref([])
watch(
  () => form.organ_id,
  value => {
    if (value !== '') {
      handleGetSemesterList()
    }
  }
)
watch(
  () => form.semester_id,
  value => {
    if (value !== '') {
      handleGetClassList()
    }
  }
)
watch(
  () => form.course_id,
  value => {
    if (value !== '') {
      handleGetChapterList()
    }
  }
)
watch(
  () => form.class_id,
  value => {
    if (value !== '') {
      handleGetCourseList()
    }
  }
)

// 获取学期列表
const handleGetSemesterList = () => {
  if (form.organ_id !== '') {
    const params: any = { type: 'semester', organ_id: form.organ_id }
    getConditionList(params).then((res: any) => {
      semesterList.value = res.data
    })
  }
}
// 获取班级列表
const handleGetClassList = () => {
  if (form.organ_id !== '' && form.semester_id !== '') {
    const params: any = { type: 'class', organ_id: form.organ_id, semester_id: form.semester_id }
    getConditionList(params).then((res: any) => {
      classList.value = res.data
    })
  }
}
// 获取课程列表
const handleGetCourseList = () => {
  if (form.organ_id !== '' && form.semester_id !== '' && form.class_id !== '') {
    const params: any = { type: 'course', organ_id: form.organ_id, semester_id: form.semester_id }
    getConditionList(params).then((res: any) => {
      courseList.value = res.data
    })
  }
}
// 获取课程章节列表
const handleGetChapterList = () => {
  if (form.organ_id !== '' && form.semester_id !== '' && form.class_id !== '' && form.course_id !== '') {
    const params: any = {
      type: 'chapter',
      organ_id: form.organ_id,
      semester_id: form.semester_id,
      course_id: form.course_id
    }
    getConditionList(params).then((res: any) => {
      chapterList.value = res.data
    })
  }
}

// 取消
const handleCancel = () => {
  emit('update:isShowAddDialog', false)
}
// 确认
const handleConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      loading.value = true
      form.files = JSON.stringify(form.files)
      const params: any = Object.assign({}, form)
      createPosts(params).then(() => {
        loading.value = false
        emit('update:isShowAddDialog', false)
        emit('create')
      })
    }
  })
}
const handleChangeOrgan = () => {
  form.semester_id = ''
  form.class_id = ''
  form.course_id = ''
  form.chapter_id = ''
  semesterList.value = []
  classList.value = []
  courseList.value = []
  chapterList.value = []
}
const handleChangeSemester = () => {
  form.class_id = ''
  form.course_id = ''
  form.chapter_id = ''
  classList.value = []
  courseList.value = []
  chapterList.value = []
}
const handleChangeClass = () => {
  form.course_id = ''
  form.chapter_id = ''
  courseList.value = []
  chapterList.value = []
}
const handleChangeCourse = () => {
  form.chapter_id = ''
  chapterList.value = []
}
const videoLimit = computed(() => {
  return form.files.filter((item: any) => item.url.includes('.mp4'))
})
const imgLimit = computed(() => {
  return form.files.filter(
    (item: any) => item.url.includes('.png') || item.url.includes('.jpg') || item.url.includes('.jpeg')
  )
})

const beforeUploadFiles = (file: any) => {
  if (file.type.includes('video/') && file.size > 104857600) {
    ElMessage.warning('视频大小不能超过100MB')
    return false
  }
  if (file.type.includes('image/') && file.size > 2097152) {
    ElMessage.warning('图片大小不能超过2MB')
    return false
  }
  if (imgLimit.value.length >= 10 && (file.url.includes('.png') || file.url.includes('.jpg') || file.url.includes('.jpeg'))) {
    ElMessage.warning('最多只能上传10张图片')
    return false
  }
  if (videoLimit.value.length >= 1 && file.url.includes('.mp4')) {
    ElMessage.warning('最多只能上传1个视频')
    return false
  }
}
</script>
<template>
  <el-dialog :model-value="isShowAddDialog" title="新建帖子" :before-close="handleCancel">
    <div style="max-height: 65vh; padding-right: 20px; overflow-y: auto">
      <el-form
        :model="form"
        label-position="right"
        label-width="auto"
        :rules="rules"
        ref="ruleFormRef"
        label-suffix="："
      >
        <el-row>
          <el-col :span="11">
            <el-form-item label="所属机构" prop="organ_id">
              <el-select
                clearable
                v-model="form.organ_id"
                placeholder="所属机构"
                @change="handleChangeOrgan"
                style="width: 100%"
              >
                <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"> </el-col>

          <el-col :span="11">
            <el-form-item label="所属学期" prop="semester_id">
              <el-select
                clearable
                v-model="form.semester_id"
                placeholder="所属学期"
                @change="handleChangeSemester"
                no-data-text="请先选择所属机构"
                style="width: 100%"
              >
                <el-option v-for="item in semesterList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="所属班级" prop="class_id">
              <el-select
                clearable
                v-model="form.class_id"
                placeholder="所属班级"
                @change="handleChangeClass"
                no-data-text="请先选择所属学期"
                style="width: 100%"
              >
                <el-option v-for="item in classList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"> </el-col>

          <el-col :span="11">
            <el-form-item label="所属课程" prop="course_id">
              <el-select
                clearable
                v-model="form.course_id"
                placeholder="所属课程"
                @change="handleChangeCourse"
                no-data-text="请先选择所属班级"
                style="width: 100%"
              >
                <el-option v-for="item in courseList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="所属章节" prop="chapter_id">
              <el-select
                clearable
                v-model="form.chapter_id"
                placeholder="所属章节"
                no-data-text="请先选择所属课程"
                style="width: 100%"
              >
                <el-option v-for="item in chapterList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"> </el-col>

          <el-col :span="11">
            <el-form-item label="类型" prop="type">
              <el-select clearable v-model="form.type" placeholder="类型" style="width: 100%">
                <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="标题" />
        </el-form-item>
        <el-form-item label="正文内容" prop="content">
          <el-input
            v-model="form.content"
            maxlength="500"
            placeholder="请输入正文内容"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item prop="files">
          <AppUpload v-model="form.files" accept="image/*,video/*" :beforeUploadFiles="beforeUploadFiles">
            <template #tip
              >支持最多上传10张图片，格式支持jpg，jpeg，png，2MB以内<br />视频最多上传1个，100Mb以内
            </template>
          </AppUpload>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm(ruleFormRef)" :loading="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.upload-video {
  display: flex;
  align-items: center;
  .upload-btn {
    position: absolute;
    top: 0;
    left: 0;
    width: 94px;
    line-height: 36px;
    background: rgba(250, 223, 230, 0.39);
    border: 1px solid #aa1941;
    border-radius: 20px;
    font-size: 14px;
    color: #aa1941;
    margin-right: 30px;
    text-align: center;
  }
}
.tips {
  font-size: 12px;
  color: #989898;
}
:deep(.el-upload-list__item) {
  margin-right: 20px;
  .el-upload-list__item-info {
    display: inline-flex;
    justify-content: center;
    flex-direction: column;
    width: calc(100% - 100px);
    margin-left: 4px;
  }
}
</style>
