<template>
    <div class="app-login-third">
        <span class="title">{{ $t("components.login.other") }}</span>
        <div class="app-login-third-imgrwap">
            <div class="sign-btn" @click="handleThirdLogin('DINGDING')">
                <img class="third-svg-container" src="@/assets/img/dingding.svg" />
            </div>
            <div class="sign-btn" @click="handleThirdLogin('WXWORK')">
                <img class="third-svg-container" src="@/assets/img/qiyeweixin.svg" />
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import qs from "qs";
// import * as dd from "dingtalk-jsapi";
import axios from "axios";
import { Util } from "@/utils";
@Component({})
export default class AppThirdLogin extends Vue {
    /**
     * 处理第三方登录
     *
     * @param type 登录类型
     * @memberof AppThirdLogin
     */
    handleThirdLogin(type: string) {
        switch (type) {
            case "DINGDING":
                this.dingTalkHandleClick();
                break;
            case "WXWORK":
                this.wxWorkHandleClick();
                break;
            default:
                console.warn(`暂不支持${type}登录`);
                break;
        }
    }

    /**
     * 钉钉登录
     *
     * @memberof AppThirdLogin
     */
    async dingTalkHandleClick() {
        let result: any = await this.dingtalkLogin();
        if (result) {
            if (result.state && Object.is(result.state, "SUCCESS")) {
                const data = result.data;
                // 截取地址，拼接需要部分组成新地址
                const baseUrl = this.getNeedLocation();
                // 1.钉钉开放平台提供的appId
                const appId = data.appid;
                // 2.钉钉扫码后回调地址,需要UrlEncode转码
                const redirect_uri = baseUrl + "assets/third/dingdingRedirect.html?id=" + data.appid;
                const redirect_uri_encode = encodeURIComponent(redirect_uri);
                // 3.钉钉扫码url
                const url =
                    "https://oapi.dingtalk.com/connect/qrconnect?response_type=code" +
                    "&appid=" +
                    appId +
                    "&redirect_uri=" +
                    redirect_uri_encode +
                    "&scope=snsapi_login" +
                    "&state=STATE";

                // 4.跳转钉钉扫码
                window.location.href = url;
            } else if (result.message) {
                throw new Error(result.message);
            }
        }
    }

    /**
     * 微信登录
     *
     * @memberof AppThirdLogin
     */
    async wxWorkHandleClick() {
        let result: any = await this.wxWorkLogin();
        if (result) {
            if (result.state && Object.is(result.state, "SUCCESS")) {
                const data = result.data;
                // 截取地址，拼接需要部分组成新地址
                const baseUrl = this.getNeedLocation();
                // 1.微信平台提供的appId
                const appId = data.corp_id;
                const agentId = data.agentid;
                // 2.微信扫码后回调地址,需要UrlEncode转码
                const redirect_uri = baseUrl + "assets/third/wxWorkRedirect.html?id=" + data.appid;
                const redirect_uri_encode = encodeURIComponent(redirect_uri);
                // 3.微信扫码url
                const url =
                    "https://open.work.weixin.qq.com/wwopen/sso/qrConnect?state=STATE" +
                    "&appid=" +
                    appId +
                    "&agentid=" +
                    agentId +
                    "&redirect_uri=" +
                    redirect_uri_encode;
                // 4.跳转微信扫码
                window.location.href = url;
            } else if (result.message) {
                throw new Error(result.message);
            }
        }
    }

    /**
     * 截取地址
     *
     * @memberof AppThirdLogin
     */
    private getNeedLocation() {
        // 截取地址，拼接需要部分组成新地址
        const scheme = window.location.protocol;
        const host = window.location.host;
        let baseUrl: any = scheme + "//" + host;
        const port = window.location.port;
        if (port) {
            if (port == "80" || port == "443") {
                baseUrl += "/";
            } else {
                baseUrl += ":" + port + "/";
            }
        } else {
            baseUrl += "/";
        }
        return baseUrl;
    }

    /**
     * 钉钉授权登录
     *
     * @memberof AppThirdService
     */
    public dingtalkLogin(): Promise<any> {
        return new Promise((resolve) => {
            //  请求头
            const headers = {};
            const tempViewParam = Util.getDcSystemIdViewParam();
            if (tempViewParam && tempViewParam.srfdcsystem) {
                Object.assign(headers, { srfdcsystem: tempViewParam.srfdcsystem });
            }
            const get: Promise<any> = this.getData("/uaa/open/dingtalk/appid", {}, false, headers);
            get.then((response: any) => {
                if (response && response.status === 200) {
                    const data = response.data;
                    if (data && data.appid) {
                        resolve({ state: "SUCCESS", data: data });
                    } else {
                        resolve({
                            state: "ERROR",
                            message: `获取网站应用appid失败，${data.detail}`,
                        });
                    }
                }
            }).catch((error: any) => {
                const data = error.data;
                if (data && data.detail) {
                    resolve({
                        state: "ERROR",
                        message: `获取网站应用appid失败，${data.detail}`,
                    });
                } else {
                    resolve({ state: "ERROR", message: `获取网站应用appid失败` });
                }
            });
        });
    }

