<template>
  <el-dialog
    title="新增排班"
    v-model="visible"
    :width="500"
    :close-on-click-modal="false"
    draggable>
    <el-form
      ref="dataFormRef"
      :model="form"
      :rules="dataRules"
      label-width="100px"
      v-loading="loading">
      <el-form-item label="值班日期" prop="date">
        <el-date-picker
          v-model="form.date"
          type="date"
          placeholder="选择值班日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="预约师" prop="teacherUserName">
        <el-select
          v-model="form.teacherUserName"
          placeholder="请选择预约师"
          filterable
          clearable
          style="width: 100%">
          <el-option
            v-for="item in teacherList"
            :key="item.userName"
            :label="(item.realName || '') + (item.userName ? ` (${item.userName})` : '')"
            :value="item.userName" />
        </el-select>
      </el-form-item>
      <el-form-item label="周类型" prop="weekType">
        <el-select
          v-model="form.weekType"
          placeholder="请选择"
          clearable
          style="width: 100%">
          <el-option label="单周" value="single" />
          <el-option label="双周" value="double" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="PsychologicalCounselingDutyFormDialog">
import { ref, reactive, nextTick, watch } from 'vue'
import { useMessage } from '/@/hooks/message'
import { saveDuty } from '/@/api/stuwork/psychologicalcounselingduty'
import { getList } from '/@/api/stuwork/psychologicalcounselingteacher'

const props = defineProps<{
  year?: number
  month?: number
}>()

const emit = defineEmits(['refresh'])

const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const teacherList = ref<any[]>([])

const form = reactive({
  date: '',
  teacherUserName: '',
  weekType: 'single'
})

const dataRules = {
  date: [{ required: true, message: '请选择值班日期', trigger: 'change' }],
  teacherUserName: [{ required: true, message: '请选择预约师', trigger: 'change' }]
}

// 限制只能选当前年月的日期
const disabledDate = (time: Date) => {
  if (!props.year || !props.month) return false
  const y = time.getFullYear()
  const m = time.getMonth() + 1
  if (y !== props.year) return true
  if (m !== props.month) return true
  return false
}

const loadTeacherList = async () => {
  try {
    const res = await getList()
    if (res.data && Array.isArray(res.data)) {
      teacherList.value = res.data
    } else {
      teacherList.value = []
    }
  } catch (err) {
    teacherList.value = []
  }
}

const openDialog = () => {
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.date = ''
    form.teacherUserName = ''
    form.weekType = 'single'
  })
}

const onSubmit = async () => {
  if (!dataFormRef.value) return
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      await saveDuty([
        {
          date: form.date,
          teacherUserName: form.teacherUserName,
          weekType: form.weekType || 'single'
        }
      ])
      useMessage().success('排班成功')
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || '排班失败')
    } finally {
      loading.value = false
    }
  })
}

watch(visible, (v) => {
  if (v) loadTeacherList()
})

defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
</style>
