<script>
import Vue from 'vue'
import BASE_URL from './config.js'
import { mapActions } from 'vuex'
import loginService from '@/api/auth/loginService'
import * as dd from 'dingtalk-jsapi'
export default {
    onLaunch: function () {
        uni.getSystemInfo({
            success: function (e) {
                // #ifndef MP
                Vue.prototype.StatusBar = e.statusBarHeight;
                if (e.platform == 'android') {
                    Vue.prototype.CustomBar = e.statusBarHeight + 50;
                } else {
                    Vue.prototype.CustomBar = e.statusBarHeight + 45;
                };
                // #endif

                // #ifdef MP-WEIXIN
                Vue.prototype.StatusBar = e.statusBarHeight;
                let custom = wx.getMenuButtonBoundingClientRect();
                Vue.prototype.Custom = custom;
                Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
                // #endif

                // #ifdef MP-ALIPAY
                Vue.prototype.StatusBar = e.statusBarHeight;
                Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
                // #endif
            }
        })

        Vue.prototype.ColorList = [{
            title: '嫣红',
            name: 'red',
            color: '#e54d42'
        },
        {
            title: '桔橙',
            name: 'orange',
            color: '#f37b1d'
        },
        {
            title: '明黄',
            name: 'yellow',
            color: '#fbbd08'
        },
        {
            title: '橄榄',
            name: 'olive',
            color: '#8dc63f'
        },
        {
            title: '森绿',
            name: 'green',
            color: '#39b54a'
        },
        {
            title: '天青',
            name: 'cyan',
            color: '#1cbbb4'
        },
        {
            title: '海蓝',
            name: 'blue',
            color: '#0081ff'
        },
        {
            title: '姹紫',
            name: 'purple',
            color: '#6739b6'
        },
        {
            title: '木槿',
            name: 'mauve',
            color: '#9c26b0'
        },
        {
            title: '桃粉',
            name: 'pink',
            color: '#e03997'
        },
        {
            title: '棕褐',
            name: 'brown',
            color: '#a5673f'
        },
        {
            title: '玄灰',
            name: 'grey',
            color: '#8799a3'
        },
        {
            title: '草灰',
            name: 'gray',
            color: '#aaaaaa'
        },
        {
            title: '墨黑',
            name: 'black',
            color: '#333333'
        },
        {
            title: '雅白',
            name: 'white',
            color: '#ffffff'
        },
        ]

    },
    onShow: function () {
        console.log('App Show')
    },
    onHide: function () {
        console.log('App Hide')
    },
    created: async function () {

        const urlParams = this.getUrlParams();
        if (await this.tryDingTalkAutoLogin(urlParams)) {
            return;
        }
        // 获取 URL 中的 code 参数
        const code = urlParams.get('code');

        console.log('传入 code -------');
        console.log(code);

        if (code) {
            try {
                // 发起请求获取用户信息
                const [err, res] = await uni.request({
                    url: BASE_URL + `/flowable-server/app/proxy?appid=wxbcd608a92d6f9412&secret=69d382e18089367566df595b102fe756&code=` + code,
                    method: 'GET'
                });

                if (res && res.statusCode === 200) {
                  //console.log('用户信息获取成功-----------');
                    const data = res.data;
                  //console.log(data);
                  //console.log(data.openId);
                    // 将微信用户的 openId 存到本地
                    uni.setStorageSync('openId', data.openId);
                  //console.log('getStorageSync-> ', uni.getStorageSync('openId'));
                } else {
                    console.error('获取用户信息失败：', res.data);
                }
            } catch (err) {
                console.error('请求失败：', err);
            }
        }

        // 判断当前微信号的openId 是否已经存入到数据库了，如果存入了，那么就直接通过openId匹配登录，否则就进入登录页面
        const flag = true;
        const localOpenId = uni.getStorageSync('openId');
        if (localOpenId) {
            try {
                // 发起请求获取库中的openId
                const [err, res] = await uni.request({
                    url: BASE_URL + `/system-server/sys/user/allOpenIds`,
                    method: 'GET'
                });

                if (res && res.statusCode === 200) {
                    const data = res.data;
                  //console.log('allOpenIds:', data);
                    // 确保 data 是数组
                    if (Array.isArray(data) && data.includes(localOpenId)) {
                        // 包含的话，则直接根据 openId来实现登录
                      //console.log(`data 包含 openId: ${localOpenId}`);
                        const [err, res] = await uni.request({
                            url: BASE_URL + `/auth-server/user/sys/wxLogin`,
                            method: 'POST',
                            data: { openId: localOpenId },
                            header: {
                                'domain': 'ydddl'
                            }
                        });
                        if (res && res.statusCode === 200) {
                            this.$store.commit('SET_TOKEN', res.data.token);
                            await this.refreshUserInfo();
                            uni.reLaunch({
                                url: '../index/index',
                            });
                        }
                    }
                }
            } catch (err) {
                console.error('请求失败：', err);
            }
        }

        if (flag) {
            console.log('进来了');
        }

        // 获取 URL 中的 'flow' 参数
        const flowParam = this.$route.query.flow;
        // 将 URL 编码的 'flow' 参数解析为 JSON 对象
        if (!flowParam) {
            return;
        }
        const flowObject = JSON.parse(decodeURIComponent(flowParam));
      //console.log("flowObject.openId---> ", flowObject.openId)
        if (flowObject.openId) {
            const [err, res] = await uni.request({
                url: BASE_URL + `/auth-server/user/sys/wxLogin`,
                method: 'POST',
                data: { openId: flowObject.openId },
                header: {
                    'domain': 'ydddl'
                }
            });
            if (res && res.statusCode === 200) {
                this.$store.commit('SET_TOKEN', res.data.token);
                await this.refreshUserInfo();
            }
        }

    },
    methods: {
        ...mapActions(['refreshUserInfo']),
        getUrlParams() {
            const params = new URLSearchParams(window.location.search || '');
            const hash = window.location.hash || '';
            const hashQueryIndex = hash.indexOf('?');
            if (hashQueryIndex > -1) {
                const hashParams = new URLSearchParams(hash.substring(hashQueryIndex + 1));
                hashParams.forEach((value, key) => {
                    if (!params.has(key)) {
                        params.set(key, value);
                    }
                });
            }
            return params;
        },
        isDingTalkEnv() {
            return /DingTalk/i.test(window.navigator.userAgent || '');
        },
        loadDingTalkJs() {
            return Promise.resolve(dd);
        },
      requestDingTalkAuthCode(corpId) {
        return new Promise((resolve, reject) => {
          // 节点1：进入方法
          //console.log('1. 进入获取钉钉授权码函数，corpId:' + corpId);

          // 节点2：判断dd是否存在
          if (!dd) {
            const errMsg = '钉钉资源未加载成功，请联系管理员';
            //console.log('2. 异常：' + errMsg);
            reject(new Error(errMsg));
            return;
          }
          //console.log('2. dd对象存在，准备调用getAuthCode');

          let hasCallbackTriggered = false;

          dd.getAuthCode({
            corpId: corpId,
            onSuccess: (res) => {
              if (hasCallbackTriggered) return;
              hasCallbackTriggered = true;
              //console.log('3. getAuthCode成功，返回数据:' + JSON.stringify(res));
              const code = res.code || res.authCode;
              //console.log('4. 提取授权码=' + code);
              resolve(code);
            },
            onFail: (err) => {
              if (hasCallbackTriggered) return;
              hasCallbackTriggered = true;
              //console.log('3. getAuthCode失败，错误信息:' + JSON.stringify(err));
              reject(err);
            }
          });

          // 钉钉全局异常监听
          dd.error((err) => {
            if (hasCallbackTriggered) return;
            hasCallbackTriggered = true;
            //console.log('5. 钉钉全局捕获异常:' + JSON.stringify(err));
            reject(err);
          });
        });
      },
        async handleDingTalkLoginSuccess(data) {
            this.$store.commit('SET_TOKEN', data.token);
            await this.refreshUserInfo();
        },
      async tryDingTalkAutoLogin(urlParams) {
        //console.log('[钉钉自动登录] 1、进入 tryDingTalkAutoLogin 函数');

        const isDingEnv = this.isDingTalkEnv();
        //console.log('[钉钉自动登录] 2、钉钉环境检测结果：', isDingEnv);
        if (!isDingEnv) {
          //console.log('[钉钉自动登录] 分支：非钉钉环境，return false，流程终止');
          return false;
        }

        const existToken = !!this.$store.state.user.token;
        //console.log('[钉钉自动登录] 3、当前是否存在token：', existToken);
        if (this.$store.state.user.token) {
          //console.log('[钉钉自动登录] 分支：已有token，自动跳转首页');
          // 已有登录态，直接跳首页，解决你不跳转的问题
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/index/index'
            });
          }, 200);
          return true;
        }

        //console.log('[钉钉自动登录] 4、无token，继续往下执行免登逻辑');
        const tenantId = urlParams.get('tenantId') || uni.getStorageSync('dingTalkTenantId') || '10009';
        //console.log('[钉钉自动登录] 5、解析得到tenantId：', tenantId);

        try {
          //console.log('[钉钉自动登录] 6、开始请求后端 dingTalkClientConfig 获取corpId配置');
          const clientConfig = await loginService.dingTalkClientConfig(tenantId);
          //console.log('[钉钉自动登录] 7、后端返回clientConfig：', clientConfig);

          if (!clientConfig || !clientConfig.corpId) {
            //console.log('[钉钉自动登录] 分支：clientConfig为空 或 corpId不存在，抛出异常');
            throw new Error('DingTalk corpId is missing');
          }
          //console.log('[钉钉自动登录] 8、拿到有效corpId：', clientConfig.corpId);

          //console.log('[钉钉自动登录] 9、即将执行 loadDingTalkJs 校验钉钉SDK是否加载');
          await this.loadDingTalkJs();
          //console.log('[钉钉自动登录] 10、loadDingTalkJs执行完成，准备调用 requestDingTalkAuthCode');

          //console.log('>>>>>>>>>> 即将进入 requestDingTalkAuthCode 方法 <<<<<<<<<<');
          const authCode = await this.requestDingTalkAuthCode(clientConfig.corpId);
          //console.log('[钉钉自动登录] 11、requestDingTalkAuthCode执行完成，获取到authCode：', authCode);

          //console.log('[钉钉自动登录] 12、调用后端钉钉登录接口 dingTalkLogin');
          const loginResult = await loginService.dingTalkLogin({
            authCode: authCode,
            tenantId: tenantId
          });
          //console.log('[钉钉自动登录] 13、登录接口返回结果：', loginResult);

          if (loginResult.bindRequired) {
            //console.log('[钉钉自动登录] 分支：需要账号绑定，跳转绑定页面');
            uni.setStorageSync('dingTalkBindKey', loginResult.bindKey);
            uni.setStorageSync('dingTalkTenantId', loginResult.tenantId || tenantId);
            uni.reLaunch({
              url: '/pages/login/login?bind=dingtalk'
            });
            return true;
          }
          //console.log('[钉钉自动登录] 14、登录成功，执行保存用户信息');
          await this.handleDingTalkLoginSuccess(loginResult);
          //console.log('[钉钉自动登录] 15、跳转首页');
          uni.reLaunch({
            url: '/pages/index/index'
          });
        } catch (e) {
          console.error('[钉钉自动登录] 捕获异常，流程中断，错误对象：', e);
          console.error('[钉钉自动登录] 异常信息message：', e.message);
          uni.showToast({
            title: JSON.stringify(e),
            icon: 'none'
          });
        }
        //console.log('[钉钉自动登录] 函数末尾，return true');
        return true;
      },
    }

}
</script>

<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/uview-ui/index.scss";
@import "static/css/jeeplus.scss";
/* @import 'jeeplus-flowable/lib/jeeplus-flowable.css'; */
@import "static/css/main.css";
@import "static/css/icon.css";
/*每个页面公共css */
</style>
