<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useMapStore } from '@/stores/map'
import { useProjectList } from '@/composables/useGetProjectList'
import { addClass, updateClass, getClassDetail, searchTeacher, getProList } from '../api'
const ruleFormRef = ref<FormInstance>()
const userStore = useUserStore()
const store = useMapStore()
const emit = defineEmits<Emits>()
const departmentList: any = useProjectList('', '79806610719731712').departmentList

const startYearList = store.getMapValuesByKey('class_start_year')
const statusList = store.getMapValuesByKey('system_status')
const teacherList: any = ref([])
const allLecturers: any = ref([])
const form: any = reactive({
  code: '',
  name: '',
  organ_id: '',
  teacher_id: '',
  specialty_id: '',
  start_year: '',
  status: '1'
})
const rules = reactive<FormRules>({
  code: [{ required: true, message: '请输入班级代码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  organ_id: [{ required: true, message: '请选择所属部门/学校', trigger: 'change' }],
  teacher_id: [{ required: true, message: '请选择班主任', trigger: 'change' }],
  specialty_id: [{ required: true, message: '请选择所属专业', trigger: 'change' }],
  start_year: [{ required: true, message: '请选择入学年份', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})
const props = defineProps({
  isShowClassDialog: {
    type: Boolean
  },
  title: {
    type: String
  },
  id: {
    type: String
  },
  isEdit: {
    type: String
  }
})
interface Emits {
  (e: 'update:isShowClassDialog', isShowClassDialog: boolean): void
  (e: 'create'): void
}
// 取消
const handleCancel = () => {
  emit('update:isShowClassDialog', false)
}

watch(
  () => form.organ_id,
  value => {
    if (value !== '' || form.organ_id_name !== undefined) {
      handleGetTeacherList()
    }
  }
)
const handleGetTeacherList = () => {
  searchTeacher({ organ_id: form.organ_id, 'per-page': '100' }).then((res: any) => {
    teacherList.value = res.data.list.filter((item: any) => item.status === '1')
    teacherList.value.forEach((item: any) => {
      const findItem = allLecturers.value.find((cItem: any) => cItem.id === item.id)
      if (!findItem) {
        allLecturers.value.push(item)
      }
    })
  })
}
if (userStore.roles[0].name !== '超级管理员') {
  form.organ_id = userStore.organization?.id
  handleGetTeacherList()
}
// 确认
const handleConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      if (props.isEdit === '0') {
        form.organ_id = form.organ_id || userStore.organization?.id
        const params: any = Object.assign({}, form)
        addClass(params).then(() => {
          ElMessage.success('新增班级成功')
          emit('update:isShowClassDialog', false)
          emit('create')
        })
      } else if (props.isEdit === '1') {
        form.organ_id = form.organ_id || userStore.organization?.id

        const params: any = Object.assign({ id: props.id }, form)
        updateClass(params).then(() => {
          ElMessage.success('更新班级成功')
          emit('update:isShowClassDialog', false)
          emit('create')
        })
      } else {
        emit('update:isShowClassDialog', false)
        emit('create')
      }
    }
  })
}
// 获取详情
if (props.isEdit === '2' || props.isEdit === '1') {
  const params: any = { id: props.id }
  getClassDetail(params).then((res: any) => {
    Object.keys(form).forEach(key => {
      form[key] = res.data[key]
    })
  })
}

const proList: any = ref([])
const allPro: any = ref([])

getProList({ name: '', 'per-page': '100' }).then((res: any) => {
  proList.value = res.data.list.filter((item: any) => item.status === '1')
  proList.value.forEach((item: any) => {
    const findItem = allPro.value.find((cItem: any) => cItem.id === item.id)
    if (!findItem) {
      allPro.value.push(item)
    }
  })
})
</script>
<template>
  <el-dialog :model-value="isShowClassDialog" draggable :before-close="handleCancel" :title="props.title" width="30%">
    <el-form :model="form" label-position="right" label-width="auto" :rules="rules" ref="ruleFormRef" label-suffix="：">
      <el-form-item label="班级代码" prop="code">
        <el-input v-model="form.code" :disabled="props.isEdit === '2' || props.isEdit === '1'"></el-input>
      </el-form-item>
      <el-form-item label="班级名称" prop="name">
        <el-input v-model="form.name" :disabled="props.isEdit === '2' || props.isEdit === '1'"></el-input>
      </el-form-item>
      <el-form-item label="所属部门/学校" prop="organ_id">
        <el-select
          clearable
          v-model="form.organ_id"
          :disabled="props.isEdit === '2'"
          style="width: 100%"
          placeholder="请选择所属部门/学校"
          v-if="userStore.roles[0].name === '超级管理员'"
        >
          <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-input :placeholder="userStore.organization?.name" v-model="form.organ_id_name" v-else disabled> </el-input>
      </el-form-item>
      <el-form-item label="班主任" prop="teacher_id">
        <!-- {{ teacherList }} -->
        <el-select
          v-model="form.teacher_id"
          filterable
          clearable
          placeholder="请输入班主任"
          style="width: 230px"
          :disabled="props.isEdit === '2'"
        >
          <el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属专业" prop="specialty_id">
        <el-select
          v-model="form.specialty_id"
          filterable
          clearable
          placeholder="请输入所属专业"
          style="width: 230px"
          :disabled="props.isEdit === '2'"
        >
          <el-option v-for="item in proList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="入学年份:" prop="start_year">
        <el-select v-model="form.start_year" placeholder="请选择入学年份" :disabled="props.isEdit === '2'">
          <el-option
            v-for="(item, index) in startYearList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生效状态" prop="status">
        <el-radio-group v-model="form.status" :disabled="props.isEdit === '2'">
          <el-radio v-for="(item, index) in statusList" :key="index" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer v-if="props.isEdit !== '2'">
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm(ruleFormRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