    /**
     * 企业微信授权登录
     *
     * @memberof AppThirdService
     */
    public wxWorkLogin(): Promise<any> {
        return new Promise((resolve) => {
            //  请求头
            const headers = {};
            const tempViewParam = Util.getDcSystemIdViewParam();
            if (tempViewParam && tempViewParam.srfdcsystem) {
                Object.assign(headers, { srfdcsystem: tempViewParam.srfdcsystem });
            }
            const get: Promise<any> = this.getData("/uaa/open/wxwork/appid", {}, false, headers);
            get.then((response: any) => {
                if (response && response.status === 200) {
                    const data = response.data;
                    if (data && (data.corp_id || data.appid)) {
                        resolve({ state: "SUCCESS", data: data });
                    } else {
                        resolve({
                            state: "ERROR",
                            message: `获取网站应用appid失败，${data.detail}`,
                        });
                    }
                }
            }).catch((error: any) => {
                const data = error.data;
                if (data && data.detail) {
                    resolve({
                        state: "ERROR",
                        message: `获取网站应用appid失败，${data.detail}`,
                    });
                } else {
                    resolve({ state: "ERROR", message: `获取网站应用appid失败` });
                }
            });
        });
    }

    /**
     * 钉钉内部免登
     *
     * @memberof AppThirdService
     */
    public embedDingTalkLogin(Environment: any): Promise<any> {
        return new Promise((resolve) => {
            //  请求头
            const headers = {};
            const tempViewParam = Util.getDcSystemIdViewParam();
            if (tempViewParam && tempViewParam.srfdcsystem) {
                Object.assign(headers, { srfdcsystem: tempViewParam.srfdcsystem });
            }
            const param = Util.handleViewParam(window.location.href);
            if (param.corpId) {
                let corpId: string = param.corpId;
                if (corpId.indexOf("#") > -1) {
                    corpId = corpId.split("#")[0];
                }
                // dd.runtime.permission
                //     .requestAuthCode({ corpId })
                //     .then((res: any) => {
                //         if (res && res.code) {
                //             this.getData(`/uaa/open/dingtalk/auth/${res.code}`, {}, false, headers).then((res: any) => {
                //                 if (res.status == 200 && (res.data.token || res.data.user)) {
                //                     resolve({ state: "SUCCESS", data: res.data });
                //                 } else {
                //                     resolve({ state: "ERROR", message: `${res.data.message}` });
                //                 }
                //             });
                //         } else {
                //             resolve({ state: "ERROR", message: `钉钉用户信息获取失败` });
                //         }
                //     })
                //     .catch((error: any) => {
                //         resolve({ state: "ERROR", message: `钉钉用户信息获取失败` });
                //     });
            } else {
                resolve({ state: "ERROR", message: `获取企业ID失败` });
            }
        });
    }

    /**
     * 获取数据
     *
     * @memberof AppThirdService
     */
    public getData(url: string, params: any = {}, isloading?: boolean, headers: any = {}) {
        params = this.handleRequestData(params);
        if (params.srfparentdata) {
            Object.assign(params, params.srfparentdata);
            delete params.srfparentdata;
        }
        if (Object.keys(params).length > 0) {
            let tempParam: any = {};
            Object.keys(params).forEach((item: any) => {
                if (params[item] || Object.is(params[item], 0)) {
                    tempParam[item] = params[item];
                }
            });
            if (Object.keys(tempParam).length > 0) {
                url += `?${qs.stringify(tempParam)}`;
            }
        }
        return new Promise((resolve: any, reject: any) => {
            axios.get(url, { headers: headers }).then((response: any) => {
                resolve(response);
            });
        });
    }

    /**
     * 处理请求数据
     *
     * @memberof AppThirdService
     */
    public handleRequestData(data: any) {
        if (data?.srfsessionkey) {
            delete data.srfsessionkey;
        }
        if (data?.srfsessionid) {
            delete data.srfsessionid;
        }
        if (data?.srfparentdemapname) {
            delete data.srfparentdemapname;
        }
        return data;
    }
}
</script>

<style lang="less">
@import "./app-login-third.less";
</style>
