<script setup lang="ts">
import type {FormInstance} from 'element-plus';
import {ElForm, ElFormItem, ElInput, ElMessage} from 'element-plus';

import {onMounted, ref, watch} from 'vue';

import {EasyFlowFormModal, EasyFlowInputPassword} from '@easyflow/common-ui';

import {getCredentialKeyApi} from '#/api';
import {api} from '#/api/request';
import DictSelect from '#/components/dict/DictSelect.vue';
// import Cropper from '#/components/upload/Cropper.vue';
import UploadAvatar from '#/components/upload/UploadAvatar.vue';
import {$t} from '#/locales';
import {encryptCredentialPayload} from '#/utils/credential-encryption';
import {isStrongPassword} from '#/utils/password-policy';

const emit = defineEmits(['reload']);
// vue
onMounted(() => {});
defineExpose({
  openDialog,
});
const saveForm = ref<FormInstance>();
// variables
const dialogVisible = ref(false);
const isAdd = ref(true);
function createDefaultEntity() {
  return {
    deptId: '',
    loginName: '',
    password: '',
    confirmPassword: '',
    accountType: '',
    nickname: '',
    mobile: '',
    email: '',
    avatar: '',
    dataScope: '',
    deptIdList: '',
    status: 1,
    remark: '',
    positionIds: [],
    roleIds: [],
  };
}
const entity = ref<any>(createDefaultEntity());
const validateStrongPassword = (_rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error($t('message.required')));
    return;
  }
  if (!isStrongPassword(value)) {
    callback(new Error($t('sysAccount.passwordStrongTip')));
    return;
  }
  callback();
};
const validateConfirmPassword = (_rule: any, value: string, callback: any) => {
  if (!isAdd.value) {
    callback();
    return;
  }
  if (!value) {
    callback(new Error($t('sysAccount.repeatPwd')));
    return;
  }
  if (value !== entity.value.password) {
    callback(new Error($t('sysAccount.notSamePwd')));
    return;
  }
  callback();
};
const btnLoading = ref(false);
const rules = ref({
  deptId: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
  loginName: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
  nickname: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
  password: [
    { required: true, validator: validateStrongPassword, trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' },
  ],
  status: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
});
// functions
function openDialog(row: any) {
  isAdd.value = !row?.id;
  entity.value = {
    ...createDefaultEntity(),
    ...row,
  };
  if (!Array.isArray(entity.value.roleIds)) {
    entity.value.roleIds = [];
  }
  if (!Array.isArray(entity.value.positionIds)) {
    entity.value.positionIds = [];
  }
  dialogVisible.value = true;
}
function save() {
  saveForm.value?.validate(async (valid) => {
    if (valid) {
      btnLoading.value = true;
      try {
        const {
          confirmPassword: _confirmPassword,
          password,
          ...payload
        } = entity.value;
        if (isAdd.value) {
          payload.passwordCredential = await encryptCredentialPayload(
            getCredentialKeyApi,
            { password },
          );
        }
        const res = await api.post(
          isAdd.value ? 'api/v1/sysAccount/save' : 'api/v1/sysAccount/update',
          payload,
        );
        if (res.errorCode === 0) {
          ElMessage.success(res.message);
          emit('reload');
          closeDialog();
        }
      } finally {
        btnLoading.value = false;
      }
    }
  });
}
function closeDialog() {
  saveForm.value?.resetFields();
  isAdd.value = true;
  entity.value = createDefaultEntity();
  dialogVisible.value = false;
}

watch(
  () => entity.value.password,
  () => {
    if (!dialogVisible.value || !isAdd.value || !entity.value.confirmPassword) {
      return;
    }
    saveForm.value?.validateField('confirmPassword').catch(() => {});
  },
);
</script>

<template>
  <EasyFlowFormModal
    v-model:open="dialogVisible"
    :title="isAdd ? $t('button.add') : $t('button.edit')"
    :before-close="closeDialog"
    :confirm-loading="btnLoading"
    :confirm-text="$t('button.save')"
    :submitting="btnLoading"
    width="xl"
    @confirm="save"
  >
    <ElForm
      ref="saveForm"
      :model="entity"
      status-icon
      :rules="rules"
      label-position="top"
      class="easyflow-modal-form easyflow-modal-form--compact"
    >
      <ElFormItem prop="avatar" :label="$t('sysAccount.avatar')">
        <!-- <Cropper v-model="entity.avatar" crop /> -->
        <UploadAvatar v-model="entity.avatar" />
      </ElFormItem>
      <ElFormItem prop="deptId" :label="$t('sysAccount.deptId')">
        <DictSelect v-model="entity.deptId" dict-code="sysDept" />
      </ElFormItem>
      <ElFormItem prop="loginName" :label="$t('sysAccount.loginName')">
        <ElInput v-model.trim="entity.loginName" />
      </ElFormItem>
      <ElFormItem
        v-if="isAdd"
        prop="password"
        :label="$t('sysAccount.password')"
      >
        <div class="w-full">
          <EasyFlowInputPassword v-model="entity.password" password-strength />
          <div class="mt-2 text-xs text-[var(--el-text-color-secondary)]">
            {{ $t('sysAccount.passwordStrongTip') }}
          </div>
        </div>
      </ElFormItem>
      <ElFormItem
        v-if="isAdd"
        prop="confirmPassword"
        :label="$t('sysAccount.confirmPwd')"
      >
        <EasyFlowInputPassword
          v-model="entity.confirmPassword"
          :placeholder="$t('sysAccount.repeatPwd')"
        />
      </ElFormItem>
      <ElFormItem prop="nickname" :label="$t('sysAccount.nickname')">
        <ElInput v-model.trim="entity.nickname" />
      </ElFormItem>
      <ElFormItem prop="mobile" :label="$t('sysAccount.mobile')">
        <ElInput v-model.trim="entity.mobile" />
      </ElFormItem>
      <ElFormItem prop="email" :label="$t('sysAccount.email')">
        <ElInput v-model.trim="entity.email" />
      </ElFormItem>
      <ElFormItem prop="status" :label="$t('sysAccount.status')">
        <DictSelect v-model="entity.status" dict-code="dataStatus" />
      </ElFormItem>
      <ElFormItem prop="remark" :label="$t('sysAccount.remark')">
        <ElInput v-model.trim="entity.remark" />
      </ElFormItem>
      <ElFormItem prop="roleIds" :label="$t('sysAccount.roleIds')">
        <DictSelect multiple v-model="entity.roleIds" dict-code="sysRole" />
      </ElFormItem>
      <ElFormItem prop="positionIds" :label="$t('sysAccount.positionIds')">
        <DictSelect
          multiple
          v-model="entity.positionIds"
          dict-code="sysPosition"
        />
      </ElFormItem>
    </ElForm>
  </EasyFlowFormModal>
</template>

<style scoped></style>
