<script setup lang="ts">
import { createCourse, getCourseDetails, updateCourse, getMajorList, getBookDetail } from '../api'
// setStatus
import { useGetCategoryList } from '@/composables/useGetCategoryList'
import { useMapStore } from '@/stores/map'
import VEditor from '@/components/tinymce/Index.vue'
// 课程封面
import AddCourseCover from '../components/stepOneComponents/AddCourseCover.vue'
// 添加讲师
import AddLecturer from '../components/stepOneComponents/AddLecturer.vue'
// 添加助教
import AddAssistant from '../components/stepOneComponents/AddAssistant.vue'

// 添加试卷
import AddExam from '../components/stepOneComponents/AddExam.vue'
// 添加直播
import AddLive from '../components/stepOneComponents/AddLive.vue'
// 添加课程资料

import AddCourseData from '../components/stepOneComponents/AddCourseData.vue'

// 添加数字教材
import AddTextbook from '../components/stepOneComponents/AddTextbook.vue'

import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
const store = useMapStore()
const route = useRoute()
const router = useRouter()

const id: any = route.query.id as string
const majorList: any = ref([])
const allMajorList: any = ref([])

// is 编辑 新建
const isUpdate = computed(() => {
  return !!route.query.id
})

interface ICourseList {
  label: string
  value: string
}

const ruleFormRef = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()

// 课程类型
const courseType = computed<ICourseList[]>(() => {
  return store.getMapValuesByKey('system_online_type')
})

// 课程类型
const electiveType = computed<ICourseList[]>(() => {
  return store.getMapValuesByKey('system_elective_type')
})

// 下拉选择tree 视频分类
let { list: selectTree }: any = useGetCategoryList()
const defaultProps = { children: 'children', label: 'category_name', value: 'id' }

// form
const form = reactive<Record<string, any>>({
  name: '',
  online_type: '',
  elective_type: '',
  classification: '',
  credit: '',
  source: '2',
  cover: '/center_resource/course-cover.png',
  lecturer_id: '',
  teacher_id: '',
  represent: '',
  essay: '',
  previous_preparation: '',
  target: '',
  exam_id: '',
  live_id: '',
  specialty_id: [],
  information_id: '',
  book_id: ''
})

// 表单验证
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入标题' }],
  online_type: [{ required: true, message: '请选择课程类型' }],
  elective_type: [{ required: true, message: '请选择选课类型' }],
  classification: [{ required: true, message: '请选择课程分类' }],
  credit: [
    { required: true, message: '请输入学分' },
    { pattern: /\d/, message: '请输入数字' }
  ],
  lecturer_id: [{ required: true, message: '请添加课程讲师' }],
  specialty_id: [{ required: true, message: '请选择适用专业' }]
})

// 课程封面dialog
const dialogVisible = ref(false)
// 选择封面
const coverChange = (url: string) => {
  form.cover = url
}

// 选择考试
const changeExam = (data: any) => {
  form.exam_id = JSON.parse(JSON.stringify(data))
    .map((item: any) => {
      return item.id
    })
    .toString()
}
// 选择资料

// 考试数据回显
const examList: any = ref([])
const information: any = ref([])
const textbookInfo: any = ref([])

// 获取详情
const loading = ref<boolean>(false)
function fetchDetail() {
  loading.value = true
  getCourseDetails({ id }).then((res: any) => {
    Object.assign(form, res.data)
    examList.value = res.data.examinations
    information.value = res.data.information
    form.exam_id = res.data.examinations.map((item: any) => item.id).toString()
    form.specialty_id = res.data.specialty.map((item: any) => item.id)
    form.teacher_id = res.data.teachers.map((item: any) => item.id)
    // textbookList.value = res.data.books?.book_id
    if (res.data.books.length) {
      getBookDetail({ id: res.data.books[0]?.book_id }).then(res => {
        if (res.data) {
          textbookInfo.value = [res.data]
        }
      })
      // res.data.books[0]?.book_id
    }
    loading.value = false
  })
}
onMounted(() => {
  if (isUpdate.value) {
    fetchDetail()
  }
})

watchEffect(() => {
  form.teacher_id = setDefaultData(form.teachers)
  form.lecturer_id = setDefaultData(form.lecturers)
  form.live_id = setDefaultData(form.meetings)
})

watch(
  () => form.lecturer_id,
  () => {
    ruleFormRef.value?.validateField('lecturer_id')
  }
)

function setDefaultData(data: any[] = []) {
  return data.map((item: any) => item.id).join()
}

// 提交
function handleSubmit() {
  Promise.all([ruleFormRef.value!.validate(), ruleFormRef2.value!.validate()])
    .then(() => {
      isUpdate.value ? handleUpdate() : handleCreate()
    })
    .catch(() => {
      ElMessage.error('请检查表单是否填写完整')
    })
}
// 创建课程
function handleCreate() {
  form.specialty_id = form.specialty_id.toString()
  createCourse(form).then((res: any) => {
    if (res.code === 0) {
      // 操作第二部
      router.push({
        path: '/course/update-course/stepTwo',
        query: { id: res.data.id, isEditCourse: '0', bid: form.book_id }
      })
    }
  })
}
// 修改课程
function handleUpdate() {
  form.specialty_id = form.specialty_id.toString()
  updateCourse(form).then((res: any) => {
    if (res.code === 0) {
      // 操作第二部
      router.push({
        path: '/course/update-course/stepTwo',
        query: { id: res.data.id, isEditCourse: '1', bid: form.book_id }
      })
    }
  })
}

