<template>
  <div class="p-base edit-user-view">
    <el-card shadow="never" class="form-card">
      <base-form ref="formRef" :model="model" :items="items" :rules="rules" :label-width="useVW(90)">
        <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="EditUser">
/** 新增/编辑用户 */
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 } from 'global-type'

const props = defineProps<{ id?: string | number }>()

const isEdit = !!props.id

const { back } = useRouter()

const mainStore = useMainStore()

const initModel: ExtractApiParams<'saveUserInfo'> = {
  subjectCode: '',
  mainNumber: void 0,
  markingGroupNumber: void 0,
  role: 'MARKER',
  loginName: '',
  name: '',
  password: '',
  enable: true,
}

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

const { formRef, elFormRef } = 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: '请选择用户角色' }],
    loginName: [{ required: true, message: '请填写账号代码' }],
    password: [{ required: true, message: '请填写用户密码' }],
    enable: [{ required: true, message: '请选择用户状态' }],
  }
})

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

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

const items = computed<EpFormItem[]>(() => {
  return [
    {
      label: '考试批次',
      slotType: 'input',
      slot: {
        disabled: true,
        value: mainStore.myUserInfo?.examName,
      },
    },
    {
      label: '科目',
      slotType: 'select',
      prop: 'subjectCode',
      slot: {
        placeholder: '请选择科目',
        onChange: changeModelValue('subject'),
        options: subjectList.value,
        disabled: isEdit,
      },
    },
    {
      label: '大题',
      slotType: 'select',
      prop: 'mainNumber',
      slot: {
        placeholder: '大题号-大题名称',
        onChange: changeModelValue('question'),
        options: mainQuestionList.value,
        disabled: isEdit,
      },
    },
    {
      label: '用户角色',
      slotType: 'select',
      prop: 'role',
      slot: {
        options: ROLE_OPTION,
        placeholder: '设置用户角色',
        disabled: isEdit,
      },
    },
    model.role !== 'CHIEF'
      ? {
          label: '小组',
          slotType: 'select',
          prop: 'markingGroupNumber',
          slot: {
            placeholder: '用户所在小组',
            options: groupList.value,
            onChange: changeModelValue('group'),
            disabled: isEdit,
          },
        }
      : null,
    {
      label: '账号代码',
      slotType: 'input',
      prop: 'loginName',
      slot: {
        placeholder: '账号代码',
        disabled: isEdit,
      },
    },
    !isEdit && {
      label: '用户密码',
      slotType: 'input',
      prop: 'password',
      slot: {
        showPassword: true,
        placeholder: '设置用户密码',
        disabled: isEdit,
      },
    },
    {
      label: '姓名',
      slotType: 'input',
      prop: 'name',
      slot: {
        placeholder: '设置用户姓名',
      },
    },
    {
      label: '状态',
      slotType: 'select',
      prop: 'enable',
      slot: {
        options: StatusMap,
        placeholder: '用户状态',
      },
    },
  ].filter(Boolean) as EpFormItem[]
})

/** 编辑模式 */
const { fetch: getUserInfo } = useFetch('getUserInfo')

if (isEdit) {
  getUserInfo({ id: +props.id }).then((result) => {
    const { subjectCode, markingGroupNumber, mainNumber, role, loginName, name, enable, id } = result
    changeModelValue('subject')(subjectCode)
    nextTick(() => {
      changeModelValue('question')(mainNumber)
    }).then(() => {
      changeModelValue('group')(markingGroupNumber)
    })
    Object.assign(model, { subjectCode, markingGroupNumber, mainNumber, role, loginName, name, enable, id })
  })
}

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

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

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

<style scoped lang="scss">
.edit-user-view {
  .form-card {
    padding-right: 1000px;
  }
}
</style>
