<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="考试名称">
        {{ curExamName }}
      </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-if="appStore.system.authType === 'offline'"
          v-model.trim="formModel.prefix"
          placeholder="自定义前缀"
          style="width: 120px; margin-right: 5px"
        >
        </el-input>
        <span> {{ prefixLabel }} </span>
      </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.trim="formModel.password"
          type="password"
          placeholder="请输入密码"
          :disabled="formModel.random"
          show-password
        />
      </el-form-item>
      <el-form-item label="选择科目" prop="subjectCodes">
        <el-button type="primary" link @click="openSelectSubjectDialog"
          >设置</el-button
        >
        <div v-if="formModel.subjectCodes.length > 0" style="margin-left: 10px">
          已选择 {{ formModel.subjectCodes.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-codes="formModel.subjectCodes"
    @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 { batchAddUser } from '@/api/user';
  import type { BatchCreateUserParam } from '@/api/types/user';
  import { modalConfirm } from '@/utils/ui';

  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.displayExamName);

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

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

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

  const prefixLabels = {
    online: {
      SUBJECT_HEADER: '机构ID+科目代码+流水号',
      INSPECTOR: '机构ID+FH+科目代码+流水号',
      MARKER: '机构ID+科目代码+分组号+流水号',
    },
    offline: {
      SUBJECT_HEADER: '+科目代码+流水号',
      INSPECTOR: '+FH+科目代码+流水号',
      MARKER: '+科目代码+分组号+流水号',
    },
  };
  const prefixLabel = computed(() => {
    return prefixLabels[appStore.system.authType][formModel.role];
  });

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

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

  const openSelectSubjectDialog = () => {
    selectSubjectDialogRef.value?.open();
  };

  const handleSubjectsSelected = (subjectCodes: string[]) => {
    formModel.subjectCodes = subjectCodes;
    formRef.value?.validateField('subjectCodes');
  };

  function getTips() {
    const subjectCount = selectSubjectDialogRef.value?.getSubjectCount();
    const selectCount = formModel.subjectCodes.length;
    const codeString = formModel.subjectCodes.join('、');
    const roleName = BATCH_ADD_ROLE[formModel.role];
    if (selectCount === subjectCount) {
      return `确认创建 <strong>全部科目</strong> 的“${roleName}”，每组${formModel.number}个账号吗？`;
    }

    if (selectCount > 5) {
      return `确认创建${selectCount}个科目“${roleName}”，每组${formModel.number}个账号吗？`;
    }

    return `确认创建${codeString}科目“${roleName}”，每组${formModel.number}个账号吗？`;
  }

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

    const confirm = await modalConfirm(getTips(), '提示').catch(() => false);
    if (!confirm) 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());
  };
</script>
