<template>
  <div>
    <template v-for="(item, index) in dashboardArray" :key="item.no">
      <component
        :is="item.componentName == undefined ? '' : item.componentName"
        :dashboard="item"
        @collapse="collapse($event)"
        @remove="remove(index)"
      />
    </template>
  </div>
</template>

<script>
import { defineComponent } from 'vue';

import Common from '../common/Common.js';
import { CssUtil,Notify } from 'pc-component-v3';
import JsUtil from '../common/JsUtil';

import { useRoleStateSingleton } from '../client/RoleState.js';


export default defineComponent({
  name: 'DashboardPage',

  components: {},
  data() {
    return {
      dashboardArray: [],
      moduleDtos: [],
      roleStateInstance: useRoleStateSingleton,
    };
  },

  watch: {
    'roleStateInstance.userRoleOrTemplate': function(newValue, oldVal){
      console.log(newValue);
      this.loadData();
    },
  },

  mounted: function () {
    // 仅在角色已初始化（非首次挂载）时才直接加载，
    // 首次挂载由 watch(roleStateInstance.userRoleOrTemplate) 驱动
    if (this.roleStateInstance.userRoleOrTemplate !== undefined) {
      this.loadData();
    }
  },

  beforeUnmount: function () {
    if (this.dashboardArray != null && this.dashboardArray.length > 0) {
      this.dashboardArray.forEach(item => {
        CssUtil.dynamicUnloadCss(item.componentName);
      });
    }
  },

  methods: {
    loadData() {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('dashboardResource/listDashBoard'),
        type: 'POST',
        data: _self.roleStateInstance.userRoleOrTemplate == null ? null : JSON.stringify(_self.roleStateInstance.userRoleOrTemplate),
        dataType: 'json',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if(data.errorCode == 0){
            _self.dynamicInit(data.datas);
          } else {
            Notify.error('仪表盘数据获取错误', data.errorMessage, false);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    collapse: function (params) {
      var contentElement = params[0];
      contentElement.slideToggle();
    },

    remove: function (index) {
      var _self = this;
      _self.dashboardArray.splice(index, 1);
    },

    /**
     * 动态初始化仪表盘
     */
    dynamicInit: function (dashboards) {
      let _self = this;
      _self.dashboardArray.splice(0, _self.dashboardArray.length);

      if (dashboards != null && dashboards.length > 0) {
        dashboards.forEach(function (item) {
          console.log(item);
          // const jsUrl = '' + '/DictionaryBase/Dashboard/BASE/2020080401.js';
          //const jsUrl = '/DictionaryAsset/Dashboard/EAM/20220309_095250.js';
          const componentName = item.componentName;
          const sortNo = (item.sortNo == null) ? 100 : item.sortNo;

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

          let jsUrl = null;
          if (item.jsUrl != null && item.jsUrl != undefined) {
            jsUrl = item.jsUrl;
            let promise = JsUtil.dynamicLoadJsModule(Common.getHostPageBaseURL() + jsUrl);
            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);
                var item1 = {
                  no: componentName,
                  componentName: componentName,
                  sortNo: sortNo,
                };

                // console.log(_self.dashboardArray);
                if(!_self.isExistDashboardComponent(item1)){
                  _self.dashboardArray.push(item1);
                  // add by jack 2024-05-22 增加排序
                  _self.dashboardArray.sort((a, b) => a.sortNo - b.sortNo);
                }
              },
              errorData => {
                console.error(errorData);
              },
            );
          }
        });
      }
    },

    /**
     * 是否是现有的看板项
     * @param dashboardItem 看板项
     */
    isExistDashboardComponent(dashboardItem){
      let _self = this;
      for(let i = 0; i < _self.dashboardArray.length; i ++){
        let dashboardItemExist = _self.dashboardArray[i];
        if(dashboardItemExist.no == dashboardItem.no){
          return true;
        }
      }
      return false;
    },
  },
});
</script>

<style scoped>
ul.dropdown-menu > li {
  padding-left: 1em;
}

ul.dropdown-menu > li:hover {
  background-color: gray;
  cursor: pointer;
  color: white;
}

div.dropdown {
  margin-bottom: 20px;
}
</style>