<template>
  <div>
    <component
      :is="componentName"
      v-if="componentName != null && componentName != '' && componentLoadedCount > 0"
      :key="componentName + '-' + componentLoadedCount" 
      ref="infoComponent" 
      :field-value="fieldValue" 
      :info-window="infoWindowDto"
      :where-clause-source="whereClauseSource" 
      :is-search-widget="isSearchWidget" 
      :parent-model-data="parentModelData"
      :model-data="modelData" 
      :multiple="multiple" 
      :window-no="infoWindowNo"
      @data-selected="dataSelected"
      @delete-selected="deleteSelected"
    />

    <Loading v-if="loading" />
  </div>
</template>
<script>
import { defineComponent } from 'vue';
import Common from '../../common/Common.js';
import Notify from '../../common/Notify.js';
import CssUtil from '../../common/CssUtil.js';
import QueryPage from './QueryPage.vue';
import Loading from '../../loading/src/Loading.vue';
import ClientOrganization from '../../client-organization/src/ClientOrganization.vue';

export default defineComponent({
  name: 'InfoWindow',

  components: {
    QueryPage,
    Loading,
    'ClientOrganization': ClientOrganization,
  },

  props: {
    'whereClauseSource': {
      type: Object,
      default(){
        return null;
      },
    },
    'isSearchWidget': {
      type: Boolean,
      default: false,
    },
    'parentModelData': {
      type: Object,
      default(){
        return null;
      },
    },
    'modelData': {
      type: Object,
      default(){
        return null;
      },
    },
    'fieldValue': {
      type: Object,
      default(){
        return null;
      },
    },
    /**
     * 查询窗口编号
     */
    'infoWindowNo': {
      type: String,
      default: null,
    },
    /**
     * 是否多选
     */
    'multiple': {
      type: Boolean,
      default: false,
    },
  },

  emits: ['dataSelected', 'valueChanged', 'deleteSelected'],

  data: function () {
    return {
      infoWindowDto: {},
      componentName: '',  // 显示部件名称
      loading: false,
      componentLoadedCount: 0, // 异步组件加载成功的数量
    };
  },

  watch: {

    'infoWindowNo': {
      handler: function (newValue, oldValue) {
        let _self = this;
        if (newValue != oldValue) {
          this.$nextTick(function () {
            _self.loadData();
          });
        }
      },
      immediate: true,
    },
  },

  mounted: function () {
  },

  methods: {
    /**
         * 加载数据
         */
    loadData: function () {
      if (this.infoWindowNo == null || this.infoWindowNo.length == 0) {
        return;
      }
      var _self = this;
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('InfoWindowResource/uniqueByNo'),
        type: 'GET',
        dataType: 'json',
        data: { 'infoWindowNo': _self.infoWindowNo },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          console.log(data);
          _self.infoWindowDto = data;

          // 计算显示的部件
          if (_self.infoWindowDto.componentName != undefined && _self.infoWindowDto.componentName != '') {
            _self.componentName = _self.infoWindowDto.componentName;
            _self.dynamicInit();
          } else if (_self.infoWindowDto.infoWindowType == undefined || _self.infoWindowDto.infoWindowType == 'TableGrid'
              || _self.infoWindowDto.infoWindowType == 'NONE') {
            _self.componentName = 'QueryPage';
          }

          if(_self.componentName === 'QueryPage' || _self.componentName === 'ClientOrganization'){
            _self.componentLoadedCount ++;
          }

          _self.$nextTick(function () {
            if (_self.infoWindowDto.componentName == undefined || _self.infoWindowDto.componentName == '') {
              if (_self.infoWindowDto.infoWindowType == undefined || _self.infoWindowDto.infoWindowType == 'TableGrid' || _self.infoWindowDto.infoWindowType == 'NONE') {
                _self.$refs.infoComponent.initWidget(data);
              } else {
                _self.$refs.infoComponent.initWidget(data);
              }
            }
          });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 动态初始化仪表盘
     */
    dynamicInit: function () {
      let _self = this;

      const componentName = _self.infoWindowDto.componentName;
      const cssUrl = _self.infoWindowDto.cssUrl;

      if(cssUrl != null && cssUrl != undefined){
        CssUtil.dynamicLoadCss(cssUrl, componentName);
      }

      const jsUrl = _self.infoWindowDto.jsUrl;
      if(jsUrl != null && jsUrl != undefined){

        let promise = new Promise((resolve, reject) => {
          import(/* webpackIgnore: true */ jsUrl).then(remoteComponent => {
            resolve(remoteComponent);
          }).catch(error => {
            reject(error);
          });
        });


        promise.then(remoteComponent => {
          console.log('remoteComponent：' + remoteComponent.default.name);
          if(componentName !== remoteComponent.default.name){
            let errorMessage = '数据字典-查询窗口自定义组件部件名称定义的是' + componentName + '，但是程序中name定义的是' + remoteComponent.default.name + '，两者必须相同。';
            console.error(errorMessage);
            Notify.error('查询窗口自定义组件定义错误', errorMessage, false);
          }
          window.app.component(componentName, remoteComponent.default);
          _self.componentLoadedCount ++;
        }, errorData => {
          console.error(errorData);
        });
      }
    },

    /**
         * 数据选择事件
         */
    dataSelected: function (data) {
      this.$emit('dataSelected', data);
    },

    valueChanged: function (fieldValue) {
      this.$emit('valueChanged', fieldValue);
    },

    /**
         * 数据删除事件
         */
    deleteSelected: function (data) {
      this.$emit('deleteSelected', data);
    },

    /**
         * 获取选择的数据
         */
    getSelectedModelDatas: function (data) {
      var _self = this;
      return _self.$refs.infoComponent.getSelectedModelDatas();
    },

    refresh: function () {
      var _self = this;
      if (_self.$refs.infoComponent != undefined) {
        if (_self.componentName == 'QueryPage') {
          _self.$refs.infoComponent.pageSearch();
        } else if (_self.componentName == 'ClientOrganization') {
          _self.$refs.infoComponent.refresh();
        }
      }
    },
  },
});

</script>