<template>
  <Dialog v-model="visible" :diaTitle="$t('知识库.上传')" :width="500" showFooter>
    <template #default>
      <TableForm
        ref="tableFormRef"
        :tableName="tableName"
        v-model:data="formData"
        :formAttrs="formAttrs"
        :itemNum="6"
        @change="onFormChangeFun"
      >
        <template #form-simulationPoolInfoList>
          <pool-task-select v-model="formData.simulationPoolInfoList" layout="vertical" />
        </template>
      </TableForm>
    </template>
    <template #footer>
      <div>
        <el-button @click="onCancelFun">{{ $t('通用.取消') }}</el-button>
        <el-button
          type="primary"
          :loading="confirmLoading"
          :disabled="!isDirty"
          @click="onConfirmFun"
          >{{ $t('通用.确定') }}</el-button
        >
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watchEffect, watch } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import PoolTaskSelect from '@/components/pool/poolTaskSelect.vue';
import TableForm from '@/components/common/table/tableForm.vue';
import { useDirtyForm } from '@/utils/useDirtyForm';

interface Props {
  modelValue?: boolean;
  detail?: any;
  folder?: any;
  tableName: string;
  confirmLoading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  detail: null,
  folder: null,
  tableName: '',
  confirmLoading: false,
});
const emits = defineEmits<{
  'update:modelValue': [val: boolean];
  confirm: [data: any];
}>();
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emits('update:modelValue', val),
});

interface RuleForm {
  originalName: any;
  projectId: string | null;
  analysisDirectionId: string | null;
  simulationPoolInfoList?: Array<any>;
  remarks: string | null;
  templateName?: string | null;
  templateId?: string | null;
}
const formData = ref<RuleForm>({
  originalName: null,
  projectId: null,
  analysisDirectionId: null,
  simulationPoolInfoList: undefined,
  remarks: null,
  templateName: null,
  templateId: null,
});
const isEdit = computed(() => !!(props.detail && props.detail.id));
const { isDirty, init: initSnapshot } = useDirtyForm(formData, {
  mode: () => (isEdit.value ? 'edit' : 'add'),
  pick: (data) => ({
    originalName: data.originalName?.map(({ fileId, name }: any) => ({ fileId, name })),
    projectId: data.projectId,
    analysisDirectionId: data.analysisDirectionId,
    simulationPoolInfoList: data.simulationPoolInfoList,
    remarks: data.remarks,
    templateId: data.templateId,
  }),
});

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      resetFun();
      if (props.detail && props.detail.id) {
        initData();
      }
    }
  }
);

const initData = () => {
  const file = [
    {
      fileId: props.detail?.id,
      name: props.detail?.originalName,
    },
  ];
  formData.value = { ...props.detail, ...{ originalName: file } };
  formData.value.simulationPoolInfoList = props.detail?.poolInfos;
  initSnapshot(formData.value);
};
watchEffect(() => {
  nextTick(() => {
    if (props.detail && props.detail.id) {
      initData();
    }
  });
});
const resetFun = () => {
  formData.value = {
    originalName: null,
    projectId: null,
    analysisDirectionId: null,
    remarks: null,
    templateName: null,
    templateId: null,
    simulationPoolInfoList: undefined,
  };
  initSnapshot();
  tableFormRef.value?.resetFun();
};
const formAttrs = computed(() => ({
  originalName: {
    multiple: !isEdit.value,
    limit: isEdit.value ? 1 : undefined,
  },
}));

const onFormChangeFun = (data: any) => {
  formData.value = tableFormRef.value.getFormDataFun();
  if (data.key === 'templateId') {
    formData.value.templateId = data?.val?.value;
    formData.value.templateName = data?.val?.label;
  }
};
const tableFormRef = ref<any>();
const onCancelFun = () => {
  visible.value = false;
};
const onConfirmFun = async () => {
  const valid = await tableFormRef.value?.validateFun();
  if (valid) {
    const data = tableFormRef.value?.getFormDataFun();
    const formResult = { ...data, ...formData.value };
    if (formData.value?.originalName && formData.value?.originalName.length > 0) {
      formResult.file = formResult.originalName.map((item: any) => {
        return {
          fileName: item.raw?.name,
          size: item.raw?.size,
          raw: item.raw,
        };
      });
    }
    emits('confirm', formResult);
  }
};
</script>
<style lang="scss" scoped>
.upload {
  width: 100%;
}
</style>
