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

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
  addPreloadImage() {
    // this._imageResList.push({ url: this.data.pic_url });
  }

  rows;
  kidInfo;
  async initData() {
    const middleLayer = cc.find('middleLayer');
    if (!middleLayer) {
      this.rows = [
        { id: 1, locked: false, name: 1 },
        { id: 1, locked: false, name: 1 },
        { id: 1, locked: true, name: 1 },
      ];
      return;
    }

    const middleLayerComponent = middleLayer.getComponent('middleLayer');

    const userInfo = await middleLayerComponent.getUserInfo();
    if (!userInfo) {
      return;
    }

    console.log('userInfo = ' + JSON.stringify(userInfo));
    this.kidInfo = userInfo;

    const folderId = middleLayerComponent.getData('NJ_ShaMo');
    console.log('folderId = ' + folderId);

    const resStr = await asyncCallNetworkApiGet('/api/syllabus/v1/list', {
      pid: folderId
    });

    console.log('resStr = ' + resStr);

    const res = JSON.parse(resStr);
    this.rows = res.rows.map((row, idx) => {
      let locked = true;
      if (idx == 0) {
        locked = false;
      }
      if (userInfo.unlock_syllabuses?.includes(row.id)) {
        locked = false;
      }
      return {
        id: row.id,
        locked: locked,
        name: row.name
      };
    });
  }

  async onLoadEnd() {
    await this.initData();
    await this.initView();
    this.initListener();
  }

  async initView() {
    const bg = cc.find('Canvas/touchboard/contant/bg');
    for (let i = 0; i < 36; i++) {
      const btn = seekChildByName(bg, `btn_${i}`);
      const row = this.rows[i];
      if (row && !row.locked) {
        this.changeNodeColor(btn);
      } else {
        this.changeNodeGray(btn);
      }
    }
  }

  changeNodeGray(node) {
    const sprite: cc.Sprite = node.getComponent(cc.Sprite);
    if (sprite) {
      node.color = cc.color(200, 200, 200);
      //   let material = cc.Material.createWithBuiltin('2d-gray-sprite', 0);
      //   let variant1 = cc.MaterialVariant.create(material, sprite);
      //   sprite.setMaterial(0, variant1);
    }

    node.children.forEach(child => {
      this.changeNodeGray(child);
    });
  }
  changeNodeColor(node) {
    const sprite: cc.Sprite = node.getComponent(cc.Sprite);
    if (sprite) {
      node.color = cc.color(255, 255, 255);
      //   let material = cc.Material.createWithBuiltin('2d-sprite', 0);
      //   let variant1 = cc.MaterialVariant.create(material, sprite);
      //   sprite.setMaterial(0, variant1);
    }

    node.children.forEach(child => {
      this.changeNodeColor(child);
    });
  }

  initListener() {
    const bg = cc.find('Canvas/touchboard/contant/bg');
    for (let i = 0; i < 36; i++) {
      const btn = seekChildByName(bg, `btn_${i}`);
      const row = this.rows[i];
      buttonOnClick(btn, async () => {
        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
          return;
        }
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        if (!row) {
          middleLayerComponent.showTips("未解锁 [101]");
          return;
        }
        if (row.locked) {
          middleLayerComponent.showTips("未解锁");
          return;
        }
        if (i == 0) {
          // 如果是第一个文件夹，则上报一个解锁
          await asyncCallNetworkApiPost('/api/oxford/v1/kid/unlock', {
            kidid: this.kidInfo.id,
            syllabusid: row.id,
            token: cc.sys.localStorage.getItem('token')
          });
        }

        const resStr = await asyncCallNetworkApiGet('/api/syllabus/v1/list', {
          pid: this.rows[i].id
        });

        const res = JSON.parse(resStr);
        const guideRow = res.rows.find(row => row.name == '指读索引');
        if (!guideRow) {
          middleLayerComponent.showTips("未配置‘指读索引’");
          return;
        }
        middleLayerComponent.setData('NJ_game_select', {
          folderId: this.rows[i].id,
          courseId: guideRow.id,
          nextForderId: this.rows[i + 1]?.id
        });
        jumpToCourseWare(guideRow.id);
      });
    }
  }
}
