<template>
  <el-drawer
    v-model="visible"
    title="文件搜索"
    :size="400"
    :close-on-click-modal="false"
    @close="closeFun"
  >
    <div class="content">
      <TableForm ref="tableFormRef" v-model:data="searchData" tableName="DATA_OVERVIEW_SEARCH">
        <template #form-fileSize>
          <div class="file-size">
            <el-input-number class="size" v-model="searchData.fileSize" />
            <el-select class="unit" v-model="searchData.fileSizeUnit">
              <el-option
                v-for="(item, index) in FILE_SIZE_UNIT.A"
                :key="index"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </div>
        </template>
      </TableForm>
    </div>
    <template #footer>
      <div>
        <el-button @click="resetFun">重置</el-button>
        <el-button type="primary" @click="searchFun">
          {{ loading ? '搜索中...' : '搜索' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import TableForm from '@/components/common/table/tableForm.vue';
import { dataOverViewSearchSimulationNodeFilesApi } from '@/api/data/dataOverView';
import { useDict } from '@/utils/useDict';

const { FILE_SIZE_UNIT } = useDict('FILE_SIZE_UNIT');
const emit = defineEmits(['update:modelValue', 'search', 'reset']);
const tableFormRef = ref();
const visible = ref(false);
const searchData = ref<any>({});
const loading = ref(false);

interface Props {
  modelValue: boolean;
  data: any;
  fileIds: any;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  data: {},
  fileIds: [],
});

watch(
  () => props.modelValue,
  (val: boolean) => {
    visible.value = val;
  }
);

const searchFun = async () => {
  const valid = await tableFormRef.value.validateFun();
  if (valid) {
    emit('search', []);
    loading.value = true;
    const params = {
      ...searchData.value,
      current: 1,
      size: 9999,
    };
    if (props.data.id) {
      params.parentDirIds = props.fileIds;
    } else {
      // 根目录
      params.dirType = 2;
    }
    dataOverViewSearchSimulationNodeFilesApi(params)
      .then((res: any) => {
        if (res.code === 200) {
          emit('search', res.data);
          closeFun();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

const resetFun = () => {
  searchData.value = {};
  emit('reset');
  closeFun();
};

const closeFun = () => {
  emit('update:modelValue', false);
};
</script>

<style lang="scss" scoped>
.content {
  .file-size {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .size {
      width: 150px;
    }
    .unit {
      width: 100px;
    }
  }
}
</style>
