<template>
  <el-dialog
    v-model="visible"
    title="批量新增用户"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10vh"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="考试名称">
        <el-input :value="curExamName" disabled />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="formModel.role" placeholder="请选择角色">
          <el-option
            v-for="(val, key) in BATCH_ADD_ROLE"
            :key="key"
            :label="val"
            :value="key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="命名规则" prop="prefix">
        <el-input v-model="formModel.prefix" placeholder="自定义前缀">
          <template #append>+科目代码+流水号</template>
        </el-input>
      </el-form-item>
      <el-form-item label="每分组账号数" prop="number">
        <el-input-number
          v-model="formModel.number"
          :min="1"
          :max="20"
          :step="1"
          :precision="0"
          :controls="false"
          step-strictly
        />
      </el-form-item>
      <el-form-item label="是否随机密码" prop="random">
        <el-switch v-model="formModel.random" @change="randomPasswordChange" />
      </el-form-item>
      <el-form-item v-if="!formModel.random" label="密码" prop="password">
        <el-input
          v-model="formModel.password"
          type="password"
          placeholder="请输入密码"
          :disabled="formModel.random"
          show-password
        />
      </el-form-item>
      <el-form-item label="选择科目" prop="subjectCodeString">
        <el-button type="primary" @click="openSelectSubjectDialog"
          >设置</el-button
        >
        <div v-if="selectedSubjects.length > 0" style="margin-left: 10px">
          已选择 {{ selectedSubjects.length }} 个科目
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSave"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>

  <SelectSubjectDialog
    ref="selectSubjectDialogRef"
    :select-ids="formModel.subjectIds"
    @selected="handleSubjectsSelected"
  />
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue';
  import type { FormInstance } from 'element-plus';
  import { FormRules } from '@/types/global';
  import { ElMessage } from 'element-plus';
  import { useAppStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import useModal from '@/hooks/modal';
  import { BATCH_ADD_ROLE } from '@/constants/enumerate';

  import type { SubjectItem } from '@/api/types/base';
  import type { BatchCreateUserParam } from '@/api/types/user';
  import { batchAddUser } from '@/api/user';

  import SelectSubjectDialog from './SelectSubjectDialog.vue';

  defineOptions({
    name: 'BatchCreateUserDialog',
  });

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  const emit = defineEmits(['modified']);

  const appStore = useAppStore();
  const curExamName = computed(() => appStore.curExam?.name || '');

  const formRef = ref<FormInstance>();

  const rules: FormRules<keyof BatchCreateUserParam> = {
    role: [{ required: true, message: '请选择角色', trigger: 'change' }],
    prefix: [{ required: true, message: '请输入命名规则', trigger: 'change' }],
    number: [
      { required: true, message: '请输入每分组账号数', trigger: 'change' },
    ],
    password: [
      {
        required: true,
        message: '请输入密码或选择随机密码',
        trigger: 'change',
      },
    ],
    subjectCodeString: [
      {
        required: true,
        validator: (rule: any, value: string, callback: any) => {
          if (!value) {
            callback(new Error('请选择科目'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
  };

  function getInitialFormModel(): BatchCreateUserParam {
    return {
      role: 'MARKER',
      prefix: '',
      number: undefined,
      random: false,
      password: '',
      subjectCodeString: '',
    };
  }

  const formModel = reactive<BatchCreateUserParam>(getInitialFormModel());
  const selectedSubjects = ref<SubjectItem[]>([]);
  const selectSubjectDialogRef = ref<InstanceType<
    typeof SelectSubjectDialog
  > | null>(null);

  function randomPasswordChange() {
    if (formModel.random) {
      formModel.password = '';
    }
  }

  const handleClose = () => {
    formRef.value?.resetFields();
  };

  const openSelectSubjectDialog = () => {
    selectSubjectDialogRef.value?.open(selectedSubjects.value.map((s) => s.id));
  };

  const handleSubjectsSelected = (subjects: SubjectItem[]) => {
    selectedSubjects.value = subjects;
    formModel.subjectCodeString = subjects.map((s) => s.code).join(',');
    ElMessage.success(`已选择 ${subjects.length} 个科目`);
    formRef.value?.validateField('subjectCodeString');
  };

  const { loading, setLoading } = useLoading();
  const handleSave = async () => {
    if (!formRef.value) return;

    const valid = await formRef.value.validate().catch(() => false);
    if (!valid) return;

    try {
      setLoading(true);
      let res = true;
      await batchAddUser({ ...formModel }).catch(() => {
        res = false;
      });
      setLoading(false);
      if (!res) return;
      ElMessage.success(`批量新增用户成功！`);
      emit('modified');
      close();
    } catch (error) {
      console.error('API request error:', error);
      ElMessage.error('操作失败，请重试');
    }
  };

  const modalBeforeOpen = () => {
    Object.assign(formModel, getInitialFormModel());
    selectedSubjects.value = [];
  };
</script>
