<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="'90px'">
        <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, ref } 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 } from '@/constants/dicts'
import bus from '@/utils/bus'
import type { ExtractApiParams } from '@/api/api'
import type { EpFormItem, EpFormRules } 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 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<any>(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: '请填写账号代码' },
      { pattern: /[0-9a-zA-Z]/, message: '账号代码限制"数字、字母"' },
    ],
    password: [
      { required: true, message: '请填写用户密码' },
      { pattern: /[0-9a-zA-Z~!@#￥%&\*]/, message: '密码限制"数字、字母、~!@#￥%&\*"' },
    ],
    enable: [{ required: true, message: '请选择用户状态' }],
    name: [{ type: 'string', max: 50, message: '用户名称限制50字以内' }],
  }
})

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

// watch(dataModel, () => {
//   if (model.role !== 'EXPERT' && model.role !== 'SECTION_LEADER') {
//     model.subjectCode = dataModel.subject || ''
//     model.mainNumber = dataModel.question
//     model.markingGroupNumber = dataModel.group
//   }
//   if (model.role === 'SECTION_LEADER') {
//     model.subjectCode = dataModel.subject || '全部'
//   }
// })
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 items = computed<EpFormItem[]>(() => {
  return [
    {
      label: '考试批次',
      slotType: 'input',
      slot: {
        disabled: true,
        value: mainStore.myUserInfo?.examName,
      },
    },
    {
      label: '用户角色',
      slotType: 'select',
      prop: 'role',
      slot: {
        options: ROLE_OPTION.value,
        placeholder: '设置用户角色',
        disabled: isEdit,
      },
    },
    {
      label: '科目',
      slotType: 'select',
      prop: 'subjectCode',
      slot: {
        placeholder: '请选择科目',
        onChange: changeModelValue('subject'),
        options: model.role === 'EXPERT' ? [{ value: '全部', label: '全部' }, ...subjectList.value] : subjectList.value,
        disabled: isEdit || model.role === 'EXPERT',
      },
    },
    {
      label: '大题',
      slotType: 'select',
      prop: 'mainNumber',
      slot: {
        placeholder: '大题号-大题名称',
        onChange: changeModelValue('question'),
        options:
          model.role === 'EXPERT' || model.role === 'SECTION_LEADER'
            ? [{ label: '全部', value: '全部' }, ...mainQuestionList.value]
            : mainQuestionList.value,
        disabled: isEdit || model.role === 'EXPERT' || model.role === 'SECTION_LEADER',
      },
    },

    model.role !== 'CHIEF'
      ? {
          label: '小组',
          slotType: 'select',
          prop: 'markingGroupNumber',
          slot: {
            placeholder: '用户所在小组',
            options:
              model.role === 'EXPERT' || model.role === 'SECTION_LEADER'
                ? [{ label: '全部', value: '全部' }, ...groupList.value]
                : groupList.value,
            onChange: changeModelValue('group'),
            disabled: isEdit || model.role === 'EXPERT' || model.role === 'SECTION_LEADER',
          },
        }
      : 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()
    let data: any = {}
    for (let k in model) {
      if (model[k] !== '全部') {
        data[k] = model[k]
      }
    }
    await fetch(data)
    // unref(elFormRef)?.resetFields()   //移到下面去了
    ElMessage.success({
      message: `${isEdit ? '修改' : '创建'}用户成功`,
      duration: 1000,
    })
    back()
    bus.emit('updateUser')
    // unref(elFormRef)?.resetFields()
  } catch (error) {
    console.error(error)
  }
}

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

<style scoped lang="scss">
.edit-user-view {
  .form-card {
    padding-right: calc(100% - 420px);
  }
}
</style>
