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

import {onMounted, ref} from 'vue';

import {EasyFlowFormModal} from '@easyflow/common-ui';
import {getResourceType} from '@easyflow/utils';

import {api} from '#/api/request';
import DictSelect from '#/components/dict/DictSelect.vue';
import Upload from '#/components/upload/Upload.vue';
import {$t} from '#/locales';
import {syncProgrammaticFieldValidation} from '#/utils/form-validation';

const emit = defineEmits(['reload']);
// vue
onMounted(() => {});
defineExpose({
  openDialog,
});
const saveForm = ref<FormInstance>();
const createDefaultEntity = () => ({
  categoryId: '',
  deptId: '',
  fileSize: '',
  options: '',
  origin: '',
  resourceName: '',
  resourceType: '',
  resourceUrl: '',
  status: 0,
  suffix: '',
});
// variables
const dialogVisible = ref(false);
const isAdd = ref(true);
const entity = ref<any>(createDefaultEntity());
const btnLoading = ref(false);
const rules = ref({
  resourceType: [
    { required: true, message: $t('message.required'), trigger: 'change' },
  ],
  resourceName: [
    {
      required: true,
      message: $t('message.required'),
      trigger: ['blur', 'change'],
    },
  ],
  resourceUrl: [
    { required: true, message: $t('message.required'), trigger: 'change' },
  ],
  origin: [
    { required: true, message: $t('message.required'), trigger: 'change' },
  ],
});

// functions
function openDialog(row: any) {
  isAdd.value = !row?.id;
  entity.value = {
    ...createDefaultEntity(),
    ...row,
    status: row?.status ?? 0,
  };
  dialogVisible.value = true;
}
function save() {
  saveForm.value?.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      api
        .post(
          isAdd.value ? 'api/v1/resource/save' : 'api/v1/resource/update',
          entity.value,
        )
        .then((res) => {
          btnLoading.value = false;
          if (res.errorCode === 0) {
            ElMessage.success(res.message);
            emit('reload');
            closeDialog();
          }
        })
        .catch(() => {
          btnLoading.value = false;
        });
    }
  });
}
function closeDialog() {
  saveForm.value?.resetFields();
  isAdd.value = true;
  entity.value = createDefaultEntity();
  dialogVisible.value = false;
}
function beforeUpload(f: any) {
  const fileName = f?.name || '';
  const fileNameParts = fileName.split('.');
  const fExt = fileNameParts.length > 1 ? fileNameParts[fileNameParts.length - 1] || '' : '';
  const fName =
    fileNameParts.length > 1 ? fileNameParts.slice(0, -1).join('.') : fileName;
  entity.value.resourceType = getResourceType(fExt);
  entity.value.resourceName = fName;
  entity.value.suffix = fExt;
  entity.value.fileSize = f.size;
  entity.value.origin = 0;
  syncProgrammaticFieldValidation(saveForm, [
    'origin',
    'resourceName',
    'resourceType',
  ]);
}
function uploadSuccess(res: any) {
  entity.value.resourceUrl = res;
  syncProgrammaticFieldValidation(saveForm, ['resourceUrl']);
}
function uploadError() {
  entity.value.resourceUrl = '';
  syncProgrammaticFieldValidation(saveForm, ['resourceUrl']);
}
</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="md"
    @confirm="save"
  >
    <ElForm
      ref="saveForm"
      :model="entity"
      status-icon
      :rules="rules"
      label-position="top"
      class="easyflow-modal-form easyflow-modal-form--compact"
    >
      <ElFormItem prop="resourceUrl" :label="$t('aiResource.resourceUrl')">
        <Upload
          @before-upload="beforeUpload"
          @success="uploadSuccess"
          @error="uploadError"
        />
      </ElFormItem>
      <ElFormItem prop="origin" :label="$t('aiResource.origin')">
        <DictSelect v-model="entity.origin" dict-code="resourceOriginType" />
      </ElFormItem>
      <ElFormItem prop="resourceType" :label="$t('aiResource.resourceType')">
        <DictSelect v-model="entity.resourceType" dict-code="resourceType" />
      </ElFormItem>
      <ElFormItem prop="resourceName" :label="$t('aiResource.resourceName')">
        <ElInput v-model.trim="entity.resourceName" />
      </ElFormItem>
      <ElFormItem prop="categoryId" :label="$t('aiResource.categoryId')">
        <DictSelect
          v-model="entity.categoryId"
          dict-code="aiResourceCategory"
        />
      </ElFormItem>
    </ElForm>
  </EasyFlowFormModal>
</template>

<style scoped></style>
