/**
 * 对象转换为url参数
 * @param {object} params 当前页面的参数对象 {}
 * 
 *  使用方法
    import { convertUrlParams } from '@/utils/share'
    let params = convertUrlParams({ id: 1, name: '张三', age: 18 })
    uni.navigateTo({
        url: `/xxx/xxx/xxxx${params}`
    })
 */
export const convertUrlParams = (params = {}) => {
    let urlParamsStr = '?'
    for (const key in params) {
        if (Object.prototype.hasOwnProperty.call(params, key)) urlParamsStr += `&${key}=${params[key]}`
    }
    return urlParamsStr
}


/**
* url转换为对象参数
* @param {object} params 当前页面的参数 ''
* 
*  使用方法
import { convertObjParams } from '@/utils/share'
let params = convertObjParams('id=1&name=张三&age=18')
*/
export const convertObjParams = (params = '') => {
    let obj = {}
    params.split('&').forEach(item => {
        let [key, value] = item.split('=')
        obj[key] = value
    })
    return obj
}



/**
 * 分享函数
 * setShareMsg({shareTitle,shareImg,sharePath,shareParams}) 设置分享信息
 * @param {string} shareTitle 分享标题
 * @param {string} shareImg 分享图片
 * @param {string} sharePath 分享链接
 * @param {object} shareParams 分享参数
  
 *  使用方法
    import { setShareMsg } from '@/utils/share'
    onShareAppMessage(() => {
        return setShareMsg({
            shareTitle: '分享标题',
            shareImg: 'https://www.baidu.com/img/flexible/logo/pc/result.png',
            sharePath: '/pages/card/card',
            shareParams: {
                id: 1,
                name: '张三',
                age: 18
            }
        })
    })

  * 获取分享参数
    onLoad((option) => {
        const { id, name, age } = (Object.keys(option).length ? option : false) || getApp().globalData.shareParams || {}
        console.log(id, name, age)
    })
 */
export const setShareMsg = ({ shareTitle = '我分享了一个小程序', shareImg = '', sharePath = '', shareParams = {} }) => {
    const params = convertUrlParams({ sharePath, ...shareParams })
    return {
        title: shareTitle,
        imageUrl: shareImg,
        path: `/pages/index/welcome${params}`
    }
}

