/**初始化请求地址参数 */
export const getInitParams = function(remoteUrl) {
  let _url = remoteUrl;
  if (typeof remoteUrl === "function") {
    _url = remoteUrl();
  }
  let _default = {
    url: "",
    method: "get",
  };
  if (!_url) return undefined;
  if (typeof _url === "string") {
    _default.url = _url;
    return _default;
  }
  if (typeof _url === "object") {
    return { ..._default, ..._url };
  }
};

import _default from './default';
const { cbPagersObj } = _default;

function errorMsg(msg) {
  let _v = this._v;

  this.$error({
    width: 600,
    content(h) {
      return h('div', { style: { maxHeight: '400px', overflow: 'auto' } }, [_v(msg)]);
    }
  });
}
async function processLargeArray(arr, asyncFunction) {
  const chunkedArray = chunkArray(arr, 20);

  for (let i = 0; i < chunkedArray.length; i++) {
      await asyncFunction(chunkedArray[i]);
  }
}

function chunkArray(arr, size) {
  const newArr = [];
  for (let i = 0; i < arr.length; i += size) {
    newArr.push(arr.slice(i, i + size));
  }
  return newArr;
}


// const myLargeArray = Array.from({ length: 1000000 }, (_, i) => i + 1);

// processLargeArray(myLargeArray, 100000, async (arr) => {
//   // 模拟异步处理
//   await new Promise((resolve) => setTimeout(resolve, 1));
//   return arr
// }).then((result) => {
//   console.log(result);
// });




export async function reload(baseParma = {}) {
  /** 初化数据 */

  let { remoteUrl, paramsPage, remoteParams, remoteData } = this;
  let pageNode = this.$refs.page;

  if (!remoteUrl) {
    return;
  }
  let _this = this;
  this.loadOver = false;

  let { params, data, url, pageSize, pageNum } = baseParma;
  if (pageSize && pageNum) {
    paramsPage.pageSize=pageSize
    paramsPage.pageNum=pageNum
  }

  let remoteUrlParams = getInitParams(remoteUrl);
  if (remoteUrlParams.method == 'post') {
    remoteUrlParams.data = { ...remoteUrlParams.data,...paramsPage };
  } else if(remoteUrlParams.method == 'get'){
    remoteUrlParams.params = { ...remoteUrlParams.params,...paramsPage };
  }

  if (url) {
    remoteUrlParams.url = url;
  }

  if (data) {
    remoteUrlParams.data = {...remoteUrlParams.data,...data};
  }
  if (params) {
    remoteUrlParams.params = {...remoteUrlParams.params,...params};
  }
  if (remoteData) {
    remoteUrlParams.data = { ...remoteUrlParams.data, ...remoteData };
  }
  if (remoteParams) {
    remoteUrlParams.params = { ...remoteUrlParams.params, ...remoteParams };
  }


  if (typeof _this.remoteBefore === 'function') {
    let callback = _this.remoteBefore(this, remoteUrlParams);
    if (callback) {
      remoteUrlParams = callback;
    } else if (callback === false) {
      return;
    }
  }
  if (!remoteUrlParams.url) {
    this.loadOver = true;
    return;
  }


 let node=document.createTextNode ('O') ;
 let ob = new MutationObserver((mutationsList, observer) => {
   this.loadOver = true;
   if (this.$listeners['update:loading']) {
    this.$emit('update:loading',false);
   } else {
    this.vLoading = false;
  }
   observer.disconnect();
   node = null
   ob=null
 });
  ob.observe(node, { characterData: true });

  if (this.$listeners['update:loading']) {
    this.$emit('update:loading',true);
   } else {
    this.vLoading = true;
  }
 if (this.$listeners['update:dataSource']) {
  this.$emit('update:dataSource', []);
 } else {
   this.tData = []
 }
if (this.$listeners['updata:selectedRowKeys']) {
    this.$emit('updata:selectedRowKeys', []);
}
if (this.$listeners['selectChange']) {
  this.$emit('selectChange', [],[]);
}

 return this.axios(remoteUrlParams).then((response) => {
     if (response.data && response.data.data) {
       response = response.data;
     }

     var _tData = [];
     if (typeof _this.doneBefore === 'function') {
       let _res = _this.doneBefore(response);
       if (_res) {
         response = _res;
       }
     }
     if (response.success) {
       if (Array.isArray(response.data)) {
         _this.tableChange = (pagination) => {
           _this.sPagination = pagination;
         };
         _tData = response.data;
         if (_this.sPagination) {
           _this.sPagination = {
             ..._this.sPagination,
          }
       //   _this.sPagination.total=_tData.length
         }
        // this.total = _tData.length
         _this.addCount(_tData);


       } else if (response.data && Array.isArray(response.data.list)) {
         _tData = response.data.list;
         if (response.data.totalCount) {
          cbPagersObj(_this.sPagination, response.data)

         }
       } else if (response.data == null) {
         _tData = [];
       }

       _this.addCount(_tData);

       if (typeof _this.done === 'function') {
         let _res=_this.done(_tData);
         if (_res) {
           _tData = _res
         }
       }

       this.setClosure && this.setClosure(_tData);
     } else {
       // _this.tData = []
//       this.$emit('update:dataSource', []);

       if (this.$exception) {
         this.$exception({
           code: response.code,
           message: response.message,
           data: response.data
         });
       } else if (response.message) {
         errorMsg.call(this, JSON.stringify(response.message));
       } else if (response.data) {
         errorMsg.call(this, JSON.stringify(response.data));
       }
       if (typeof _this.remoteError === 'function') {
         _this.remoteError(response.message);
       }
     }
     if (this.$listeners['update:dataSource']) {
      this.$emit('update:dataSource', _tData);
     } else {

       this.tData = Object.freeze(_tData)

     }


     node.data='1'
     return response
   })
   .catch((error) => {
     if (typeof _this.remoteError === 'function') {
       _this.remoteError(error);
     } else {
       console.error(error);
     }
   }).finally(() => {
  //   _this.vLoading = false;
     setTimeout(() => {
     //  _this.loadOver = true;
     }, _this.delayTime);
   })



  return
}

export default { reload };
