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;
  moreGameFolder: any;
  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_NongChang');
    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
      };
    });

    this.moreGameFolder = res.rows.find(item => item.name == 'more games');
  }

  orgId = 507;
  async onLoadEnd() {
    const middleLayer = cc.find('middleLayer');
    if (middleLayer) {
      this.orgId = middleLayer.getComponent('middleLayer').ORG_ID || 507;
    }
    if (this.orgId != 507) {
      // 数字版
      cc.find('Canvas/lxc').active = false;
    }

    await this.initData();
    await this.initView();
    this.initListener();
  }

  async initView() {
    const touchboard = cc.find('Canvas/touchboard');
    const contant = cc.find('Canvas/touchboard/contant');
    const scale = touchboard.height / contant.height;
    contant.width = 4400 * scale;
    contant.height = 720 * scale;
    contant.scale = scale;
    contant.x = contant.width / 2 - touchboard.width / 2;

    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.setSpriteColor(btn, cc.color(255, 255, 255));
        this.changeNodeColor(btn.getChildByName('icon'));
        this.changeNodeColor(btn.getChildByName('icon1'));
        this.changeNodeColor(btn.getChildByName('icon2'));
      } else {
        this.setSpriteColor(btn, cc.color(200, 200, 200));
        this.changeNodeGray(btn.getChildByName('icon'));
        this.changeNodeGray(btn.getChildByName('icon1'));
        this.changeNodeGray(btn.getChildByName('icon2'));
      }
    }
  }

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

  setSpriteColor(node, color) {
    node.color = cc.color(color.r, color.g, color.b);
    node.children.forEach(child => {
      if (child.getComponent(cc.Sprite)) {
        this.setSpriteColor(child, color);
      }
      if (child.getComponent(cc.RichText)) {
        this.setSpriteColor(child, color);
      }
    });
  }

  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);

        if (this.orgId == 507) {
          const guideRow = res.rows.find(row => row.name == '指读索引');
          if (!guideRow) {
            middleLayerComponent.showTips("未配置‘指读索引’");
            return;
          }
          middleLayerComponent.setData('NJ_game_select', {
            folderId: this.rows[i].id,
            folderName: this.rows[i].name,
            courseId: guideRow.id,
            nextFolderId: (this.rows[i + 1] && this.rows[i + 1].name != 'more games')?this.rows[i + 1].id:-1
          });
          jumpToCourseWare(guideRow.id);
        } else {
          if (res.rows.length == 0) {
            middleLayerComponent.showTips("未制作");
            return;
          }
          middleLayerComponent.setData('NJ_game_select', {
            folderId: this.rows[i].id,
            folderName: this.rows[i].name,
            courseId: res.rows[0].id,
            nextFolderId: (this.rows[i + 1] && this.rows[i + 1].name != 'more games')?this.rows[i + 1].id:-1
          });
          jumpToCourseWare(res.rows[0].id, true);
        }
      });
    }

    const btnGame = cc.find('Canvas/game');
    buttonOnClick(btnGame, () => {
      const middleLayer = cc.find('middleLayer');
      if (middleLayer) {
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        if (!this.moreGameFolder) {
          middleLayerComponent.showTips("未解锁 [101]");
          return;
        }
        middleLayerComponent.setData('NJ_MoreGames', {
          folderId: this.moreGameFolder.id,
          folderName: this.moreGameFolder.name,
          Level: "L3"
        });
        middleLayerComponent.loadOnlineBundle('NJ_MoreGames');
      }
    }, 0.6);

    const btnLxc = cc.find('Canvas/lxc');
    buttonOnClick(btnLxc, () => {
      const middleLayer = cc.find('middleLayer');
      if (middleLayer) {
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        middleLayerComponent.loadOnlineBundle('workbook_l3');
      }
    }, 0.6);

    const btnReturn = cc.find('Canvas/btn_return');
    buttonOnClick(btnReturn, () => {
      const middleLayer = cc.find('middleLayer');
      if (middleLayer) {
        middleLayer.getComponent('middleLayer').loadOnlineBundle('NJ_menu');
      }
    }, 0.6);
  }
}
