<script lang="ts" setup>
import { ElMessage } from 'element-plus'

import { getRelationSemList, relationClassSem } from '../api'
const emit = defineEmits<Emits>()

const props = defineProps({
  isShowTermDialog: {
    type: Boolean
  },
  id: {
    type: String
  },
  title: {
    type: String
  }
})
interface Emits {
  (e: 'update:isShowTermDialog', isShowTermDialog: boolean): void
  (e: 'create'): void
}
const termList: any = ref([])
const formInfo = ref({})
const form = reactive({
  name: '',
  start_time: '',
  end_time: '',
  length: ''
})
const handleCancel = () => {
  emit('update:isShowTermDialog', false)
}
const handleConfirm = () => {
  const params: any = {
    class_id: props.id,
    semesters_id: termList.value.filter((item: any) => item.name === form.name)[0].id,
    type: 'add'
  }
  relationClassSem(params).then(() => {
    ElMessage.success('关联学期成功')
    emit('update:isShowTermDialog', false)
    emit('create')
  })
}

const params: any = { class_id: props.id, 'per-page': '1000' }
getRelationSemList(params).then(res => {
  termList.value = res.data.list
})
const handleChangeTerm = (val: any) => {
  if (val !== '') {
    formInfo.value = termList.value.filter((item: any) => item.id === val)[0]
    Object.keys(form).forEach(key => {
      form[key] = formInfo.value[key]
    })
  } else {
    form.start_time = ''
    form.end_time = ''
    form.length = ''
  }
}
</script>
<template>
  <el-dialog
    :model-value="isShowTermDialog"
    draggable
    :title="title"
    width="30%"
    :before-close="handleCancel"
    top="30vh"
  >
    <el-form :model="form" label-position="right" label-width="auto" label-suffix="：">
      <el-form-item label="学期名称" prop="name">
        <el-select
          clearable
          v-model="form.name"
          :disabled="props.title === '查看详情'"
          style="width: 100%"
          placeholder="请选择学期"
          @change="handleChangeTerm"
        >
          <el-option v-for="item in termList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="学期开始日期" prop="start_time">
        <el-input v-model="form.start_time" disabled></el-input>
      </el-form-item>
      <el-form-item label="学期结束日期" prop="end_time">
        <el-input v-model="form.end_time" disabled></el-input>
      </el-form-item>
      <el-form-item label="教学周" prop="length">
        <el-input v-model="form.length" disabled></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
