/**
 *
 * @authors Eric Hsiao
 *
 */

var popAniRoot;

main = function () {

  //private menbers
  var introAniRoot;
  var gameAniRoot;

  var isDrawing = false;
  var isStore = false;
  var drawCount;
  var myScore = 0;

  var currentScore = 0;
  var currentCheckinGp = 0;

  var scoreList = [66, 1, 3, 6, 8, 0, 9, 0];
  var dailyList = [1, 1, 1, 2, 2, 2, 3];
  var currentDaily = 0;
  var checkins = [];

  var userInfo;
  var LINEID;
  var name;

  var liffInitComplete = false;

  var testLINEID = 'Ud2534d6e1eed9cee2c919a993443352b';
  var testName = 'noh';

  var isComplete = false;
  var isLogin = false;
  var isCheck = false;
  var isCoupon = false;
  var errorMsg = '';

  var isAllSoldout = false;

  var popoutClickHandle = function () { };

  //private methods
  function init() {

    if (getParameterByName('test') == 1) {
      var vConsole = new VConsole();
    }

    console.log('main is loaded. v1005');

    initLiff();

    TweenMax.to('.page__overlayer', 0.3, { delay: 1.2, autoAlpha: 0 })

    var _myAnimate = new createAnimate();
    _myAnimate.load($('.intro__content'), 'intro',
      function (_exportRoot) {
        introAniRoot = _exportRoot;
        setTimeout(function () {
          introAniRoot.play();
        }, 500);
      });

    var image = new Image();
    image.onload = function () {
      // ... 在圖片載入後要進行的操作 ...
      console.log('gameAni image onload.');
      _myAnimate.load($('.main__game'), 'gameAni',
        function (_exportRoot) {
          gameAniRoot = _exportRoot;

          setTimeout(function () {
            introAniRoot.isComplete = true;
          }, 500);
          gameAniRoot.stop();
          initGame();
        });
    }

    image.src = 'images/gameAni/gameAni_atlas_1.png';


    $('.main__pop').hide();

    _myAnimate.load($('.main__pop'), 'popAni',
      function (_exportRoot) {
        popAniRoot = _exportRoot;
        popAniRoot.stop();

        //修正字體
        popAniRoot.get_btn.score_txt.textBaseline = "alphabetic";
        popAniRoot.get_btn.score_txt.y = 77;
        popAniRoot.content_mc.a_icon.content_txt.textBaseline = "alphabetic";
        popAniRoot.content_mc.b_icon.content_txt.textBaseline = "alphabetic";
        popAniRoot.content_mc.a_icon.content_txt.y = 80;
        popAniRoot.content_mc.b_icon.content_txt.y = 80;
      });

    $('.game__popout__close').click(function (e) {
      e.preventDefault();
      TweenMax.to('.game__popout', 0.3, { autoAlpha: 0 });
    });

    $('.game__popout__submit').click(function (e) {
      e.preventDefault();
      popoutClickHandle();
    });

    onResize();
    $(window).resize(function () {
      onResize();
    });
  }

  function initLiff() {
    console.log('liff.init');

    liff.init({
      liffId: URL__LIFF__ID //test
    })
      .then(() => {
        if (!liff.isLoggedIn()) {// 如果沒有登入LINE，就登入
          liff.login();
        }
      })
      .catch((err) => {
        // Error happens during initialization
        console.log(err.code, err.message);
        showError('LINE系統連線錯誤：<br>' + err.message);
      });
  }

  function onResize() {
    var _h = $(window).height();
    var _d = $(window).height() / 1138;
    if (_d > 1) _d = 1;
    TweenMax.set('.game__fixed', { scale: _d });
  }

  function gameInto() {
    // initLiff();

    // console.log('initLiff');
    liff.getProfile().then(function (e) {
      LINEID = e.userId;
      name = e.displayName;

      // if (getParameterByName('test') == 1) {
      //   LINEID = testLINEID;
      //   name = testName;
      // }

      console.log("LINEID : " + LINEID + ' , name : ' + name);
      updateUserData();
    });
  }

  function initGame() {

    gameAniRoot.luckydraw_mc.mainCTA_mc.addEventListener("click", handleCTAClick);
    function handleCTAClick(event) {
      if (isAllSoldout) {
        showError('<span style="font-size:0.8em">本次活動已結束<br>敬請期待下次遊戲。</span>');
      } else if (isComplete) {
        // showError('今天已經轉過，歡迎明天再來！');
        // showError('<span style="font-size:0.8em">今天已經轉過，<br>歡迎明天再來！<br>別忘了振興五倍券，<br>綁台灣Pay超優惠~</span>');
        showError('<span style="font-size:0.8em">活動已結束，<br>獎品兌換期限至12/6。<br>敬請期待下次活動！</span>');
      } else {
        if (!isDrawing) {
          isDrawing = true;
          //set drawCount
          //按下按鈕即開始轉動
          // gameAniRoot.luckydraw_mc.mainSpin_mc.gotoAndPlay('rolling');
          gameAniRoot.luckydraw_mc.mainCTA_mc.gotoAndPlay('rolling');
          gameAniRoot.luckydraw_mc.mainARR_mc.gotoAndPlay('rolling');
          gameAniRoot.luckydraw_mc.mainEffect_mc.flag_mc.gotoAndPlay('rolling');

          //讀取結果
          getGameGp(function (_res) {
            //顯示結果
            luckydrawStart();
          });
        }
      }
    }

    popAniRoot.addEventListener("click", handleGetClick);

    function handleGetClick(event) {
      $('.main__pop').hide();
      $('.main__pop__overlayer').hide();

      popAniRoot.gotoAndStop(0);
      // gameAniRoot.luckydraw_mc.mainCTA_mc.gotoAndPlay('stand');

      //更新分數
      // addScore(currentScore);
      updateScore();

      //取得Server data
      updateUserData();

      gameAniRoot.luckydraw_mc.store_mc.gotoAndPlay('complete');
      //更新打卡
      for (let index = 0; index < checkins.length; index++) {
        gameAniRoot.luckydraw_mc.dalylogin_mc['checkin_mc_' + index].alpha = 1;
      }
      // gameAniRoot.luckydraw_mc.dalylogin_mc['checkin_mc_' + (currentDaily - 1)].alpha = 1;
    }

    gameAniRoot.luckydraw_mc.store_mc.addEventListener("click", handleStoreClick);
    function handleStoreClick(event) {
      if (!isDrawing && !isStore) {
        isStore = true;
        gameAniRoot.luckydraw_mc.gotoAndPlay('storeInto');

        //每次進商店前就更新
        updateUserData();
      }
    }

    gameAniRoot.luckydraw_mc.storeClose_btn.addEventListener("click", handleStoreCloseClick);
    function handleStoreCloseClick(event) {
      gameAniRoot.luckydraw_mc.gotoAndPlay('storeClose');
      $('.game__store').hide();
    }
  }

  function updateGameContent() {
    //更新打卡
    console.log('========== updateGameContent ========');

    for (let index = 0; index < checkins.length; index++) {
      console.log('index = ' + index);
      gameAniRoot.luckydraw_mc.dalylogin_mc['checkin_mc_' + index].alpha = 1;

      //更新轉盤狀態
      if (userInfo.roundinfo.today == checkins[index].date) {
        isCheck = true;
        console.log('今日已簽到');
      }
    }

    //更新商店按鈕
    if (myScore > 0) {
      gameAniRoot.luckydraw_mc.store_mc.gotoAndPlay('complete');
    }

    //皆無庫存
    var selloutCount = 0;

    for (let index = 0; index < userInfo.goodinfo.length; index++) {
      if (userInfo.goodinfo[index].issoldout) {
        selloutCount++;
        console.log('selloutCount = ' + selloutCount);

        if (selloutCount >= userInfo.goodinfo.length) {
          showError('<span style="font-size:0.8em">本次活動已結束<br>敬請期待下次遊戲。</span>');
          isAllSoldout = true;
        }
      }
    }

    /*if (selloutCount >= userInfo.goodinfo.length) {
      $('.game__popout__content .content').hide();
      $('.game__popout__submit').hide();
      $('.game__popout__content .content__result').show();
      $('.game__popout__content .content__result__text').html('<p>活動已結束<br>感謝您的參與!​</p>');
      showPopout();
    }*/

    //更新Coupon
    updateCoupon();
  }

  function updateLogin() {
    if (isLogin) {
      setTimeout(function () {
        gameAniRoot.play();
        introAniRoot.gotoAndPlay('intoGame');
      }, 1000);

      //初始化分數
      setTimeout(function () {
        updateScore();
        updateGameContent();
      }, 2500);

      setTimeout(function () {
        // showError('<span style="font-size:0.8em">轉盤內優惠公告訊息，<br>為台灣Pay振興五倍券專屬優惠，<br>詳情洽台灣Pay官方網站。</span>');
        showError('<span style="font-size:0.8em">活動已結束，<br>獎品兌換期限至12/6。<br>敬請期待下次活動！</span>');
      }, 2800);

    } else {

      if (errorMsg == '請先加入 LINE 好友') {
        setTimeout(function () {
          alert('請先完成註冊，再重新進入遊戲');

          liff.openWindow({
            url: URL__REGISTER,
            external: false
          });

        }, 300);
      } else {
        showError('系統訊息：<br>' + errorMsg);

        $('.game__popout__close').click(function (e) {
          liff.closeWindow();
        });
      }
    }
  }

  function updateUserData() {

    console.log('================== updateUserData ===================');

    $.ajax({
      type: "GET",
      url: API__DOMAIN + "api2021/info/" + LINEID,
      data: {
        // LINEID: LINEID
      },
      dataType: "json",
      success: function (response) {

        if (response.succ) {
          userInfo = response.info;
          checkins = userInfo.roundinfo.checkins;
          myScore = userInfo.playerinfo.gp;

          ////////////////////////////////////////////////////////////////////
          //渲染coupon前
          //調整顯示邏輯 只允許 LP = 1、2、3、5

          var _blankGoodinfo = [
            { "id": 0, "lp": 1, "gp": 10, "issoldout": true, "isredeemed": false, "isnomoney": false, "canuse": false, "fromAPI": false },
            { "id": 0, "lp": 2, "gp": 20, "issoldout": true, "isredeemed": false, "isnomoney": false, "canuse": false, "fromAPI": false },
            { "id": 0, "lp": 3, "gp": 30, "issoldout": true, "isredeemed": false, "isnomoney": false, "canuse": false, "fromAPI": false },
            { "id": 0, "lp": 5, "gp": 50, "issoldout": true, "isredeemed": false, "isnomoney": false, "canuse": false, "fromAPI": false }
          ];

          for (let index = 0; index < userInfo.goodinfo.length; index++) {
            var _goodinfoData = userInfo.goodinfo[index];

            //檢查是否有coupon被API隱藏
            for (let blankIndex = 0; blankIndex < _blankGoodinfo.length; blankIndex++) {
              if (_goodinfoData.lp == _blankGoodinfo[blankIndex].lp) {
                //將blankGoodinfo替換為符合條件的userInfo.goodinfo
                //加入fromAPI屬性
                _goodinfoData.fromAPI = true;
                _blankGoodinfo[blankIndex] = _goodinfoData;
              }
            }
          }

          //覆寫 userInfo.goodinfo
          userInfo.goodinfo = _blankGoodinfo;
          console.log('========= Set userInfo.goodinfo ===========');
          console.log(userInfo.goodinfo);

          /////////////////////////////////////////////////////////////////////

          if (!isLogin) {
            isLogin = true;
            updateLogin();
          } else {
            // if (!isCoupon) initCoupon();
            updateGameContent();
          }

          if (!isCoupon) initCoupon();
          console.log(userInfo);

        } else {
          /*if (response.err == '請先加入 LINE 好友') {
            isLogin = false;
          } else {
            showError(response.err);
          }*/
          isLogin = false;
          errorMsg = response.err;
          updateLogin();
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log("Status: " + textStatus + ", Error: " + errorThrown);
        showError('使用者資料連線錯誤：<br>' + "Status: " + textStatus + ", Error: " + errorThrown);
        TweenMax.to('.loading', 0.3, { autoAlpha: 0 });
      }
    });
  }

  function getGameGp(_callback) {

    // drawCount = Math.floor(Math.random() * 8);
    // _callback();

    $.ajax({
      type: "POST",
      url: API__DOMAIN + "api2021/game/" + LINEID,
      data: {
        name: name
      },
      dataType: "json",
      success: function (response) {
        console.log('================== response ===================');
        console.log(response);

        if (response.succ) {
          currentScore = response.currentGameGp;
          currentCheckinGp = response.currentCheckinGp;
          myScore = response.gpAll;

          console.log('本次轉盤點數為 : ' + response.currentGameGp);
          console.log('本次簽到點數為 : ' + response.currentCheckinGp);

          if (response.currentGameGp == -1) isComplete = false;

          switch (currentScore) {
            case 66:
              drawCount = 0;
              break;
            case 1:
              drawCount = 1;
              break;
            case 3:
              drawCount = 2;
              break;
            case 6:
              drawCount = 3;
              break;
            case 8:
              drawCount = 4;
              break;
            case 0:
              drawCount = 5;
              break;
            case 9:
              drawCount = 6;
              break;
            case -1:
              drawCount = 7;
              break;
          }

          _callback();
        } else {
          // showError('<span style="font-size:0.8em">今天已經轉過，<br>歡迎明天再來！<br>別忘了振興五倍券，<br>綁台灣Pay超優惠~</span>');
          showError('<span style="font-size:0.8em">活動已結束，<br>獎品兌換期限至12/6。<br>敬請期待下次活動！</span>');
          isDrawing = false;

          gameAniRoot.luckydraw_mc.mainSpin_mc.gotoAndPlay('stand');
          // gameAniRoot.luckydraw_mc.mainCTA_mc.gotoAndPlay('stand');
          gameAniRoot.luckydraw_mc.mainARR_mc.gotoAndPlay('stand');
          gameAniRoot.luckydraw_mc.mainEffect_mc.flag_mc.gotoAndPlay('stand');
          isComplete = true;
        }

      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log("Status: " + textStatus + ", Error: " + errorThrown);
        // alert('很抱歉，資料讀取錯誤 請稍後再試。');
        showError('資料庫連線錯誤：<br>' + "Status: " + textStatus + ", Error: " + errorThrown);
        TweenMax.to('.loading', 0.3, { autoAlpha: 0 });
      }
    });
  }

  function luckydrawStart() {
    console.log('drawCount = ' + drawCount);
    isDrawing = true;
    // gameAniRoot.luckydraw_mc.mainSpin_mc.gotoAndPlay('rolling');
    // gameAniRoot.luckydraw_mc.mainCTA_mc.gotoAndPlay('rolling');
    // gameAniRoot.luckydraw_mc.mainARR_mc.gotoAndPlay('rolling');
    // gameAniRoot.luckydraw_mc.mainEffect_mc.flag_mc.gotoAndPlay('rolling');

    gameAniRoot.luckydraw_mc.mainSpin_mc.gotoAndPlay('rolling');
    gameAniRoot.luckydraw_mc.mainSpin_mc.wheel_mc.isComplete = false;

    setTimeout(function () {
      gameAniRoot.luckydraw_mc.mainSpin_mc.wheel_mc.setComplete(drawCount);
    }, 500);

    // gameAniRoot.luckydraw_mc.mainSpin_mc.wheel_mc.setComplete(drawCount);
  }

  function luckydrawComplete() {
    // isComplete = true;
    gameAniRoot.luckydraw_mc.mainTitle_mc.gotoAndPlay('complete');
    gameAniRoot.luckydraw_mc.mainSpin_mc.gotoAndPlay('complete');
    gameAniRoot.luckydraw_mc.mainARR_mc.gotoAndPlay('complete');
    gameAniRoot.luckydraw_mc.mainEffect_mc.flag_mc.gotoAndPlay('complete');

    gameAniRoot.luckydraw_mc.mainCTA_mc.gotoAndPlay('complete');

    if (drawCount == 7) {
      //再轉一次

      setTimeout(function () {
        // luckydrawStart();


        setTimeout(function () {
          isComplete = false;
          isDrawing = false;
          gameAniRoot.luckydraw_mc.mainCTA_mc.gotoAndPlay('stand');
        }, 1000);

        if (currentCheckinGp !== 0) {
          $('.main__pop').show();
          $('.main__pop__overlayer').show();
          popAniRoot.gotoAndPlay('into');

          console.log('再轉一次');

          popAniRoot.content_mc.a_icon.content_txt.text = 0;
          popAniRoot.content_mc.b_icon.content_txt.text = currentCheckinGp;

          // currentDaily++;
          if (!isCheck) {
            isCheck = true;
            gameAniRoot.luckydraw_mc.dalylogin_mc['checkin_mc_' + checkins.length].alpha = 1;
          }
          popAniRoot.get_btn.score_txt.text = currentCheckinGp;
        }
      }, 300);

    } else {
      isDrawing = false;
      $('.main__pop').show();
      $('.main__pop__overlayer').show();
      popAniRoot.gotoAndPlay('into');
      popAniRoot.content_mc.a_icon.content_txt.text = currentScore;
      popAniRoot.content_mc.b_icon.content_txt.text = currentCheckinGp;

      currentScore += currentCheckinGp;
      // currentDaily++;
      if (!isCheck) {
        isCheck = true;
        gameAniRoot.luckydraw_mc.dalylogin_mc['checkin_mc_' + checkins.length].alpha = 1;
      }


      popAniRoot.get_btn.score_txt.text = currentScore;
      isComplete = true;
    }
  }

  function addScore(_number) {
    myScore += _number;
    updateScore();
  }

  function updateScore() {
    $('.game__myScore').text(myScore);
  }

  function storeIntoComplete() {
    // $('.game__store').show();
    $('.game__store').show();

    //init loadStore
    TweenMax.set('.game__store', { autoAlpha: 0 });
    TweenMax.to('.game__store', 0.3, { autoAlpha: 1 });
  }

  function initCoupon() {
    isCoupon = true;

    $('.video__close').click(function (e) {
      e.preventDefault();
      TweenMax.to('.video__popout', 0.3, { autoAlpha: 0 });
      // $('.video__content').html('');
      player.stopVideo();
    });

    //updateCoupon
    updateCoupon();
  }



  function updateCoupon() {

    console.log('============== updateCoupon ==============');

    // console.log(userInfo.goodinfo);
    $('.game__store__coupon').html('');

    if (userInfo.goodinfo == '') {
      console.log('goodinfo 初始狀態');
    }

    var _soldout = 0;

    //////////////////////////////////////////////////////////////////////
    //渲染coupon

    for (let index = 0; index < userInfo.goodinfo.length; index++) {
      var _coupon;
      if (userInfo.goodinfo[index].lp < 5) {
        _coupon = new couponItem(index, userInfo.goodinfo[index]);
      } else {
        var _isLock;
        if ($.cookie('luckydraw.isVideoUnlock')) {
          _isLock = false;
        } else {
          _isLock = true;
        }

        console.log('luckydraw.isVideoUnlock = ' + $.cookie('luckydraw.isVideoUnlock'));

        //YOUTUBE LINK
        _coupon = new couponItem(index, $.extend(userInfo.goodinfo[index], { lock: _isLock, video: 'mDD48KKCqYw' }));
      }
    }
  }

  function showPopout() {
    $('.game__popout').show();
    TweenMax.set('.game__popout', { autoAlpha: 0 });
    TweenMax.to('.game__popout', 0.5, { autoAlpha: 1 });
  }

  /* function useCoupon(_number, _callback) {
     var _tempScore = myScore;
 
     if (_tempScore + _number < 0) {
       alert('很抱歉，吉點不足。');
     } else {
       addScore(_number);
       TweenMax.to('.game__popout', 0.3, { autoAlpha: 0 });
 
       //call 打點API
       //讀取Coupon新Data
       setTimeout(function () {
 
         //顯示成功與否
         $('.game__popout__content .content').hide();
         $('.game__popout__submit').hide();
         $('.game__popout__content .content__result').show();
         $('.game__popout__content .content__result__text').html('<p>兌換完成<br>請至LINE錢包<br>查看點數</p>');
         TweenMax.to('.game__popout', 0.5, { autoAlpha: 1 });
 
         //Coupon更新自己狀態
         _callback();
 
       }, 500);
     }
   }*/

  function useCoupon(_id, _number, _callback) {

    addScore(_number);
    TweenMax.to('.game__popout', 0.3, { autoAlpha: 0 });

    $.ajax({
      type: "POST",
      url: API__DOMAIN + "api2021/redeem/" + LINEID + '/' + _id,
      data: {
        name: name
      },
      dataType: "json",
      success: function (response) {
        console.log('================== response ===================');
        console.log(response);
        if (response.succ) {
          //顯示成功與否
          $('.game__popout__content .content').hide();
          $('.game__popout__submit').hide();
          $('.game__popout__content .content__result').show();
          $('.game__popout__content .content__result__text').html('<p>兌換完成<br>請至LINE錢包<br>查看點數</p>');
          showPopout();

          //Coupon更新自己狀態
          _callback();
          updateUserData();
        } else {
          showError("兌換錯誤：<br>" + response.err);
        }

      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log("Status: " + textStatus + ", Error: " + errorThrown);
        // alert('很抱歉，資料讀取錯誤 請稍後再試。');
        showError("連線錯誤：<br>" + "Status: " + textStatus + ", Error: " + errorThrown);
        TweenMax.to('.loading', 0.3, { autoAlpha: 0 });
      }
    });
  }

  function showLoading() {

  }

  function showError(_msg) {
    if (isAllSoldout) {
      _msg = '<span style="font-size:0.8em">本次活動已結束<br>敬請期待下次遊戲。</span>';
    }

    //顯示成功與否
    $('.game__popout__content .content').hide();
    $('.game__popout__submit').hide();
    $('.game__popout__content .content__result').show();
    $('.game__popout__content .content__result__text').html('<p>系統忙碌中<br>請稍後再試</p>');
    showPopout();

    if (_msg != undefined) {
      $('.game__popout__content .content__result__text').html('<p>' + _msg + '</p>');
    }
  }

  //constructor

  {
    $(document).ready(function () {
      init();
    });
  }

  //public

  return {
    gameInto: function () {
      console.log('gameInto');
      gameInto();
    },

    luckydrawComplete: function () {
      luckydrawComplete();
    },

    storeIntoComplete: function () {
      storeIntoComplete();
    },

    storeCloseComplete: function () {
      isStore = false;
    },

    showPopout: function (_clickHandle) {
      showPopout();
      popoutClickHandle = _clickHandle;
    },

    useCoupon: function (_id, _number, _callback) {
      useCoupon(_id, _number, _callback);
    },
  }
};

var main = new main();
