<template>
  <div class="p-base bulk-add-user-view">
    <el-card shadow="never" class="form-card">
      <base-form ref="formRef" :label-width="'130px'" :groups="groups" :model="model" :items="items" :rules="rules">
        <template #form-item-examName>
          <el-input :value="mainStore.myUserInfo?.examName" disabled />
        </template>
        <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, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElCard, ElFormItem, ElMessage, ElInput } 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 } from '@/constants/dicts'

import type { ExtractApiParams } from '@/api/api'
import type { EpFormItem, EpFormRules, FormGroup } from 'global-type'
const ROLE_OPTION = ref<any[]>([])
useFetch('getRoleList')
  .fetch()
  .then((res: any) => {
    ROLE_OPTION.value = res.map((item: any) => {
      return {
        value: item.code,
        label: item.roleName,
      }
    })
  })
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,
  employer: '',
}

const model = reactive<any>(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: '请填写账号代码位数' },
      { type: 'number', min: 0, max: 9, message: '账号代码位数限制0-9之间' },
    ],
    password: [
      { required: true, message: '请填写用户密码' },
      { pattern: /[0-9a-zA-Z~!@#￥%&\*]/, message: '密码限制"数字、字母、~!@#￥%&\*"' },
    ],
    enable: [{ required: true, message: '请选择用户状态' }],
    stage: model.role === 'MARKER' ? [{ required: true, message: '请选择评卷阶段' }] : [],
    markingGroupAccounts: [
      { required: true, message: '请填写分组账号数量' },
      { type: 'number', min: 0, max: 999999, message: '分组账号数量限制0-999999之间' },
    ],
    prefix: [
      { required: true, message: '请填写账号前缀' },
      { type: 'string', max: 50, message: '账号前缀限制50字以内' },
      { pattern: /[0-9a-zA-Z]/, message: '账号前缀限制"数字、字母"' },
    ],
    start: [
      { required: true, message: '请填写账号起始数' },
      { type: 'number', min: 0, max: 999999, message: '账号起始数限制0-999999之间' },
    ],
  }
})

watch(dataModel, () => {
  if (model.role !== 'EXPERT' && model.role !== 'SECTION_LEADER') {
    model.subjectCode = dataModel.subject || ''
    model.mainNumber = dataModel.question
    model.markingGroupNumber = dataModel.group
  }
})
watch(
  () => model.role,
  () => {
    if (model.role === 'EXPERT') {
      model.subjectCode = '全部'
      model.mainNumber = '全部'
      model.markingGroupNumber = '全部'
    } else if (model.role === 'SECTION_LEADER') {
      model.subjectCode = ''
      model.mainNumber = '全部'
      model.markingGroupNumber = '全部'
    } else {
      model.subjectCode = ''
      model.mainNumber = void 0
      model.markingGroupNumber = void 0
    }
  }
)

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

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

const items = computed<EpFormItem[]>(() => {
  return [
    {
      label: '考试批次',
      slotName: 'examName',
      // slotType: 'input',
      // slot: {
      //   disabled: true,
      //   value: mainStore.myUserInfo?.examName,
      // },
      colProp: {
        span: 6,
      },
    },
    span7({
      label: '用户角色',
      slotType: 'select',
      prop: 'role',
      slot: {
        options: ROLE_OPTION.value,
        placeholder: '设置用户角色',
      },
    }),
    span7({
      label: '科目',
      slotType: 'select',
      prop: 'subjectCode',
      slot: {
        placeholder: '请选择科目',
        onChange: changeModelValue('subject'),
        options: model.role === 'EXPERT' ? [{ value: '全部', label: '全部' }, ...subjectList.value] : subjectList.value,
        disabled: model.role === 'EXPERT',
      },
    }),
    span7({
      label: '大题',
      slotType: 'select',
      prop: 'mainNumber',
      slot: {
        placeholder: '大题号-大题名称',
        onChange: changeModelValue('question'),
        // options: mainQuestionList.value,
        options:
          model.role === 'EXPERT' || model.role === 'SECTION_LEADER'
            ? [{ label: '全部', value: '全部' }, ...mainQuestionList.value]
            : mainQuestionList.value,
        disabled: model.role === 'EXPERT' || model.role === 'SECTION_LEADER',
      },
    }),

    model.role !== 'CHIEF'
      ? span7({
          label: '小组',
          slotType: 'select',
          prop: 'markingGroupNumber',
          slot: {
            placeholder: '用户所在小组',
            // options: groupList.value,
            onChange: changeModelValue('group'),
            options:
              model.role === 'EXPERT' || model.role === 'SECTION_LEADER'
                ? [{ label: '全部', value: '全部' }, ...groupList.value]
                : groupList.value,
            disabled: model.role === 'EXPERT' || model.role === 'SECTION_LEADER',
          },
        })
      : null,
    span7({
      rowKey: 'row-6',
      label: '自定义前缀',
      slotType: 'input',
      prop: 'prefix',
      slot: {
        placeholder: '自定义账号前缀',
      },
    }),
    span7({
      rowKey: 'row-6',
      label: '账号代码位数',
      slotType: 'inputNumber',
      prop: 'loginNameLength',
      slot: {
        placeholder: '账号代码位数',
        step: 1,
        stepStrictly: true,
      },
    }),
    span7({
      rowKey: 'row-7',
      label: '起始数',
      slotType: 'inputNumber',
      prop: 'start',
      slot: {
        placeholder: '起始数',
        step: 1,
        stepStrictly: true,
      },
    }),
    span7({
      rowKey: 'row-7',
      label: '账号数量',
      slotType: 'inputNumber',
      prop: 'markingGroupAccounts',
      slot: {
        placeholder: '账号数量',
        step: 1,
        stepStrictly: true,
      },
    }),
    span7({
      rowKey: 'row-8',
      label: '用户密码',
      slotType: 'input',
      prop: 'password',
      slot: {
        showPassword: true,
        placeholder: '设置用户密码',
      },
    }),
    model.role === 'MARKER'
      ? span7({
          rowKey: 'row-8',
          label: '阶段',
          slotType: 'select',
          prop: 'stage',
          slot: {
            placeholder: '选择阶段',
            options: [
              { label: 'SAMPLE_A', value: 'SAMPLE_A' },
              { label: 'SAMPLE_B', value: 'SAMPLE_B' },
              // { label: '强制考核卷', value: 'FORCE' },
              { label: '正评', value: 'FORMAL' },
            ],
          },
        })
      : null,
    span7({
      rowKey: 'row-9',
      label: '状态',
      slotType: 'select',
      prop: 'enable',
      slot: {
        options: StatusMap,
        placeholder: '设置用户角色',
      },
    }),
    span7({
      rowKey: 'row-9',
      label: '单位',
      slotType: 'input',
      prop: 'employer',
      slot: {
        maxlength: 100,
        placeholder: '设置用户单位',
      },
    }),
  ].filter(Boolean) as EpFormItem[]
})

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

/** 确定提交 */
async function onSubmit() {
  try {
    await unref(elFormRef)?.validate()
    let data: any = {}
    for (let k in model) {
      if (model[k] !== '全部') {
        data[k] = model[k]
      }
    }
    await fetch(data)
    // unref(elFormRef)?.resetFields()
    ElMessage.success({
      message: `创建用户成功`,
      duration: 1000,
    })
    back()
  } catch (error) {
    console.error(error)
  }
}

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

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