getMajorList({ name: '', 'per-page': '100' }).then((res: any) => {
  majorList.value = res.data.list.filter((item: any) => item.status === '1')
  majorList.value.forEach((item: any) => {
    const findItem = allMajorList.value.find((cItem: any) => cItem.id === item.id)
    if (!findItem) {
      allMajorList.value.push(item)
    }
  })
})
const handleInformation = (val: any) => {
  form.information_id = val.map((item: any) => item.id).toString()
}

const handleTextbook = (val: any) => {
  form.book_id = val[0].id
}
</script>

<template>
  <AppCard :title="isUpdate ? '编辑课程' : '新建课程'" v-loading="loading">
    <!-- 基本信息 -->
    <div class="update-course-info">
      <div style="display: flex">
        <div class="cover" :style="`background-image: url(${form.cover})`">
          <div class="upload-btn" @click="dialogVisible = true">添加封面</div>
        </div>
        <el-form ref="ruleFormRef2" :model="form" :rules="rules" style="width: 50%" label-suffix="：">
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="form.name" maxlength="40" />
          </el-form-item>
          <el-form-item label="课程类型" prop="online_type">
            <el-radio-group v-model="form.online_type">
              <el-radio :key="item.value" :label="item.value" v-for="item in courseType">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选课类型" prop="elective_type">
            <el-radio-group v-model="form.elective_type">
              <el-radio :key="item.value" :label="item.value" v-for="item in electiveType">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="课程分类" prop="classification">
            <el-tree-select
              :render-after-expand="false"
              :props="defaultProps"
              style="width: 100%"
              v-model="form.classification"
              :data="selectTree"
              node-key="id"
              :default-expanded-keys="selectTree.length ? [selectTree[0]?.id] : []"
              placeholder="请选择课程分类"
            />
          </el-form-item>
          <el-form-item label="课程学分" prop="credit">
            <el-input v-model="form.credit" maxlength="3" />
          </el-form-item>
          <el-form-item label="适用专业" prop="specialty_id">
            <el-select
              v-model="form.specialty_id"
              placeholder="请选择适用专业"
              style="width: 100%"
              clearable
              multiple
              v-permission="'v1-course-search-specialty'"
            >
              <!-- :remote-method="handleMajorList" -->

              <el-option
                v-for="(item, index) in majorList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-form
        ref="ruleFormRef"
        label-position="top"
        :model="form"
        :rules="rules"
        label-suffix="："
        style="width: 100%; margin-top: 30px"
      >
        <el-form-item label="课程助教" prop="teacher_id">
          <!-- 添加助教 -->
          <AddAssistant v-model="form.teachers" style="width: 100%"></AddAssistant>
        </el-form-item>
        <el-form-item label="课程讲师" prop="lecturer_id">
          <!-- 添加讲师 -->
          <AddLecturer v-model="form.lecturers" style="width: 100%"></AddLecturer>
        </el-form-item>
        <el-form-item label="课程简介与描述">
          <v-editor v-model="form.represent" class="editor" :height="200"></v-editor>
        </el-form-item>
        <el-form-item label="课程小论文">
          <v-editor v-model="form.essay" class="editor" :height="200"></v-editor>
        </el-form-item>
        <el-form-item label="前期准备与预备知识">
          <v-editor v-model="form.previous_preparation" class="editor" :height="200"></v-editor>
        </el-form-item>
        <el-form-item label="授课目标">
          <v-editor v-model="form.target" class="editor" :height="200"></v-editor>
        </el-form-item>
        <el-form-item label="课程考试" prop="exam_id">
          <!-- 添加考试 -->
          <AddExam :data="examList" @change="changeExam" style="width: 100%"></AddExam>
        </el-form-item>
        <el-form-item label="周期性直播" prop="live_id">
          <!-- 添加直播 -->
          <AddLive v-model="form.meetings" style="width: 100%"></AddLive>
        </el-form-item>
        <el-form-item label="课程资料" prop="information_id">
          <!-- 添加课程资料 -->
          <AddCourseData
            v-model="form.information_id"
            :data="information"
            style="width: 100%"
            :id="id"
            @information="handleInformation"
          ></AddCourseData>
        </el-form-item>
        <!-- AddDigitalTextbook -->
        <el-form-item label="数字教材" prop="information_id">
          <!-- 添加数字教材 -->
          <AddTextbook
            v-model="form.book_id"
            :data="textbookInfo"
            style="width: 100%"
            :id="id"
            @information="handleTextbook"
          ></AddTextbook>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn-box" style="display: flex; justify-content: center">
      <el-button type="primary" @click="handleSubmit">下一步</el-button>
    </div>
    <!-- 添加封面 -->
    <AddCourseCover @change="coverChange" v-model:dialogVisible="dialogVisible"></AddCourseCover>
  </AppCard>
</template>
<style lang="scss">
.update-course-info {
  .cover {
    width: 430px;
    height: 270px;
    background-size: cover;
    background-image: url('https://iph.href.lu/430x270');
    margin-right: 20px;
    position: relative;
    .upload-btn {
      position: absolute;
      bottom: 10px;
      right: 10px;
      padding: 5px 10px;
      font-size: 14px;
      border-radius: 25px;
      text-align: center;
      background: rgba(0, 0, 0, 0.3);
      color: #fff;
      cursor: pointer;
    }
  }
  .tool-btn-box {
    padding-bottom: 20px;
    display: flex;
    justify-content: right;
    .btn-item {
      width: 127px;
      line-height: 36px;
      background: #aa1941;
      border-radius: 20px;
      margin-right: 10px;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      cursor: pointer;
    }
  }
}
</style>
