<template>
  <div class="p-base bulk-add-user-view">
    <el-card shadow="never" class="form-card">
      <base-form ref="formRef" :label-width="useVW(130)" :groups="groups" :model="model" :items="items" :rules="rules">
        <el-form-item class="m-t-base form-footer">
          <confirm-button :loading="loading" @confirm="onSubmit" @cancel="cancel"></confirm-button>
        </el-form-item>
      </base-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="BulkAddUser">
/** 批量新增用户 */
import { reactive, watch, nextTick, unref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElCard, ElFormItem, ElMessage } from 'element-plus'
import BaseForm from '@/components/element/BaseForm.vue'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import useFetch from '@/hooks/useFetch'
import useForm from '@/hooks/useForm'
import useVW from '@/hooks/useVW'
import useOptions from '@/hooks/useOptions'
import useMainStore from '@/store/main'
import { StatusMap, ROLE_OPTION } from '@/constants/dicts'

import type { ExtractApiParams } from '@/api/api'
import type { EpFormItem, EpFormRules, FormGroup } from 'global-type'

const { back } = useRouter()

const mainStore = useMainStore()

const { subjectList, mainQuestionList, groupList, dataModel, changeModelValue } = useOptions([
  'subject',
  'question',
  'group',
])

const initModel: ExtractApiParams<'bulkSaveUser'> = {
  subjectCode: dataModel.subject || '',
  mainNumber: dataModel.question,
  markingGroupNumber: dataModel.group,
  enable: true,
  loginNameLength: 3,
  markingGroupAccounts: void 0,
  password: '',
  prefix: '',
  role: 'MARKER',
  start: 1,
}

const model = reactive<ExtractApiParams<'bulkSaveUser'>>(initModel)

const { formRef, elFormRef, defineColumn, _ } = useForm()

const rules = computed<EpFormRules>(() => {
  return {
    subjectCode: [{ required: true, message: '请选择科目' }],
    mainNumber: [{ required: true, message: '请选择大题' }],
    markingGroupNumber: model.role !== 'CHIEF' ? [{ required: true, message: '请选择小组' }] : [],
    role: [{ required: true, message: '请选择用户角色' }],
    loginNameLength: [{ required: true, message: '请填写账号代码位数' }],
    password: [{ required: true, message: '请填写用户密码' }],
    enable: [{ required: true, message: '请选择用户状态' }],
    markingGroupAccounts: [{ required: true, message: '请填写分组账号数量' }],
    prefix: [{ required: true, message: '请填写账号前缀' }],
    start: [{ required: true, message: '请填写账号起始数' }],
  }
})

watch(dataModel, () => {
  model.subjectCode = dataModel.subject || ''
  model.mainNumber = dataModel.question
  model.markingGroupNumber = dataModel.group
})

const groups: FormGroup[] = [
  {
    rowKeys: ['row-1', 'row-2', 'row-3', 'row-4', 'row-5'],
  },
  {
    groupTitle: '批量新增设置',
    rowKeys: ['row-6', 'row-7', 'row-8', 'row-9'],
  },
]

const span7 = defineColumn(_, '', { span: 7 })

const items = computed<EpFormItem[]>(() => {
  return [
    {
      label: '考试批次',
      slotType: 'input',
      slot: {
        disabled: true,
        value: mainStore.myUserInfo?.examName,
      },
      colProp: {
        span: 6,
      },
    },
    span7({
      label: '科目',
      slotType: 'select',
      prop: 'subjectCode',
      slot: {
        placeholder: '请选择科目',
        onChange: changeModelValue('subject'),
        options: subjectList.value,
      },
    }),
    span7({
      label: '大题',
      slotType: 'select',
      prop: 'mainNumber',
      slot: {
        placeholder: '大题号-大题名称',
        onChange: changeModelValue('question'),
        options: mainQuestionList.value,
      },
    }),
    span7({
      label: '用户角色',
      slotType: 'select',
      prop: 'role',
      slot: {
        options: ROLE_OPTION,
        placeholder: '设置用户角色',
      },
    }),
    model.role !== 'CHIEF'
      ? span7({
          label: '小组',
          slotType: 'select',
          prop: 'markingGroupNumber',
          slot: {
            placeholder: '用户所在小组',
            options: groupList.value,
            onChange: changeModelValue('group'),
          },
        })
      : null,
    span7({
      rowKey: 'row-6',
      label: '自定义前缀',
      slotType: 'input',
      prop: 'prefix',
      slot: {
        placeholder: '自定义账号前缀',
      },
    }),
    span7({
      rowKey: 'row-6',
      label: '账号代码位数',
      slotType: 'inputNumber',
      prop: 'loginNameLength',
      slot: {
        placeholder: '账号代码位数',
      },
    }),
    span7({
      rowKey: 'row-7',
      label: '起始数',
      slotType: 'input',
      prop: 'start',
      slot: {
        placeholder: '起始数',
      },
    }),
    span7({
      rowKey: 'row-7',
      label: '账号数量',
      slotType: 'input',
      prop: 'markingGroupAccounts',
      slot: {
        placeholder: '账号数量',
      },
    }),
    span7({
      rowKey: 'row-8',
      label: '用户密码',
      slotType: 'input',
      prop: 'password',
      slot: {
        showPassword: true,
        placeholder: '设置用户密码',
      },
    }),
    span7({
      rowKey: 'row-9',
      label: '状态',
      slotType: 'select',
      prop: 'enable',
      slot: {
        options: StatusMap,
        placeholder: '设置用户角色',
      },
    }),
  ].filter(Boolean) as EpFormItem[]
})

const { fetch, loading } = useFetch('bulkSaveUser')

/** 确定提交 */
async function onSubmit() {
  try {
    await unref(elFormRef)?.validate()
    await fetch(model)
    unref(elFormRef)?.resetFields()
    ElMessage.success({
      message: `创建用户成功`,
      duration: 1000,
    })
    back()
  } catch (error) {
    console.error(error)
  }
}

/** 取消 */
function cancel() {
  back()
}
</script>

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