<script setup lang="ts">
import XReport from '@af-mobile-client-vue3/components/data/XReportGrid/XReport.vue'
import { useUserStore } from '@af-mobile-client-vue3/stores/modules/user'
import { executeStrFunctionByContext } from '@af-mobile-client-vue3/utils/runEvalFunction'
import { storeToRefs } from 'pinia'
import { showDialog, Dialog as VanDialog } from 'vant'
import { inject, provide, ref } from 'vue'

// Props
const props = defineProps({
  env: {
    type: String,
    default: 'prod',
  },
})

// Emits
const emit = defineEmits<{
  (e: 'close'): void
  (e: 'selectRow', keys: any[], rows: any[]): void
}>()
// 状态管理
const showReport = ref(true)
const configName = ref('')
const displayOnly = ref(true)
const serverName = ref(process.env.VUE_APP_SYSTEM_NAME)
const loading = ref(false)
const visible = ref(false)
const selectedId = ref(null)
const mixinData = ref({})
const outEnv = ref({})
const attr = ref({})

// Store
const userStore = useUserStore()
const currUser = storeToRefs(userStore)

// Refs
const mainRef = ref()

// 注入
const getParentComponentByName = inject<Function>('getParentComponentByName')
const setGlobalData = inject<Function>('setGlobalData')
const getGlobalData = inject<Function>('getGlobalData')

// 提供依赖
provide('getSelectedId', () => getSelectedId())
provide('getSelectedData', () => selectedId.value)
provide('getMixinData', () => mixinData.value)
provide('getOutEnv', () => outEnv.value)
provide('isInAModal', () => true)
provide('currUser', currUser)

// Methods
function init(params: {
  configName?: string
  serverName?: string
  displayOnly?: boolean
  selectedId?: any
  outEnv?: Record<string, any>
  mixinData?: Record<string, any>
  attr?: Record<string, any>
}) {
  const {
    configName: initConfigName = 'medicalRecordCover',
    serverName: initServerName = process.env.VUE_APP_SYSTEM_NAME,
    displayOnly: initDisplayOnly = true,
    selectedId: initSelectedId = null,
    outEnv: initOutEnv = {},
    mixinData: initMixinData = {},
    attr: initAttr = {},
  } = params

  configName.value = initConfigName
  serverName.value = initServerName
  displayOnly.value = initDisplayOnly
  visible.value = true
  attr.value = initAttr

  if (initSelectedId)
    selectedId.value = initSelectedId

  mixinData.value = initMixinData
  outEnv.value = initOutEnv
}

function getSelectedId() {
  if (typeof selectedId.value === 'object') {
    if (selectedId.value?.selectedId)
      return selectedId.value.selectedId

    if (Object.keys(selectedId.value).length > 0)
      return selectedId.value[Object.keys(selectedId.value)[0]]
  }
  return selectedId.value
}

function selectRow(selectedRowKeys: any[], selectedRows: any[]) {
  emit('selectRow', selectedRowKeys, selectedRows)
}

function close() {
  loading.value = false
  visible.value = false
  emit('close')
}

function getComponentByName(name: string) {
  const innerRef = getParentComponentByName?.(name)
  if (innerRef)
    return innerRef

  return mainRef.value?.getComponentByName(name)
}

async function onSubmit() {
  if (mainRef.value?.config?.confirmFunction) {
    let func = mainRef.value.config.confirmFunction
    if (func && func.startsWith('function'))
      func = func.replace('function', 'async function')

    try {
      const result = await executeStrFunctionByContext(null, func, [])
      if (!result) {
        close()
        return
      }

      let messageType = 'success'

      if (result?.name) {
        const waitRefreshRef = getComponentByName(result.name)
        if (waitRefreshRef)
          waitRefreshRef.refresh()
        else
          console.warn(`未找到组件${result.name}无法刷新`)
      }

      if (result?.messageType)
        messageType = result.messageType

      if (result?.message) {
        showDialog({
          message: result.message,
        })
      }

      close()
    }
    catch (error) {
      console.error('确认逻辑执行失败:', error)
      close()
    }
  }
  else {
    console.warn('未配置modal确认按钮逻辑')
    close()
  }
}

function updateImg(data: any) {
}

// 暴露方法
defineExpose({
  init,
  getComponentByName,
})
</script>

<template>
  <VanDialog
    v-model:show="visible"
    :before-close="close"
    :confirm-loading="loading"
    width="80%"
    :show-confirm-button="true"
    confirm-text="提交"
    v-bind="attr"
    @confirm="onSubmit"
  >
    <div v-if="showReport" style="max-height: 70vh; overflow-y: auto; overflow-x: hidden;">
      <XReport
        ref="mainRef"
        :env="env"
        :use-oss-for-img="false"
        :config-name="configName"
        :show-img-in-cell="true"
        :display-only="displayOnly"
        :edit-mode="false"
        :show-save-button="false"
        :dont-format="true"
        @update-img="updateImg"
        @select-row="selectRow"
      />
    </div>
  </VanDialog>
</template>
