import { ACTION_LOGIN_OK } from '../../const/actioncmd'
Page({
  data: {
    name: "",
    password: "",
    sn: "",
    containerVersion: "",
    //按钮是否可点击
    loginDisabled: true,
    //错误提示是否可见
    errHidden: true,
    errHint: ""
  },

  onReady() {
    if (my.canIUse('hideBackHome')) {
      my.hideBackHome();
    }
  },
  onLoad() {
    //首先获取下sn
    var serialno = my.ix.getSysPropSync({ key: 'ro.serialno' });
    console.log("getSN success==>" + JSON.stringify(serialno));
    if (serialno) {
      this.setData({
        sn: serialno.value
      });
      //设置到全局变量
      getApp().globalData.sn = serialno.value;
    }

    var r = my.ix.getVersionSync();
    if (r) {
      this.setData({
        containerVersion: r.versionName//r.versionCode
      })
    }

    //获取下本地登录数据
    var localLoginInfo = my.getStorageSync({
      key: 'localLoginInfo', // 缓存数据的key
    });
    console.log("localLoginInfo==>" + JSON.stringify(localLoginInfo));
    if (localLoginInfo.success != false && localLoginInfo.data != null) {
      //赋值
      this.setData({
        name: localLoginInfo.data.name,
        password: localLoginInfo.data.password,
        sn: localLoginInfo.data.sn
      })
    }
  },
  onNameClear() {
    this.setData({
      name: ""
    });
    this.setData({
      loginDisabled: true
    });
  },
  onPasswordClear() {
    this.setData({
      password: ""
    });
    this.setData({
      loginDisabled: true
    });
  },

  onShow() {
    //自动登录
    if (this.data.name != "" && this.data.password != null) {
      this.setData({
        loginDisabled: false
      });
      this.login();
    } else {
      this.setData({
        loginDisabled: true
      });
    }

    //开启后屏监听
    let context = this;
    my.ix.onBuddyMessage({
      success: (res) => {
        console.info(`onBuddyMessage success: ${JSON.stringify(res)}`);
        if (res.action == ACTION_LOGIN_OK) {
          //后屏登录成功
          my.hideLoading();
          my.reLaunch({
            url: "/pages/home/home"
          });
          my.showToast({
            type: 'success',
            content: '登录成功',
            duration: 3000
          });
          getApp().globalData.isLoginOk = true
        }
      }
    });
  },

  onNameInput(e) {
    if (e.detail.value == "") {
      this.setData({
        loginDisabled: true
      });
      return;
    }
    this.setData({
      name: e.detail.value
    });
    this.setData({
      loginDisabled: false
    });
  },

  onPasswordInput(e) {
    if (e.detail.value == "") {
      this.setData({
        loginDisabled: true
      });
      return;
    }
    this.setData({
      password: e.detail.value
    });
    this.setData({
      loginDisabled: false
    });
  },

  login() {

    if (this.data.loginDisabled) {
      my.showToast({
        type: 'fail',
        content: '请输入账号或密码',
        duration: 3000,
        success: () => {
        },
      });
      return;
    }

    my.showLoading({});
    //本地存储登录信息
    my.setStorageSync({
      key: "localLoginInfo",
      data: {
        name: this.data.name,
        password: this.data.password,
        sn: this.data.sn
      }
    });

    //请求网络
    var api = require("../../utils/api.js");
    var loginCallbackTemp = this.loginCallback.bind(this);
    api.login({
      baseUrl: getApp().globalData.BASE_URL,
      name: this.data.name,
      password: this.data.password,
      callback: loginCallbackTemp
    });
  },
  loginCallback(res) {
    console.log("业务层登录 success==>" + JSON.stringify(res));
    if (res.code == 0) {
      //本地存储账户信息
      my.setStorageSync({
        key: 'localAccountInfo', // 缓存数据的key
        data: res.data, // 要缓存的数据
      });
      //登陆信息设置到全局变量
      getApp().globalData.localAccountInfo = res.data;
      console.info(`localAccountInfo: ${JSON.stringify(getApp().globalData.localAccountInfo)}`);
      //通知后屏登录成功
      this.sendLoginOkToBackScreen();
      this.setData({
        errHidden: true
      });
    } else {
      my.hideLoading();
      //提示登录失败
      my.showToast({
        type: 'fail',
        content: '登录失败:' + res.data,
        duration: 3000
      });
      this.setData({
        errHint: res.data
      });
      this.setData({
        errHidden: false
      });
    }
  },

  //  登录完成通知后屏
  sendLoginOkToBackScreen() {
    let context = this;
    var commonRequest = {
      action: ACTION_LOGIN_OK,
      data: {
        account: getApp().globalData.localAccountInfo,
        sn: context.data.sn,
        containerVersion: context.data.containerVersion
      }
    };
    console.log("登录成功，发送数据：" + commonRequest);
    my.ix.sendBuddyMessage({
      target: getApp().globalData.backScreenAppId,
      data: commonRequest,
      success: (res) => {
        console.log("登录成功通知后屏  成功 ===》" + JSON.stringify(res));
        if (!getApp().globalData.isLoginOk) {
          setTimeout(() => {
             //防止在等待的过程当中后屏通知前屏成功 
             if (!getApp().globalData.isLoginOk) {
               context.sendLoginOkToBackScreen();
             }
          }, 500);
        }
      },
      fail: (res) => {
        console.log("登录成功通知后屏 失败 ===》 " + JSON.stringify(res));
        //发送失败重试
        context.sendLoginOkToBackScreen();
      }
    })
  },
  onHide() {
    //关闭后屏监听
    my.ix.offBuddyMessage();
  },

});
