const api = require('../../api/api');
const { md5 } = require('../../utils/util.js');
var monitApi = require("../../utils/util.js");

Page({
  data: {
    checked:false,
    userVersion: '1', //1户用光伏系统，2监控运维系统
  },

  onLoad() {
    this.setData({
      loginName: wx.getStorageSync('loginName'),
      password: wx.getStorageSync('password'),
      userId: wx.getStorageSync('userId'),
      userName: wx.getStorageSync('userName'),
      userType: wx.getStorageSync('userType'),  
    })
    if(wx.getStorageSync('sysType')){
      this.setData({
        userVersion: wx.getStorageSync('sysType'),
      })
    }
    if (this.data.loginName && this.data.password) {    
      if(this.data.userVersion =='1'){
        this.login()
      }else if(this.data.userVersion =='2'){
        this.servLogin()
      }
    }
  },

  /**
   * 
   * 忘记密码
   * 
   * @param {*} e 
   */
  showForget(e) {
    wx.navigateTo({
      url: '/pages/forgotPassword/forgotPassword',
    })
  },


  /**
   * 
   * 登录事件
   * 
   * @param {*} e 
   */
  loginSubmit(e) {
    if (!this.data.loginName) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none',
      })
    } else if (!this.data.password) {
      wx.showToast({
        title: '请输入登录密码',
        icon: 'none',
      })
    } else if (!this.data.checked){
      wx.showToast({
        title: '请先阅读并同意《用户协议》和《隐私政策》',
        icon: 'none',
      })
    } else {
      if(this.data.userVersion =='1'){
        this.login()
      }else if(this.data.userVersion =='2'){
        this.servLogin()
      }  
    }
  },

  /**
   * 
   * 代理商登录
   * 
   * @param {*} data 
   */
  login(data) {
    wx.showLoading({
      title: '登录中',
    })

    var data = {
      loginName: this.data.loginName,
      password: this.data.password,
      from: 'RROJECT_MANAGE',
    }

    api.login(data).then(res => {
      wx.hideLoading()
      if (res.isLogin == 200) {
        wx.setStorageSync('loginName', this.data.loginName)
        wx.setStorageSync('password', this.data.password)

        wx.setStorageSync('userId', res.userId)
        wx.setStorageSync('userName', res.userName)
        wx.setStorageSync('mobile', res.mobile)
        wx.setStorageSync('userType', res.userType) //TRADER:代理商，TRADER_EMP:代理商员工，PLATFORM_EMP：平台，暂不用（SYS_EMP:系统工程师。PRO_EMP:项目工程师）
        wx.setStorageSync('traderId', '')
        wx.setStorageSync('traderName', '所有代理商')
        wx.setStorageSync('traderType', res.traderType) //代理商等级
        wx.setStorageSync('sysType', '1')


        //代理商员工角色菜单权限控制
        if (res.userType == "TRADER_EMP" && res.menuList) {
          let menuList = JSON.parse(res.menuList), obj={};
          if(menuList.length){
            menuList.forEach(itm=>{
              obj[itm] = true;
            });
          }
          wx.setStorageSync('permission', obj)
        }
        //平台列表按钮权限控制
        if (res.userType == "PLATFORM_EMP") {
          wx.setStorageSync('PTpermission', res.menus.split(","))
        }
        //登录代理商traderId
        if (res.traderId) {
          wx.setStorageSync('traderId', res.traderId)
        }

        wx.switchTab({
          url: '/pages/home/home',
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: res.errMsg || res.msg || '登录失败，请联系管理员',
        })
      }
    })
  },

  /**
   * 
   * 服务商登录
   * 
   * @param {*} data 
   */
  servLogin() {
    wx.showLoading({
      title: '登录中',
    })

    var data = {      
      grant_type: 'password',      
      username: this.data.loginName,
      password: md5(this.data.password),
    }
    monitApi.req('oauth/miniapp/token', data, 'post').then(res => {
      wx.hideLoading()
      if (res.code == '200') {       
        wx.setStorageSync('loginName', this.data.loginName)
        wx.setStorageSync('password', this.data.password)
        monitApi.toast('登录成功', 1500, 'success')       
        wx.setStorageSync('userId', res.data.user_id)
        wx.setStorageSync('name', res.data.real_name)
        wx.setStorageSync('TOKEN', res.data.access_token)
        wx.setStorageSync('RTOKEN', res.data.refresh_token)
        wx.setStorageSync('userType', res.data.token_type)
        wx.setStorageSync('sysType', '2')
        wx.reLaunch({
          url: '/monitor/pages/home/home',
        })
      } else {
        monitApi.toast(res.msg, 2000, 'none')
      }
    }).catch(res => {
      console.log(res)
      // monitApi.toast('内部系统错误', 1000, 'none')
    })   
  },



  onShareAppMessage() {

  },

  onShareTimeline() {

  },
  //协议查看
  linkTo(e){
    let type=e.currentTarget.dataset.type,src='';
    if(type==='ys'){
      src='https://nhet.oss-cn-shanghai.aliyuncs.com/static/files/privacy.docx'
    }else if(type==='fw'){
      src="https://nhet.oss-cn-shanghai.aliyuncs.com/static/files/agreements.docx"
    }
    wx.downloadFile({
      url: src,
      success (res) {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          showMenu: true,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (err) {
            console.log('打开文档失败',err)
          }
        })
      },
      fail: function (err) {
        console.log('下载文档失败',err)
      }
    });
  },
  //选中
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
  //切换登录版块
  swichUser(e){
    let type = this.data.userVersion;
    if(type=='1'){
      this.setData({
        userVersion: '2',       
      })
    }else{
      this.setData({        
        userVersion: '1',
      })
    }
  }
})