import { defineStore } from 'pinia'
import { getAttachmentListApi } from '@/service/file'
import { until } from '@vueuse/core'

export const useFileStore = defineStore(
  'file',
  () => {
    // 文件前缀地址
    const fileHeadUrl = ref('')

    // 查询附件列表
    const getAttachmentList = async ({
      attlsh,
      attmodel,
    }: {
      attlsh: string
      attmodel: string
    }) => {
      const { data: configList, loading } = useRequest(
        () => getAttachmentListApi({ attlsh, attmodel }, { pageindex: 1, rows: 999 }),
        {
          immediate: true,
        },
      )

      await until(loading).toBe(false)
      // https://dzapi.kdboss.cn/upfile/orders_invoice/20250410/2025041018283477178626.png

      const fileList = configList.value.Data.map((item) => {
        return {
          ...item,
          url: `${fileHeadUrl.value}${item.attpath}${item.attname}.${item.atttype}`,
        }
      })

      return fileList
    }

    const setFileHeadUrl = (url: string) => {
      fileHeadUrl.value = url
    }

    return {
      getAttachmentList,
      setFileHeadUrl,
      fileHeadUrl,
    }
  },
  {
    persist: true,
  },
)
