<template>
  <a-drawer
    :destroyOnClose="true"
    :visible="visible"
    placement="right"
    width="85vw"
    @close="visible=false"
    v-bind="attr">
    <x-report
      @updateImg="updateImg"
      @selectRow="selectRow"
      ref="main"
      :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"/>
  </a-drawer>
</template>
<script>
import { mapState } from 'vuex'
import { executeStrFunctionByContext } from '@vue2-client/utils/runEvalFunction'
import { runLogic } from '@vue2-client/services/api/common'
import { getMicroData, getWindow, isMicroAppEnv, microDispatch } from '@vue2-client/utils/microAppUtils'
import { getRealKeyData } from '@vue2-client/utils/util'

export default {
  name: 'XReportDrawer',
  components: {
    XReport: () => import('@vue2-client/base-client/components/common/XReportGrid/XReport.vue'),
  },
  props: {
    env: {
      type: String,
      default: 'prod'
    }
  },
  data () {
    return {
      // 业务类型
      businessType: '',
      configName: '',
      displayOnly: true,
      serverName: '',
      // 业务标题
      title: '',
      // 自定义标题
      resolvedTitle: '',
      // 新增或修改业务是否执行中
      loading: false,
      // 是否显示新增/修改模态框
      visible: false,
      // 选中的处理对象的id号
      selectedId: null,
      // 混入插槽组件的数据
      mixinData: {},
      // 打开窗口接收到的外部环境数据
      outEnv: {},
      // 外部传递来的 modal 参数
      attr: {},
    }
  },
  provide () {
    return {
      getSelectedId: () => this.getSelectedId(),
      getSelectedData: () => {
        return this.selectedId
      },
      getMixinData: () => {
        return this.mixinData
      },
      getOutEnv: () => {
        return this.outEnv
      },
      isInAModal: () => {
        return true
      },
      currUser: this.currUser
    }
  },
  inject: ['getParentComponentByName', 'setGlobalData', 'getGlobalData'],
  computed: {
    businessTitle () {
      return this.businessType + this.title
    },
    ...mapState('account', { currUser: 'user' })
  },
  methods: {
    getWindow,
    isMicroAppEnv,
    microDispatch,
    getMicroData,
    getRealKeyData,
    runLogic,
    init (params) {
      console.log('params', params)
      const {
        configName = '',
        serverName = process.env.VUE_APP_SYSTEM_NAME,
        displayOnly = true,
        selectedId = null,
        outEnv = {},
        mixinData = {},
        attr = {}
      } = params
      this.configName = configName
      this.serverName = serverName
      this.displayOnly = displayOnly
      this.visible = true
      this.attr = attr
      // 有选中项，给选中项赋值
      if (selectedId) {
        this.selectedId = selectedId
      }
      // 当有些组件需要外部传数据时 使用这个混入
      this.mixinData = mixinData
      // 把打开时的环境传递给打开窗口，以便js脚本中使用
      this.outEnv = outEnv
    },
    getSelectedId () {
      if (typeof this.selectedId === 'object') {
        if (this.selectedId.selectedId) {
          return this.selectedId.selectedId
        }
        if (Object.keys(this.selectedId) > 0) {
          return this.selectedId[Object.keys(this.selectedId)[0]]
        }
      } else {
        return this.selectedId
      }
    },
    selectRow (selectedRowKeys, selectedRows) {
      this.table_selectedRowKeys = selectedRowKeys
      this.table_selectedRows = selectedRows
      console.log('XAddReport')
      this.$emit('selectRow', selectedRowKeys, selectedRows)
    },
    close () {
      this.loading = false
      this.visible = false
      this.$emit('close')
    },
    getComponentByName (name) {
      const innerRef = this.getParentComponentByName(name)
      if (innerRef) {
        return innerRef
      } else {
        return this.$refs.main.getComponentByName(name)
      }
    },
    async onSubmit () {
      if (this.$refs.main?.config?.confirmFunction) {
        console.info('执行自定义确认逻辑')
        let func = this.$refs.main?.config?.confirmFunction
        if (func && func.startsWith('function')) {
          func = func.replace('function', 'async function')
        }
        const result = executeStrFunctionByContext(this, func, [])
        if (result instanceof Promise) {
          result.then((res) => {
            if (!res) {
              this.close()
              return
            }
            let messageType = 'success'
            // 如果传递了组件名字 自动调用刷新
            if (res?.name) {
              const waitRefreshRef = this.getComponentByName(res.name)
              if (waitRefreshRef) {
                waitRefreshRef.refresh()
              } else {
                console.warn(`未找到组件${res.name}无法刷新`)
              }
            }
            // 如果传递消息类型 自动调用消息
            if (res?.messageType) {
              messageType = res.messageType
            }
            // 如果传递了提示信息自动调用提示
            if (res?.message) {
              this.$message[messageType](res?.message)
            }
            this.close()
          })
        } else {
          this.close()
        }
      } else {
        console.warn('未配置modal确认按钮逻辑')
        this.close()
      }
    },
    updateImg (data) {
      console.log(data)
    }
  }
}
</script>
