import signAxios from './httpSign'
import sealAxios from './sealHttp'
import { getInfo, logout, getSeal } from './auth'
import qs from 'qs'
import { Toast } from 'vant'

import config from '@/config'

export function handleProblemImgs(imageId = '') {
    let url = process.env.VUE_APP_API
    if (process.env.NODE_ENV == 'development') {
        url = 'http://183.66.101.90:8083'
    }
    return url + '/v2/api/file/' + imageId + '/open'
}

export let signToken = null

const signUrl = '/v2/sign'
// const signUrl = 'http://119.84.246.34:7021'

/**
 * 初始化电子签名
 * @returns 
 */
export async function initSign () {
    let aos
    try {
        aos = window.axLib.AosSign(
            {},
            _ => {},
        );
        await signSetToken(aos)
    } catch(_) {
        this.$toast('签名环境初始化失败!')
    }
    return aos
}

export async function signSetToken(aos) {
    const res = await getRealSignToken()
    signToken = res.data.data
    aos.setToken(signToken)
}

export function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

export function convertStreamDataToFile(streamData) {
    var uInt8Array = new Uint8Array(streamData);
    var i = uInt8Array.length;
    var binaryString = new Array(i);
    while (i--) {
        binaryString[i] = String.fromCharCode(uInt8Array[i]);
    }
    var data = binaryString.join('');
}

/**
 * 将二进制流转换为 base64
 * @param {*} streamData 
 * @returns 
 */
export function convert(streamData, type = 'application/pdf') {
    return new Promise((resolve) => {
        const blob = new Blob([streamData], {type})
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = function () {
            resolve(reader.result)
        }
    })
}

// export const sealClientId="a654a238c655263bf0f93798de1eff83" 
// export const sealClientSecret="w7wc2e89ZDz0ez2o91K5f2r77uhnQ59t75lk"
/**
 * 获取
 * @returns 
 */
export async function getSealToken() {
    return await sealAxios.get(`${signUrl}/oauth/token?clientId=${config.sealClientId}&clientSecret=${config.sealClientSecret}&type=client_credentials`, {
        removeToken: true
    })
}

/**
 * 自由签名
 * @param {*} access_token 由 getSealToken 调用后返回的 access_token
 * @param {*} sealConfig 应该包含 file 字段值为要签名文件的 base64 格式内容
 * @returns 
 */
export async function seal(access_token, sealConfig, sealOffset) {
    if (sealConfig.file && sealConfig.file.indexOf('data:application/pdf;base64,') === 0) {
        sealConfig.file = sealConfig.file.slice(28)
    }
    const sealNetConfig = getSeal();
    let outUserId = config.outUserId;
    let sealId = config.sealId;
    let mac = config.mac;
    let sealKey = config.sealKey;
    if (sealNetConfig) {
        if (sealNetConfig.out_user_id) {
            outUserId = sealNetConfig.out_user_id;
        }
        if (sealNetConfig.seal_id) {
            sealId = sealNetConfig.seal_id;
        }
        if (sealNetConfig.mac) {
            mac = sealNetConfig.mac;
        }
        if (sealNetConfig.seal_key) {
            sealKey = sealNetConfig.seal_key;
        }
    }
    // http://119.84.246.34:7021/forward/b00cf30eb0f842ebb45a2677b70a7aa5/
    const params = {
        "userId":"",
        "timestamp": new Date().getTime(),//1635067293216,
        "outUserId": outUserId,
        "title":"123",
        "siteId":10000,
        "positionUnitType":1,
        "signatoriesList":[{
            "page":1,
            "sealId": sealId,
            ...sealOffset,
        }],
        "sealKey": sealKey,
        "mac": mac,
        ...sealConfig
    };
    const res = await sealAxios.post(`${signUrl}/forward/b00cf30eb0f842ebb45a2677b70a7aa5/${access_token}`, params);
    return res;
}

/**
 * 下载已经签名后的文件
 * @param {*} access_token 由 getSealToken 调用后返回的 access_token
 * @param {*} params 包含 seal 签名方法调用成功后返回的 documentPath
 * @returns 
 */
export async function downloadSealedFile(access_token, params = {}) {
    return await signAxios.get(`${signUrl}/forward/8024e7c251aa49fca0e5da41613da80f/${access_token}`, {
        removeToken: true,
        responseType: 'arraybuffer',
        params: {
            siteId: 10000,
            ...params
        }
    })
}

export async function sealFile(base64File, sealOffset = {
    "x": "150.00",
    "y": "160.00",
}) {
    const tokenData = await getSealToken()
    const signData = await seal(tokenData.data.data.access_token, {
        file: base64File
    }, sealOffset)
    const downloadData = await downloadSealedFile(tokenData.data.data.access_token, {
        documentPath: signData.data.data[0].layoutPath
    })
    return downloadData
}

// 签名相关接口
// export const signClientId = '34325f270ac3e99650f05efa22a0c41b'
// export const signClientSecret = 'o2pG99EDb86YS612fp8au16ttbmX7O152054'
// export const signThirdBizId = ''
/**
 * 获取签名 access_token
 * @returns 
 */
 export async function getSignTokenStep1() {
    return await signAxios.get(`${signUrl}/oauth/token?clientId=${config.signClientId}&clientSecret=${config.signClientSecret}&type=client_credentials`, {
        removeToken: true,
    })
}

export async function getSignTokenStep2(access_token) {
    const userInfo = getInfo();
    // console.log(`token = ${token}`);
    // console.log(`userInfoUrl = ${config.userInfoUrl}`);
    return await signAxios.post(`${signUrl}/forward/142c0cc60bc642e2a46ac74ce6c3bc3d/${access_token}`, qs.stringify({
        grant_type: "aos_exchange_token",
        clientToken: userInfo.uid,
        userInfoUrl: config.userInfoUrl,
    }),{
        removeToken: true,
        headers: {
            Authorization: 'Basic Slc1WmNJZDE2Mjc4NzU3MzA3Njk6dm1CelA0dDE2Mjc4NzU3MzA3Njk=',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
    })
}

export async function downloadSignedFile(id) {
    return await signAxios.get(`${config.downloadSignedFileUrl}/paas-api/gateway/paas-file-storage/metadata/files/${id}`, {
        contentType: 'application/x-www-form-urlencoded',
        responseType: 'arraybuffer',
        headers: {
            Authorization: `Bearer ${signToken.access_token}`
        }
    })
}

/**
 * 获取签字的 access_token
 * @returns streamData
 */
export async function getRealSignToken() {
    const step1Data = await getSignTokenStep1()
    let step2Data
    try {
        step2Data = await getSignTokenStep2(step1Data.data.data.access_token)
    } catch (error) {
        if (error && error.response && error.response.status == 401) {
            Toast('登录超时，请重新登录');
            logout();
            location.reload();
        }
    }
    return step2Data
}

export function getMaxDateInMonth(year, month){
    var d = new Date(year, month, 0);
    return d.getDate();
}
