<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useProjectList } from '@/composables/useGetProjectList'
import { useMapStore } from '@/stores/map'
import { useUserStore } from '@/stores/user'
import { addStudent, updateStudent, getStuDetail, getClassList, getProList } from '../api'

const store = useMapStore()
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>()
const emit = defineEmits<Emits>()
const departmentList: any = useProjectList('', '79806610719731712').departmentList
const sexList = store.mapList.filter((item: any) => item.key === 'system_gender')[0].values
const idTypeList = store.mapList.filter((item: any) => item.key === 'system_id_type')[0].values
const statusList = store.getMapValuesByKey('system_status')
const loading = ref(false)
const classList: any = ref([])
const allLecturers: any = ref([])
const form: any = reactive({
  sno_number: '',
  name: '',
  gender: '1',
  mobile: '',
  id_type: '1',
  id_number: '',
  organ_id: '',
  specialty_id: '',
  class_id: '',
  status: '1'
})
const rules = reactive<FormRules>({
  sno_number: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  id_type: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
  id_number: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
  organ_id: [{ required: true, message: '请选择部门/学校', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})
const props = defineProps({
  isShowAddDialog: {
    type: Boolean
  },
  title: {
    type: String
  },
  id: {
    type: String
  },
  isEdit: {
    type: String
  }
})
interface Emits {
  (e: 'update:isShowAddDialog', isShowAddDialog: boolean): void
  (e: 'create'): void
}

// 取消
const handleCancel = () => {
  emit('update:isShowAddDialog', false)
}
const proList: any = ref([])
const allPro: any = ref([])
watch(
  () => form.organ_id,
  () => {
    if (form.organ_id !== '' || form.organ_id_name !== '') {
      handleGetProList()
    }
  }
)

watch(
  () => form.specialty_id,
  () => {
    if (form.specialty_id !== '') {
      handleClassList()
    }
  }
)
// 修改部门/学校为空的时候班级专业要清除数据

const handleChangeOrgan = () => {
  form.specialty_id = ''
  proList.value = []
  form.class_id = ''
  classList.value = []
}
// 修改专业为空的时候班级要清除数据
const handleChangeSpe = () => {
  form.class_id = ''
  classList.value = []
}
// 获取专业列表
const handleGetProList = () => {
  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)
      }
    })
  })
}
if (userStore.roles[0].name !== '超级管理员') {
  form.organ_id = userStore.organization?.id
  handleGetProList()
}
// 获取班级列表
const handleClassList = () => {
  getClassList({
    specialty_id: form.specialty_id,
    organ_id: form.organ_id || userStore.organization?.id,
    'per-page': '100'
  }).then((res: any) => {
    loading.value = false
    classList.value = res.data.list.filter((item: any) => item.status === '1')
    classList.value.forEach((item: any) => {
      const findItem = allLecturers.value.find((cItem: any) => cItem.id === item.id)
      if (!findItem) {
        allLecturers.value.push(item)
      }
    })
  })
}
// 确认
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)
        addStudent(params).then(() => {
          ElMessage.success('新增学生成功')
          emit('update:isShowAddDialog', 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)

        updateStudent(params).then(() => {
          ElMessage.success('更新学生成功')
          emit('update:isShowAddDialog', false)
          emit('create')
        })
      } else {
        emit('update:isShowAddDialog', false)
        emit('create')
      }
    }
  })
}
// 获取详情
if (props.isEdit === '2' || props.isEdit === '1') {
  const params: any = { id: props.id }
  getStuDetail(params).then((res: any) => {
    Object.keys(form).forEach(key => {
      form[key] = res.data[key]
    })
    if (res.data.specialty_id === '0') {
      form.specialty_id = ''
    }
  })
}
</script>
<template>
  <el-dialog :model-value="isShowAddDialog" draggable :before-close="handleCancel" :title="props.title" width="35%">
    <el-form :model="form" label-width="130px" :rules="rules" ref="ruleFormRef" label-suffix="：">
      <el-form-item label="学号" prop="sno_number">
        <el-input v-model="form.sno_number" :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="gender">
        <el-radio-group v-model="form.gender" :disabled="props.isEdit === '2'">
          <el-radio v-for="(item, index) in sexList" :key="index" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="联系电话" prop="mobile">
        <el-input v-model="form.mobile" :disabled="props.isEdit === '2'"></el-input>
      </el-form-item>
      <el-form-item label="证件类型" prop="card_type">
        <el-radio-group v-model="form.id_type" :disabled="props.isEdit === '2'">
          <el-radio v-for="(item, index) in idTypeList" :key="index" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="证件号码" prop="id_number">
        <el-input v-model="form.id_number" :disabled="props.isEdit === '2'" />
      </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 === '超级管理员'"
          @change="handleChangeOrgan"
        >
          <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="specialty_id">
        <el-select
          v-model="form.specialty_id"
          clearable
          placeholder="请选择专业"
          style="width: 100%"
          @change="handleChangeSpe"
          :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="class_id">
        <el-select
          v-model="form.class_id"
          clearable
          placeholder="请选择班级"
          style="width: 100%"
          :disabled="props.isEdit === '2'"
        >
          <el-option v-for="item in classList" :key="item.id" :label="item.name" :value="item.id" />
        </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, id) in statusList" :key="id" :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>
