<template>
  <view>

  </view>
</template>

<script setup>
  // 添加路由拦截
  import '@/interceptor/routeInterceptor.js'
  import { encryptByEnAESLogin } from '@/utils/index.js'
  import { onLoad } from '@dcloudio/uni-app'
  import { defaultColor } from '@/static/js/theme.js'
  import { api_wechatLoginEncrypt, api_loginEncrypt, api_systemConfiguration } from "@/http/api.js"
  import { useWechatAuth } from '@/share/useWechatAuth.js'
  import { useLoginSuccess } from '@/share/useLoginSuccess.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  
  useSetTitle()
  const { wechatAuth } = useWechatAuth()
  const { loginSuccess } = useLoginSuccess()

  /**
   * 微信登录
   */
  function wechatLoginEncrypt() {
    const url = window.location.href.split("?");
		let wenhaohoumian = window.location.href.split("?code="); //截取问号地址数组
		let codeStr = wenhaohoumian[1]; //地址数组赋值
    if (!url[1]) {
      wechatAuth();
    } else {
			codeStr = codeStr.split("&");
			codeStr = codeStr[0];
      uni.showLoading({
        title: "登录中",
        mask: true,
      });
      api_wechatLoginEncrypt({
				code:codeStr
			}).then(res => {
        uni.hideLoading();
        if (res.status == 200) {
          loginSuccess(res.user);
					getConfig();
        } else if (res.status == 501) {
          uni.showModal({
            title: '提示',
            content: '您的账号被删除，请联系管理员',
            showCancel: false,
            confirmColor: defaultColor,
            confirmText: '取消',
          });
        } else if (res.status == 403) {
          uni.reLaunch({
            url: `/pages/initBind/initBind?wechat=${res.wechat}`
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: res.remarks || '请求数据失败！'
          });
        }
      });
    }
  }
  
  /**
   * 账号密码登录
   */
  function loginEncrypt(username, password) {
    uni.showLoading({
      title: "登录中",
      mask: true,
    });
    let postData = {
        k: encryptByEnAESLogin(JSON.stringify({username, password}))
    };
    api_loginEncrypt(postData).then(res => {
      uni.hideLoading();
			getConfig();
      if (res.state == 200) {
        loginSuccess(res.data);
      } else {
        uni.showToast({
          icon: 'none',
          title: res.remarks || '请求数据失败！'
        });
      }
    });
  }
	
	// 获取配置项
	function getConfig(){
		api_systemConfiguration({
			idx: 0,
			sum: 9999,
		}).then(res=>{
			uni.setStorageSync('sysData',JSON.stringify(res.list))
		})
	}
	
  onLoad((option) => {
    uni.clearStorageSync();
    // 获取当前页面的实例
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    // 获取URL参数
    const options = currentPage.options;
    if (process.env.NODE_ENV === 'development' && options.username && options.password) {
      // http://localhost:8081/user/#/?username=liaomingming&password=Dstech@123
      // 本地开发调试用
    	loginEncrypt(options.username, options.password)
    } else {
    	wechatLoginEncrypt();
    }

  })
</script>
