import { asyncCallNetworkApiGet, asyncCallNetworkApiPost, asyncDelay, buttonOnClick, onHomeworkFinish, jumpToBundle } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

  @property(cc.AudioClip)
  bgMusic1: cc.AudioClip = null;
  @property(cc.AudioClip)
  monkyBegin: cc.AudioClip = null;
  @property(cc.AudioClip)
  monkyWait: cc.AudioClip = null;

  addPreloadImage() {
    // this._imageResList.push({ url: this.data.pic_url });
  }

  async getKidInfo() {
    const kidDataStr = await asyncCallNetworkApiGet('/api/oxford/v1/kid/info', {
      token: cc.sys.localStorage.getItem('token')
    });
    if(kidDataStr){
      return JSON.parse(kidDataStr).data;
    }
    return null;
  }

  showTips(tips) {
    const middleLayer = cc.find('middleLayer');
    if (!middleLayer) {
      console.log(tips);
      return;
    }
    middleLayer.getComponent('middleLayer').showTips(tips);
  }

  playId = null;

  async onLoadEnd() {

    const middleLayer = cc.find('middleLayer');
    if (!middleLayer) {
      cc.sys.localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NCwicGhvbmUiOiIxNTUwMDAwMDAwMSIsInNpZ24iOiI0OTliYjg5Yy1lYjI5LTQ2M2EtYjk5ZS0zNDg2NDUwMGEyOTkiLCJpYXQiOjE2NTQ2NzY4MzMsImV4cCI6MTY1NzI2ODgzM30.MacCd_XUhvpNrMukYu8YNRVSbc-hju_WBN_FeiRACuc');
    }

    const kidDataStr = await asyncCallNetworkApiGet('/api/oxford/v1/kid/info', {
      token: cc.sys.localStorage.getItem('token')
    });
    const kidData = JSON.parse(kidDataStr);
    if(!kidData.data || !kidData.data.id) {
      this.showTips("用户登录失效，请重新登录");
      jumpToBundle("NJ_login");
      return;
    }

    this.initListener();

    // 播放背景音乐
    cc.audioEngine.stopMusic();
    cc.audioEngine.playMusic(this.bgMusic1, true);
    cc.audioEngine.setMusicVolume(0.3);

    this.playId = cc.audioEngine.play(this.monkyBegin, null, 1);
    cc.audioEngine.setFinishCallback(this.playId, () => {
      cc.audioEngine.setMusicVolume(1);
    })

    if(!middleLayer) {
      return;
    }
    const pid = middleLayer.getComponent('middleLayer').getData('NJ_MoTianLun');
    const classDataStr = await asyncCallNetworkApiGet('/api/syllabus/v1/list', {
      pid: pid
    });
    const classData = JSON.parse(classDataStr);

    const ballData = classData.rows.map((row, idx) => {
      let locked = true;
      if (kidData.data.unlock_syllabuses?.includes(row.id)) {
        locked = false;
      }
      return { id: row.id, locked: locked };
    });

    for (let i=0;i<5;i++) {
      const idx = i;
      const data = ballData[i];
      const star = cc.find(`Canvas/bg/bg_circle/star_${idx}`);
      const lock = cc.find(`Canvas/bg/bg_circle/star_${idx}/lock`);
      if (data) {
        if (data.locked) {
          lock.active = true;
        } else {
          lock.active = false;
        }
        buttonOnClick(star, async () => {
          const kidInfo = await this.getKidInfo();
          const activeLevels = kidInfo?kidInfo.active_levels:[];
          const activeItem = activeLevels.find(item => item.syllabus_id == data.id);
          if (middleLayer && !activeItem ) {
            // 弹出激活码
            middleLayer.getComponent('middleLayer').showActiveWindow();
            return;
          }
  
  
          if (!data.locked) {
            console.log('jump to id: ' + data.id);
            if (middleLayer) {
              const middleLayerComponent = middleLayer.getComponent('middleLayer');
              middleLayerComponent.setData('NJ_MonkyTree', data.id);
              middleLayerComponent.setData('nextLevelId', ballData[idx+1]?ballData[idx+1].id: null);
              middleLayerComponent.loadOnlineBundle('NJ_MonkyTree');
            }
          } else {
            this.showTips("未解锁");
          }
        });
      } else {
        lock.active = true;
        buttonOnClick(star, async () => {
          this.showTips("精彩在路上~ 敬请期待！");
        });
      }
    }
  
  }

  initListener() {
    const btnReturn = cc.find('Canvas/bg/btn_return');
    buttonOnClick(btnReturn, () => {
      jumpToBundle('NJ_YouLeChang');
    });

    const btnMonkey = cc.find('Canvas/bg/bg_monkey');
    buttonOnClick(btnMonkey, () => {
      if (this.playId) {
        cc.audioEngine.stop(this.playId);
      }
      cc.audioEngine.setMusicVolume(0.3);
      this.playId = cc.audioEngine.play(this.monkyWait, null, 1);
      cc.audioEngine.setFinishCallback(this.playId, () => {
        cc.audioEngine.setMusicVolume(1);
      })
    });
  }

  protected update(dt: number): void {
  }
}
