import { asyncCallNetworkApiGet, asyncDelay, buttonOnClick, jumpToBundle, onHomeworkFinish, getSpriteFrimeByUrl, callNetworkApiGet } from "../script/NJ_YouLeChang_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 });
  }

  orgId = 507;
  engineType = "universal";
  async onLoadEnd() {
    const middleLayer = cc.find('middleLayer');
    if (middleLayer) {
      this.orgId = middleLayer.getComponent('middleLayer').ORG_ID || 507;
      this.engineType = middleLayer.getComponent('middleLayer').type || "universal";
    }
    if (this.orgId != 507) {
      // 说明是数字版, 变换一下界面布局
      cc.find(`Canvas/bg_ground/bg_grass`).active = false;
      cc.find(`Canvas/bg_ground/bg_grass_lite`).active = true;

      if (this.engineType == 'aixuebao') {
        cc.find(`Canvas/userInfo/frame/BtnLogout/text`).getComponent(cc.Label).string = "退出APP";
      }
    }
    await this.initData();
    await this.initView();
    this.initListener();
  }

  classData: any;
  async initData() {
    const middleLayer = cc.find('middleLayer');
    if (!middleLayer) {
      cc.sys.localStorage.setItem('token', '"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywicGhvbmUiOiIxODUwMjEzOTQwNCIsInNpZ24iOiJhZjFlYmM4NC0zZDBhLTRiYjUtYWNmOC0yODc3N2VhZTQyNTkiLCJpYXQiOjE2NTMzMDEwNTEsImV4cCI6MTY1NTg5MzA1MX0.2qwCaMTADzRNlFuwuHeRUSTN5EVdR8zJjd0ynpkkm_0"');
    }

    const classDataStr = await asyncCallNetworkApiGet('/api/syllabus/v1/list', {
      orgid: this.orgId
    });
    const classData = JSON.parse(classDataStr);
    this.classData = classData.rows.map(row => {
      return {
        id: row.id,
        name: row.name
      };
    });
  }

  async initView() {
    const canvas = cc.find('Canvas');
    const sky = cc.find('Canvas/bg_sky');
    sky.scale = Math.max(
      (canvas.width / sky.width),
      ((canvas.height / 2) / sky.height)
    );

    const ground = cc.find('Canvas/bg_ground');
    const gsx = canvas.width / ground.width;
    const gsy = canvas.height / ground.height;
    ground.scale = Math.min(gsx, gsy);

    const grass = cc.find('Canvas/bg_ground/bg_grass');
    const box = grass.getBoundingBox();

    grass.scale = Math.min(
      1,
      canvas.width / (box.width * ground.scale),
      (canvas.height - 100) / ((box.height + 100) * ground.scale)
    );

    // 头像等基本信息
    const middleLayer = cc.find('middleLayer');
    if (!middleLayer) {
      return;
    }
    if (middleLayer.getComponent('middleLayer').isLogin == false) {
      // 游客
      cc.find("Canvas/avatar_border/nick_name").getComponent(cc.Label).string = "游客";
      this.initUserInfoView();
      return;
    } 
    const kidInfo = await middleLayer.getComponent('middleLayer').getUserInfo();
    cc.find("Canvas/avatar_border/nick_name").getComponent(cc.Label).string = kidInfo.nick_name || "拼读达人";
    const golds = await this.getGolds(kidInfo);
    cc.find('Canvas/avatar_border/goldBg/goldLabel').getComponent(cc.Label).string = golds+"";
    const avatarUrl = middleLayer.getComponent('middleLayer').getHeadUrl(kidInfo.avatar_url || kidInfo.id);
    getSpriteFrimeByUrl(avatarUrl, (spriteFrame) => {
      cc.find("Canvas/avatar_border/defaulte_avatar").getComponent(cc.Sprite).spriteFrame = spriteFrame;
    });

    this.initUserInfoView(kidInfo);
  }

  async getGolds(kidInfo) {
    if (!kidInfo || !kidInfo.id) {
      return 0;
    }
    const goldDataStr = await asyncCallNetworkApiGet(`/api/oxford/v1/kid/${kidInfo.id}/golds`, {
      token: cc.sys.localStorage.getItem('token')
    });
    if (goldDataStr) {
      return JSON.parse(goldDataStr).data;
    }
    return 0;
  }

  async initUserInfoView(kidInfo = null) {
    const middleLayer = cc.find('middleLayer');
    if (!middleLayer) {
      return;
    }
    const middleLayerComponent = middleLayer.getComponent('middleLayer');

    const goldNumber = cc.find('Canvas/userInfo/frame/goldBg/goldNumber');
    const nickname = cc.find('Canvas/userInfo/frame/nickname');
    if (middleLayerComponent.isLogin == false) {
      // 游客
      goldNumber.getComponent(cc.Label).string = "0";
      nickname.getComponent(cc.Label).string = "游客";
      return;
    }

    const golds = await this.getGolds(kidInfo);
    goldNumber.getComponent(cc.Label).string = golds+"";

    if (kidInfo.nick_name) {
      nickname.getComponent(cc.Label).string = kidInfo.nick_name;
    }

    if (kidInfo.avatar_url) { }
    const headUrl = middleLayerComponent.getHeadUrl(kidInfo.avatar_url || kidInfo.id);
    const headImg = cc.find('Canvas/userInfo/frame/mask/headImg');
    cc.assetManager.loadRemote(headUrl, (err, tex) => {
      headImg.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(tex);
    });
  }

  initListener() {
    const middleLayer = cc.find('middleLayer');
    if (!middleLayer) {
      return;
    }
    const middleLayerComponent = middleLayer.getComponent('middleLayer');
    buttonOnClick(cc.find('Canvas/bg_ground/bg_grass/btn_quwen'), () => {
      const data = this.classData.find(data => data.name == '趣问趣答');
      if(!data) {
        middleLayerComponent.showTips("没有创建‘趣问趣答’");
        return;
      }
      middleLayerComponent.setData('NJ_MoTianLun', data.id);
      jumpToBundle('NJ_MoTianLun');
    });
    buttonOnClick(cc.find('Canvas/bg_ground/bg_grass_lite/btn_quwen'), () => {
      const data = this.classData.find(data => data.name == '趣问趣答');
      if(!data) {
        middleLayerComponent.showTips("没有创建‘趣问趣答’");
        return;
      }
      middleLayerComponent.setData('NJ_MoTianLun', data.id);
      jumpToBundle('NJ_MoTianLun');
    });
    buttonOnClick(cc.find('Canvas/bg_ground/bg_grass/btn_familypindu'), () => {
      const data = this.classData.find(data => data.name == '家庭拼读');
      middleLayerComponent.showTips("精彩在路上~ 敬请期待！");
      console.log(data);
    });
    buttonOnClick(cc.find('Canvas/bg_ground/bg_grass/btn_yuedu'), () => {
      const data = this.classData.find(data => data.name == '阅读加油站');
      if(!data) {
        middleLayerComponent.showTips("没有创建‘阅读加油站’");
        return;
      }
      middleLayerComponent.setData('NJ_YueDuJiaYouZhan', data.id);
      jumpToBundle('NJ_YueDuJiaYouZhan');
    });
    buttonOnClick(cc.find('Canvas/bg_ground/bg_grass_lite/btn_yuedu'), () => {
      const data = this.classData.find(data => data.name == '阅读加油站');
      if(!data) {
        middleLayerComponent.showTips("没有创建‘阅读加油站’");
        return;
      }
      middleLayerComponent.setData('NJ_YueDuJiaYouZhan', data.id);
      jumpToBundle('NJ_YueDuJiaYouZhan');
    });

    buttonOnClick(cc.find('Canvas/bg_ground/bg_grass/btn_pindu'), () => {
      const data = this.classData.find(data => data.name == '拼读天地');
      if(!data) {
        middleLayerComponent.showTips("没有创建‘拼读天地’");
        return;
      }
      middleLayerComponent.setData('NJ_menu', data.id);
      jumpToBundle('NJ_menu');
    });
    buttonOnClick(cc.find('Canvas/bg_ground/bg_grass_lite/btn_pindu'), () => {
      const data = this.classData.find(data => data.name == '拼读天地');
      if(!data) {
        middleLayerComponent.showTips("没有创建‘拼读天地’");
        return;
      }
      middleLayerComponent.setData('NJ_menu', data.id);
      jumpToBundle('NJ_menu');
    });
    const btn_last = cc.find('Canvas/bg_ground/bg_bottom/btn_last');
    buttonOnClick(btn_last, async () => {
      if (middleLayerComponent.isLogin == false) {
        // 游客
        // 提示先登录后购买
        middleLayerComponent.showConfirm("需要登录后才能使用，去登录吗？", ()=>{
          middleLayerComponent.loadOnlineBundle('NJ_login');
        });
        return;
      }
      const kidInfo = await middleLayerComponent.getUserInfo();
      if (!kidInfo) {
        return;
      }
      if (!kidInfo.lastgameinfo) {
        middleLayerComponent.showTips("还未开始学习！");
        return;
      }
      const lastgameinfo = JSON.parse(kidInfo.lastgameinfo);
      middleLayerComponent.reSetData(lastgameinfo);
      const syllabusId = kidInfo.last_syllabus;
      const coursewareId = kidInfo.last_courseware;
      middleLayerComponent.loadOnlineCourseWare(syllabusId, false, coursewareId);
    });
    const btn_center = cc.find('Canvas/bg_ground/bg_bottom/btn_center');
    buttonOnClick(btn_center, async () => {
      jumpToBundle('NJ_usercenter');
    });

    const avatar_border = cc.find('Canvas/avatar_border');
    buttonOnClick(avatar_border, async () => {
      if (middleLayerComponent.isLogin == false) {
        return;
      }
      cc.find('Canvas/userInfo').active = true;
    }, 0.7);

    const BtnLogout = cc.find('Canvas/userInfo/frame/BtnLogout');
    buttonOnClick(BtnLogout, () => {
      middleLayerComponent.showConfirm("确定退出？", () => {
        if (this.engineType == 'aixuebao') {
          if (window && (<any>window).courseware && (<any>window).courseware.exitApp) {
            (<any>window).courseware.exitApp();
          }
        } else {
          cc.sys.localStorage.setItem('token', '');
          jumpToBundle('NJ_login');
        }
      });
    });

    const btnClose = cc.find('Canvas/userInfo/btnClose');
    buttonOnClick(btnClose, () => {
      cc.find('Canvas/userInfo').active = false;
    });


    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
      // 整个IF都是用于IOS过审
      cc.find(`Canvas/userInfo/deleteAccount`).active = true;
      buttonOnClick(cc.find('Canvas/userInfo/deleteAccount'), () => {
        middleLayerComponent.showConfirm("确定退出并删除账号？", () => {
          const phone = cc.sys.localStorage.getItem('phone');
          cc.sys.localStorage.setItem('phone', `${phone}_x`);
          cc.sys.localStorage.setItem('token', '');
          jumpToBundle('NJ_login');
        });
      });
    }
  }
}
