import { headerOptions } from '@/config'
import { isObject } from '@vue/shared'
import { getToken } from './auth'

/**
 * @description 获取元素节点信息（在组件中的元素必须要传ctx）
 * @param  { String } selector 选择器 '.app' | '#app'
 * @param  { Boolean } all 是否多选
 * @param  { ctx } context 当前组件实例
 */
export const getRect = (selector: string, all = false, context?: any) => {
    return new Promise((resolve, reject) => {
        let qurey = uni.createSelectorQuery()
        if (context) {
            qurey = uni.createSelectorQuery().in(context)
        }
        qurey[all ? 'selectAll' : 'select'](selector)
            .boundingClientRect(function (rect) {
                if (all && Array.isArray(rect) && rect.length) {
                    return resolve(rect)
                }
                if (!all && rect) {
                    return resolve(rect)
                }
                reject('找不到元素')
            })
            .exec()
    })
}

/**
 * @description 获取当前页面实例
 */
export function currentPage() {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    return currentPage || {}
}

/**
 * @description 后台选择链接专用跳转
 */
interface Link {
    path: string
    name?: string
    type: string
    isTab: boolean
    query?: Record<string, any>
}

export enum LinkTypeEnum {
    'SHOP_PAGES' = 'shop',
    'CUSTOM_LINK' = 'custom'
}

export function navigateTo(link: Link, navigateType: 'navigateTo' | 'reLaunch' = 'navigateTo') {
    const url = link.query ? `${link.path}?${objectToQuery(link.query)}` : link.path
    navigateType == 'navigateTo' && uni.navigateTo({ url })
    navigateType == 'reLaunch' && uni.reLaunch({ url })
}

/**
 * @description 是否为空
 * @param {unknown} value
 * @return {Boolean}
 */
export const isEmpty = (value: unknown) => {
    return value == null && typeof value == 'undefined'
}

/**
 * @description 显示消息提示框。
 * @param  { String } title 弹出内容
 * @param  { Number } duration 延时多少毫秒
 */
export const toast = (title: string | number | null, duration = 1000) => {
    uni.showToast({
        title: title,
        duration: duration,
        icon: 'none'
    })
}

/**
 * @description 对象格式化为Query语法
 * @param { Object } params
 * @return {string} Query语法
 */
export function objectToQuery(params: Record<string, any>): string {
    let query = ''
    for (const props of Object.keys(params)) {
        const value = params[props]
        const part = encodeURIComponent(props) + '='
        if (!isEmpty(value)) {
            console.log('objectToQuery', encodeURIComponent(props), isObject(value))
            if (isObject(value)) {
                for (const key of Object.keys(value)) {
                    if (!isEmpty(value[key])) {
                        const params = props + '[' + key + ']'
                        const subPart = encodeURIComponent(params) + '='
                        query += subPart + encodeURIComponent(value[key]) + '&'
                    }
                }
            } else {
                query += part + encodeURIComponent(value) + '&'
            }
        }
    }
    return query.slice(0, -1)
}
/**
 * @description 上传图片
 * @param  { String } path 选择的本地地址
 */
export function uploadFile(path: any) {
    return new Promise((resolve, reject) => {
        const token = getToken()
        uni.uploadFile({
            url: `${import.meta.env.VITE_APP_BASE_URL}/${headerOptions.urlPrefix}/upload/image`,
            filePath: path,
            name: 'file',
            header: {
                token
            },
            fileType: 'image',
            success: res => {
                console.log('uploadFile res ==> ', res)
                const data = JSON.parse(res.data)
                console.log('data.code', data.code)
                if (data.code == 200) {
                    resolve(data.data)
                } else {
                    reject()
                }
            },
            fail: err => {
                console.log(err)
                reject()
            }
        })
    })
}

// 清除本地缓存
export const removeStorageData = (key: string) => {
    uni.removeStorage({
        key,
        success: res => {
            // console.log('清除成功', res)
        }
    })
}

/**
 * @description 组合异步任务
 * @param  { string } task 异步任务
 */
export function series(...task: Array<(_arg: any) => any>) {
    return function (): Promise<any> {
        return new Promise((resolve, reject) => {
            const iteratorTask = task.values()
            const next = (res?: any) => {
                const nextTask = iteratorTask.next()
                if (nextTask.done) {
                    resolve(res)
                } else {
                    Promise.resolve(nextTask.value(res))
                        .then(next)
                        .catch(() => {
                            setTimeout(() => {
                                reject()
                            }, 1000)
                        })
                }
            }
            next()
        })
    }
}

/**
 * @description 添加单位
 * @param {String | Number} value 值 100
 * @param {String} unit 单位 px em rem
 */
export const addUnit = (value: string | number, unit = 'rpx') => {
    return !Object.is(Number(value), NaN) ? `${value}${unit}` : value
}

/**添加金额符号 */
export function joinSuffix(value: number, suffix = '元') {
    return `${value}${suffix}`
}
/**转换日期 */
export function convertChineseMonthToDate(chineseMonth: string) {
    const regex = /(\d{4})年(\d{1,2})月/
    const matches = chineseMonth.match(regex)

    if (matches && matches.length === 3) {
        const year = matches[1]
        const month = matches[2].padStart(2, '0')
        return `${year}-${month}`
    } else {
        return ''
    }
}
/**金额千分位并保留2位小数 */
export function formatMoney(amount: any) {
    const fixedAmount = parseFloat(amount).toFixed(2)
    return amount && amount !== 0
        ? fixedAmount.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
        : amount === 0
        ? 0
        : '--'
}

/**判空 */
export function formatEmpty(value: any) {
    return value ?? '--'
}
/**设置单位 */
export function setUnit(value: any, unit: string) {
    return value || value === 0 ? `${value}${unit}` : '--'
}

/**路由跳转 */
export function router(url: string) {
    uni.navigateTo({ url })
}

/**转换时间格式 */
export function formatDate(datetime: string | any) {
    if (!datetime) return '--'
    const date = new Date(parseInt(datetime) * 1000)
    const year = date.getFullYear(),
        month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1,
        day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
        hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
        min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
        sec = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec
}

export function formatString(input) {
    const processNumber = numStr => {
        if (!numStr.includes('.')) return numStr

        // 分割整数和小数部分（处理 .00 和 20. 等情况）
        const parts = numStr.split('.', 2)
        let [intPart, decPart] = parts

        // 处理类似 ".00" 的情况
        intPart = intPart || '0'

        // 处理小数部分全零或无小数部分的情况
        if (!decPart || decPart.trimEnd().replace(/^0+$/, '') === '') {
            return intPart
        }

        // 去除末尾零并处理格式问题
        const strippedDec = decPart.trimEnd().replace(/^0+$/, '')
        const result = `${intPart}.${strippedDec}`

        // 处理特殊情况
        if (strippedDec === '') return intPart // 123.000 → 123
        if (result.endsWith('.')) return intPart // 123. → 123
        if (result.startsWith('.') && strippedDec) return `0${result}` // .55 → 0.55

        return result
    }

    if (!input) return
    const parts = input.split('-', 2)
    if (parts.length !== 2) return input

    const left = processNumber(parts[0])
    const right = processNumber(parts[1])

    return `${left}-${right}`
}
