<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import dayjs from 'dayjs';
import { fetchGetUser, fetchUpdateUser } from '@/service/api';
import { useForm } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import { $t } from '@/locales';

defineOptions({ name: 'UserResignedDialog' });

interface Props {
  userId?: number | null;
  username?: string | null;
  resignedAt?: number | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef } = useForm();

const submitting = ref(false);

const title = computed(() => {
  if (props.resignedAt && props.resignedAt > Date.now()) {
    return $t('page.system.user.adjustResignUser');
  }

  return $t('page.system.user.resignUser');
});
const displayUsername = computed(() => props.username?.trim() || $t('common.noData'));

const model = ref({
  resignedAt: null as Date | null
});

function createCurrentTime() {
  return dayjs().second(0).millisecond(0).toDate();
}

function initModel() {
  model.value.resignedAt = props.resignedAt ? dayjs(props.resignedAt).toDate() : createCurrentTime();
}

function closeDialog() {
  visible.value = false;
}

async function handleSubmit() {
  if (!props.userId) {
    return;
  }

  submitting.value = true;

  const detailResult = await fetchGetUser(props.userId);

  if (detailResult.error) {
    submitting.value = false;
    return;
  }

  const user = detailResult.data;

  const { error } = await fetchUpdateUser({
    id: props.userId,
    username: user.username,
    nickname: user.nickname ?? null,
    remark: user.remark ?? null,
    deptId: user.deptId,
    positionId: user.positionId ?? null,
    resignedAt: model.value.resignedAt ? dayjs(model.value.resignedAt).valueOf() : null,
    email: user.email ?? null,
    mobile: user.mobile ?? null,
    sex: user.sex ?? 0,
    avatar: user.avatar ?? null
  });

  submitting.value = false;

  if (error) {
    return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDialog();
  emit('submitted');
}

watch(visible, async value => {
  if (!value) {
    return;
  }

  initModel();
  await nextTick();
  formRef.value?.clearValidate();
});
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="title"
    preset="sm"
    :confirm-loading="submitting"
    :scrollbar="false"
    @confirm="handleSubmit"
  >
    <ElForm ref="formRef" :model="model" label-position="top">
      <ElRow :gutter="16">
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.user.userName')">
            <ElInput :model-value="displayUsername" disabled />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.user.resignedAt')" style="width: 100%">
            <ElDatePicker
              v-model="model.resignedAt"
              class="w-full"
              style="width: 100%"
              type="datetime"
              clearable
              :placeholder="$t('page.system.user.form.resignedAt')"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </BusinessFormDialog>
</template>
