import { getDictDataApi } from "@/api/common";
import { useEnumStore } from "@/store/enum";
const { data, setEnumData, getEnumData } = useEnumStore();
/**
 * 根据类型获取EUM数据。
 * 该函数用于根据给定的类型从本地存储或服务器获取EUM数据。如果数据已在本地存储中，则直接返回；
 * 否则，从服务器获取数据，并将其存储在本地，然后返回。
 *
 * @param {string} type - 数据的类型。用于指定要获取的EUM数据的类型。
 * @returns {Promise} - 返回一个Promise对象，该对象在数据获取成功后解析为相应的数据。
 */
export const getEumData = type => {
    // const storage = getStorageSync(type);
    const storage = getEnumData(type);
    const codeToNumbers = data => {
        data.forEach(v => {
            v.code = Number(v.code);
        });
        return data;
    };
    return new Promise(resolve => {
        if (storage) {
            resolve(codeToNumbers(storage));
        } else {
            getDictDataApi([type]).then(res => {
                const data = res.data[type];
                // setStorageSync(type, data);
                setEnumData(type, data);
                resolve(codeToNumbers(data));
            });
        }
    });
};
export const getEnumText = async (type, code) => {
    const eumData = await getEumData(type);
    return eumData.find(item => item.code == code)?.text || "无";
};

export const getEnumText2 = async (type, codes) => {
    const eumData = await getEumData(type);
    // 使用 Array.prototype.map 和 .filter 方法来获取所有匹配项的 text
    const texts = eumData.filter(item => codes.includes(item.code)).map(item => item.text);

    // 将获取到的 text 数组合并成一个字符串，用 "|" 分割
    return texts.join("|") || "无";
};
/**
 * 将数据存储在本地存储空间中。
 * @param {string} key 要存储的数据的关键字，用于检索数据。
 * @param {*} data 要存储的具体数据，可以是各种数据类型。
 */
export const setStorageSync = (key, data) => {
    uni.setStorageSync(key, data);
};
export const getStorageSync = key => uni.getStorageSync(key);

// 路由跳转
export const navigateTo = (url, type = "navigateTo") => {
    if (!url) return;
    uni[type]({
        url: url
    });
};

export const formatTimestamp = (timestamp, formatString = "YYYY-MM-DD hh:mm:ss") => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    const hour = ("0" + date.getHours()).slice(-2);
    const minute = ("0" + date.getMinutes()).slice(-2);
    const second = ("0" + date.getSeconds()).slice(-2);

    // 替换格式字符串中的占位符
    return formatString
        .replace(/YYYY/g, year)
        .replace(/MM/g, month)
        .replace(/DD/g, day)
        .replace(/hh/g, hour)
        .replace(/mm/g, minute)
        .replace(/ss/g, second);
};

export const validateForm = (formData, requiredFields, type) => {
    const phoneRegex = /^1[3-9]\d{9}$/; // 正则表达式匹配中国大陆手机号码
    const fieldMapping = {
        jobTypeText: "职位类型",
        postitDesc: "职位描述",
        jobName: "职位名称",
        address: "工作地址",
        identityRequirement: "人员类别",
        educationRequirement: "学历",
        maxAgeRequirement: "年龄",
        contactPerson: "联系人",
        jobType: "职位类型",
        position: "职位",
        name: "名字",
        positionalTitle: "专业技术职称",
        professionalCertificates: "职业等级证书",
        specialCertificates: "特种作业证书",
        avatarPath: "头像",
        majorText: "专业"
    };
    for (const field of requiredFields) {
        const fieldValue = formData[field];
        if (field === "contactPhone" || field === "phone") {
            if (!formData[field] || !phoneRegex.test(formData[field])) {
                uni.showToast({
                    title: `请填写正确电话号码！`,
                    icon: "none",
                    duration: 2000
                });
                return false;
            }
        } else if (fieldValue === null || fieldValue === undefined || fieldValue === "") {
            // const title = fieldMapping[field] || (type === "post" ? "岗位信息" : "表单");
            const title = fieldMapping[field] || (type === "post" ? "相关信息" : "相关信息");
            uni.showToast({
                title: `请${type === "post" ? "完善" : "完善"}${title}！`,
                icon: "none",
                duration: 2000
            });

            return false;
        }
    }
    return true;
};
