import { authorizeBatch } from '../../utils/authorize'
const util = require('../../utils/util.js')
const app = getApp() 
Page({
  data: {
    isAgree: false,
    openid:"",
    showAuthModal: false,
    userInfo: null,
    needReg: false, 
    avatarUrl: '/images/Blvlogo.png',
     nickName: '',
    form: {
          name: '',
          phone: ''
          }
        },
  onLoad() {
    	
const isAgree = wx.getStorageSync('isAgree');
	
if (typeof isAgree  !== 'undefined'){
  this.setData({ isAgree:isAgree });    
}

  
    this.handleLogin()   
  },
  onAvatar(e) {
    ////////debugger
    this.setData({ avatarUrl: e.detail.avatarUrl }) // 用户选的头像
  },
  onNick(e) {
    this.setData({ nickName: e.detail.value })      // 用户输入的昵称
  },



  inputName(e) {this.setData({'form.name': e.detail.value})},
  inputPhone(e) {this.setData({'form.phone': e.detail.value})},
  async submitReg() {
     // 校验注册信息
     const { form, nickName } = this.data;
    
     if (!form.name.trim()) {
       wx.showToast({ 
         title: '姓名不能为空',
         icon: 'none'
       });
       return;
     }
     
     if (!form.phone.trim()) {
       wx.showToast({ 
         title: '工号不能为空',
         icon: 'none'
       });
       return;
     }
     
     // 校验电话号码格式（11位数字，以1开头）
     const phoneReg = /^1\d{10}$/;
     if (!phoneReg.test(form.phone.trim())) {
       wx.showToast({ 
         title: '请输入有效的工号',
         icon: 'none'
       });
       return;
     }
     
     if (!nickName.trim()) {
       wx.showToast({ 
         title: '微信昵称不能为空',
         icon: 'none'
       });
       return;
     }
    try {
      wx.showLoading({ title: '登录中...', mask: true });
  
      // 获取微信code
      const loginRes = await new Promise((resolve, reject) => {
        wx.login({
          success: resolve,
          fail: reject
        });
      });
  
      if (!loginRes.code) {
        throw new Error('获取登录凭证失败');
      }
      const nickName = this.data.nickName;
      let form =this.data.form
      let openid =this.data.openid
      let avatarUrl =this.data.avatarUrl
      

      // 发送到后端
      const apiRes = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://wx-xcx-check.blv-oa.com:4433/api/Login/Register',
          method: 'POST',
          data: {
            UserName:form.name ,
            UserKey: openid,
            WeChatName:nickName,
            PhoneNumber:form.phone,            
            AvatarUrl:""
          },
          
          success: res =>{
            
            this.uploadAvatarToServer(avatarUrl,res.data.data.userKey)
            if (res.data.success  && res.data.data.userName && res.data.data.weChatName && res.data.data.phoneNumber) {              
              wx.setStorageSync('openid', res.data.data.userKey);
              this.setData({openid:res.data.data.userKey}); 
              app.globalData.userKey=res.data.data.userKey
              app.globalData.weChatName=res.data.data.weChatName
              app.globalData.avatarUrl=this.data.avatarUrl 
              wx.navigateTo({url: '/pages/chat/chat'});
            }
            else{
              wx.showToast({ 
                title: '登录失败:'+ res.data.message,
                icon: 'none'
              });
              this.setData({needReg: true});                      
            }
          },
          fail: reject
        });
      });
  
    
    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({ 
        title: `登录失败: ${error.message || '未知错误'}`,
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }


  },
  onAgreeChange(e) {
    
    console.log(e)
    this.setData({ isAgree: e.detail.value.length > 0 });
    wx.setStorageSync('isAgree', this.data.isAgree);
    
  },

  openContract() {
    wx.openPrivacyContract({
      success: () => console.log('已打开协议'),
      fail: (e) => console.log('打开失败', e)
    })
  },
  // 添加新方法

  // 显示授权弹窗
  showAuthModal() {
    this.setData({ showAuthModal: true });
  },

  // 取消授权
  onAuthCancel() {
    this.setData({ showAuthModal: false });
    wx.showToast({ title: '授权已取消', icon: 'none' });
  },
 // 获取用户信息
 async onGetUserInfo(e) {
  try {
    if (e.detail.errMsg !== 'getUserInfo:ok') {
      throw new Error('用户拒绝了授权');
    }

    const userInfo = e.detail.userInfo;
    this.setData({
      userInfo,
      showAuthModal: false
    });
//////////debugger
    // 保存到全局
    getApp().globalData.userInfo = userInfo;
   
    await this.onGetAuth()
    // 继续登录流程
    await this.completeLogin();
    
  } catch (error) {
    console.error('获取用户信息失败:'+error);
    wx.showToast({
      title: error.message || '获取用户信息失败',
      icon: 'none'
    });
  }
},
async onGetAuth() {
  const res = await authorizeBatch([   
    'scope.record',
    'scope.userLocation'
  ])

  if (true) {//if (res.ok) {
    wx.showToast({ title: '全部授权成功' })
  } else {
    wx.showModal({
      title: '提示',
      content: `您拒绝了 ${res.denied.map(s => SCOPE_MAP[s]).join('、')}，部分功能可能无法使用`,
      showCancel: false
    })
  }
},
uploadAvatarToServer(tempFilePath,userKey) {
  // 显示加载提示，提升用户体验
  wx.showLoading({ title: '上传中...' });
  
  wx.uploadFile({
    url: 'https://wx-xcx-check.blv-oa.com:4433/api/Check/UploadFile', // 你的服务器上传接口
    filePath: tempFilePath,
    name: 'file', // 与后端约定的文件参数名
    formData: {
      'rootPathType': 'Avatar', // 指定保存到 wwwroot/Avatar 目录
      'userKey': userKey // 指定要更新头像的用户
    },
    success: (res) => {
      wx.hideLoading();
      const data = JSON.parse(res.data); // 注意: uploadFile返回的data是字符串，需解析
      if (data.success) {
        // 上传成功，拿到服务器返回的永久链接
        const permanentUrl = data.url;
        this.setData({
          avatarUrl: permanentUrl // 更新为永久链接
        });
        // 接下来可以将 permanentUrl 保存到本地缓存或发送给后端更新用户信息
        wx.showToast({ title: '上传成功' });
      } else {
        wx.showToast({ title: '上传失败: ' + data.message, icon: 'none' });
      }
    },
    fail: (err) => {
      wx.hideLoading();
      console.error('上传接口调用失败', err);
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  });
},
// 完整的登录流程
async completeLogin() {
  
  try {
    wx.showLoading({ title: '登录中...', mask: true });

    // 获取微信code
    const loginRes = await new Promise((resolve, reject) => {
      wx.login({
        success: resolve,
        fail: reject
      });
    });

    if (!loginRes.code) {
      throw new Error('获取登录凭证失败');
    }

    // 发送到后端
    const apiRes = await new Promise((resolve, reject) => {
      wx.request({
        url: 'https://wx-xcx-check.blv-oa.com:4433/api/Login/Login',
        method: 'POST',
        data: {Code: loginRes.code},
        success: res =>{
          wx.hideLoading()
            if (res.data.success){
             
              this.setData({openid: res.data.data.userKey});
              console.log(this.data.openid)
              wx.setStorageSync('openid', res.data.data.userKey);
              app.globalData.userKey=res.data.data.userKey
              app.globalData.weChatName=res.data.data.weChatName
              app.globalData.avatarUrl=res.data.data.avatarUrl
              
            }

          if (res.data.success  && res.data.data.userName && res.data.data.weChatName && res.data.data.phoneNumber)  {         
            wx.navigateTo({url: '/pages/chat/chat'});
          }
         
          else{
            wx.showToast({ 
              title: `登录失败: 用户未注册。请先填写完整信息再进行登录`,
              icon: 'none'
            });
            this.setData({needReg: true});                      
          }
        },
        fail: reject
      });
    });

  
  } catch (error) {
    console.error('登录失败:', error);
    wx.showToast({ 
      title: `登录失败: ${error.message || '未知错误'}`,
      icon: 'none'
    });
  } finally {
    wx.hideLoading();
  }
},

// 修改原有登录方法
handleLogin: async function() {
  
  if (this.data.isAgree) {
    // 如果已有用户信息，直接完成登录
  // if (this.data.userInfo) {
    await this.completeLogin();
  // } else {
  //   // 否则显示授权弹窗
  //   this.showAuthModal();
  // }
  }else{
    // 提示为勾选用户协议
    wx.showToast({
      title: '请先勾选用户协议',
      icon: 'none'
    });
    return;            // 拦截后续登录逻辑
  }
  
},

})
