import {
    LOGO_DEFAULT,
    LOGO_DEFAULT1,
    JINGAN_LOGO,
    PUDONG_LOGO,
    BEIJING_LOGO,
    HANGZHOU_LOGO,
    ENV_LIST,
    APPID_MAP,
    APPID,
    SOURCE_KEY,
    SHENYANG_LOGO,
    TIANJIN_LOGO,
    SHENZHEN_LOGO,
} from '@/constants.js'
import CacheTool from '@/utils/cache-tool.js'
import uni from './uniHooks'

export function checkEmail(str) {
    const target = removeInvalidChar(str)
    const reg = /^[a-z0-9A-Z]+[-|a-z0-9A-Z._]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-z]{2,}$/
    return reg.test(target)
}

export function checkIdNumber(str) {
    const target = removeInvalidChar(str)
    const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return reg.test(target)
}

export function checkPhoneNumber(str) {
    const target = removeInvalidChar(str)
    const reg = /^1(3|4|5|7|8)\d{9}$/;
    return reg.test(target)
}

export function removeInvalidChar(str) {
    return str.replace(/\s|&nbsp;/g, '')
}

export function getUrl(url, prefix = '') {
    if (!url || url.trim() == '') {
        return '';
    }
    if (url.indexOf('http') == -1) {
        return prefix + url;
    }
    return url;
}

export function getCustTypeId(mallid) {
    const {JINGAN_LBS_ID, PUDONG_LBS_ID} = CacheTool.getCurEnvConst();
    if (mallid === JINGAN_LBS_ID) {
        return 1;
    } else if (mallid === PUDONG_LBS_ID) {
        return 2;
    } else {
        return 0;
    }
}

export function getLogoByBrand(brandInfo, groupId = null, mallid = null) {
    // KerryOn brandId
    if (!groupId) {
        groupId = uni?.getStorageSync("groupId") || {}
    }
    if (!mallid) {
        mallid = uni.getStorageSync("mallid")
    }
    // if (!groupId?.trim() && !mallid.trim()) {
    //     if (isKOMiniApp()) {
    //         return LOGO_DEFAULT1;
    //     } else {
    //         return LOGO_DEFAULT;
    //     }
    // }
    // kerryOn用固定logo-杭州用杭州的logo
    const {
        KERRY_ON_BRAND_ID,
        BEIJING_LBS_ID,
        JINGAN_LBS_ID,
        PUDONG_LBS_ID,
        PIC_URL,
        KERRY_HZ_BRAND_ID,
        HANGZHOU_LBS_ID,
        SHENYANG_LBS_ID,
        TIANJIN_LBS_ID,
        SHENZHEN_LBS_ID,
        SHENZHEN_BRAND_ID,
    } = CacheTool.getCurEnvConst();

    // 解决各个商场需要定制化logo的问题
    if (KERRY_ON_BRAND_ID == groupId) {
        if (mallid == BEIJING_LBS_ID) {
            return PIC_URL + BEIJING_LOGO
        } else if (mallid == JINGAN_LBS_ID) {
            return PIC_URL + JINGAN_LOGO
        } else if (mallid == PUDONG_LBS_ID) {
            return PIC_URL + PUDONG_LOGO
        }
    } else if (KERRY_HZ_BRAND_ID == groupId) {
        if (mallid == HANGZHOU_LBS_ID) {
            return PIC_URL + HANGZHOU_LOGO
        }
    } else if (SHENZHEN_BRAND_ID == groupId) {
        if (mallid == SHENZHEN_LBS_ID) {
            return PIC_URL + SHENZHEN_LOGO
        }
    } else {
        if (brandInfo && brandInfo.logo) {
            return brandInfo.logo;
        } else if (SHENYANG_LBS_ID == mallid) {
            return PIC_URL + SHENYANG_LOGO
        } else if (TIANJIN_LBS_ID == mallid) {
            return PIC_URL + TIANJIN_LOGO
        } else {
            if (isKOMiniApp()) {
                return LOGO_DEFAULT1;
            } else {
                return LOGO_DEFAULT;
            }
        }
    }
}
export function compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
        v1.push('0')
    }
    while (v2.length < len) {
        v2.push('0')
    }

    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i])
        const num2 = parseInt(v2[i])

        if (num1 > num2) {
            return 1
        } else if (num1 < num2) {
            return -1
        }
    }

    return 0
}

/**
 * 当前小程序是否是KO小程序
 */
export function isKOMiniApp() {
    const {kerryMall} = APPID_MAP;
    if (APPID == kerryMall) {
        // KO小程序
        return true;
    } else {
        // crm小程序
        return false;
    }
}

/**
 * 当前小程序是否是KO小程序，商场是否是KO的商场
 * @param {Object} curMallid
 */
export function isKOMallid(curMallid) {
    const curEnvConst = CacheTool.getCurEnvConst();
    if (!curEnvConst) {
        console.error("===>未获取到正确的环境变量")
        return false;
    }
    const {PUDONG_LBS_ID, JINGAN_LBS_ID, BEIJING_LBS_ID} = curEnvConst;
    // KO小程序
    if (curMallid != PUDONG_LBS_ID
        && curMallid != JINGAN_LBS_ID
        && curMallid != BEIJING_LBS_ID) {
        return false;
    } else {
        return true;
    }
}

