
/**
 * 接口轮询组件封装
 * 
 * import startRolling from '../../libs/spark_requstrolling.js';
 * 
 * async rollingTest() {
    await startRolling(async() => {
      return await API.getOrderStatusForThrough({});
    }, 5, 1000, "data.lottery.id", 7489, (data) => {
      console.log("success:", data);
    }, (err) => {
      console.log("error:", err);
    });
  }

  调用：this.rollingTest();
 * 
 * 
 * 
 * @param {*} fn  API请求方法
 * @param {*} count  轮询次数
 * @param {*} delay 每次轮询的延迟时间（毫秒）
 * @param {*} rollKey 断定轮询的条件 采用a.b.c.d结构，例如data.lottery.id
 * @param {*} rollValue  断定轮询的值
 * @param {*} resolve  成功回调
 * @param {*} reject  失败回调
 * @param {*} rollingIndex 起始次数，不用传，默认就好
 */

const startRolling = async (fn, count, delay, rollKey, rollValue, resolve, reject, rollingIndex = 1) => {
    if (typeof fn !== "function") {
        if(reject)reject()
        return;
    }
    console.log("开始轮询，当前轮询次数",rollingIndex)
    let result = await fn();
    console.log(result);
    if (result.success) {
        rollingIndex = 1;
        if (resolve) resolve(result);
    } else {
        if (rollKey) {
            let rollKeyArr = rollKey.split(".");
            let condition = result;
            rollKeyArr.map(res => condition = condition[res])
            if (condition == rollValue && rollingIndex < count) {
                setTimeout(() => {
                    startRolling(fn, count, delay, rollKey, rollValue, resolve, reject, ++rollingIndex);
                }, delay);
            } else {
                if (reject) reject(result);
            }

        } else {
            if (reject) reject(result);
        }
    }

}
export default startRolling;