export function isKOBrand(curGroupId) {
    const curEnvConst = CacheTool.getCurEnvConst();
    if (!curEnvConst) {
        console.error("===>未获取到正确的环境变量")
        return false;
    }
    const {KERRY_ON_BRAND_ID} = curEnvConst;
    // KO小程序
    if (curGroupId == KERRY_ON_BRAND_ID) {
        return true;
    } else {
        return false;
    }
}

export function filterLbsByKO(lbsList) {
    if (!lbsList || !lbsList.length || lbsList.length == 0) {
        console.warn("===>lbsList is empty!");
        return [];
    }
    if (isKOMiniApp()) {
        lbsList = lbsList.filter(e => isKOBrand(e.brand.id));
        return lbsList;
    } else {
        return lbsList;
    }
}

/**
 * 当前商场是否属于当前appid
 * @param {Object} curMallid
 */
export function isCurrentAppMallid(curMallid) {
    if (!curMallid) {
        console.error("===>curMallid is null");
        return
    }
    const curEnvConst = CacheTool.getCurEnvConst();
    const {kerryLink, kerryMall} = APPID_MAP;
    const {PUDONG_LBS_ID, JINGAN_LBS_ID, BEIJING_LBS_ID, HANGZHOU_LBS_ID} = curEnvConst;
    if (APPID == kerryLink) {
        if (curMallid == PUDONG_LBS_ID
            || curMallid == JINGAN_LBS_ID
            || curMallid == BEIJING_LBS_ID) {
            return false;
        } else {
            return true;
        }
    } else if (APPID == kerryMall) {
        if (curMallid != PUDONG_LBS_ID
            && curMallid != JINGAN_LBS_ID
            && curMallid != BEIJING_LBS_ID) {
            return false;
        } else {
            return true;
        }
    } else {
        console.warn("===>isCurrentAppMallid 没有任何商场与当前appid匹配")
        return false;
    }
}

export function buildShareSource(type, id) {
    let utm_function = type;
    if (id) {
        utm_function = type + id;
    }

    // const kipUserId = uni.getStorageSync("kipMember")?.id || null;
    const kipUserId = '8888888'
    const options_query = uni.getStorageSync("options_query");
    const mallid = uni.getStorageSync("mallid");
    let params = `channel=${APPID}&utm_channel=${APPID}&utm_method=sh&utm_source=sh_wechat&utm_function=${utm_function}&utm_lbs=${mallid}`;
    if (kipUserId) {
        params += `&utm_user=${kipUserId}`
    }
    return params;
}
export function getUTMSource() {
    // 返回的参数（只有utm来源参数）
    let sourceObj = {}
    // 存储在storage中的参数(有其他参数)
    let miniAppOptionsQuery = uni.getStorageSync("options_query");
    // console.log(273, 'miniAppOptionsQuery', miniAppOptionsQuery)
    if (!miniAppOptionsQuery || JSON.stringify(miniAppOptionsQuery) == '{}') {
        // 直接进入的utm_lbs是空的
        // const mallid = uni.getStorageSync("mallid")
        const defaultOptionsQuery = {
            channel: APPID,
            utm_channel: APPID,
            utm_method: 'dr',
            // utm_lbs: mallid,
        }
        miniAppOptionsQuery = defaultOptionsQuery;
    }

    // 强制赋值当前渠道(channel)
    sourceObj.channel = APPID
    miniAppOptionsQuery.channel = APPID;
    // 只获取来源参数
    SOURCE_KEY.forEach(key => {
        const value = miniAppOptionsQuery[key]
        if (value && value.trim() != '') {
            sourceObj[key] = value;
        }
    })

    // 补偿机制：如果当前utm_lbs没有传值则使用原有参数中的mallid赋值
    if (!sourceObj.utm_lbs && miniAppOptionsQuery.mallid) {
        sourceObj.utm_lbs = miniAppOptionsQuery.mallid
    }

    // 重新放进storage中
    uni.setStorageSync("options_query", miniAppOptionsQuery);

    return sourceObj;
}

export function buildExtraData(params) {
    const miniAppOptionsQuery = uni.getStorageSync("options_query");
    return {...params, ...miniAppOptionsQuery};
}
/**
 * 当前mallid是否是当前环境商场的mallid
 * @param {当前mallid} curMallid
 * @param {constants.js文件中环境常量的key} cacheKey
 */
export function isCurMallidByEnvConstKey(curMallid, cacheKey) {
    if (!curMallid || curMallid.trim() == '') {
        return false;
    }
    if (!cacheKey || cacheKey.trim() == '') {
        return false;
    }
    const curEnvConst = CacheTool.getCurEnvConst();
    if (!curEnvConst) {
        console.error("===>未获取到正确的环境变量")
        return false;
    }
    return curMallid == curEnvConst[cacheKey];
}

export function isTianJinMallid(curMallid) {
    return isCurMallidByEnvConstKey(curMallid, 'TIANJIN_LBS_ID');
}

export function isBeiJingMallid(curMallid) {
    return isCurMallidByEnvConstKey(curMallid, 'BEIJING_LBS_ID');
}
//
// export default {
//     checkEmail,
//     checkIdNumber,
//     checkPhoneNumber,
//     getUrl,
//     getCustTypeId,
//     getLogoByBrand,
//     compareVersion,
//     isKOMiniApp,
//     isKOMallid,
//     filterLbsByKO,
//     isKOBrand,
//     isCurrentAppMallid,
//     buildShareSource,
//     getUTMSource,
//     buildExtraData,
//     isCurMallidByEnvConstKey,
//     isTianJinMallid,
//     isBeiJingMallid,
// }
