/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
            // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

// 表单重置
export function resetForm(refName) {
    if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
    }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
    let search = params;
    search.params = typeof(search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
    dateRange = Array.isArray(dateRange) ? dateRange : [];
    if (typeof(propName) === 'undefined') {
        search.params['beginTime'] = dateRange[0];
        search.params['endTime'] = dateRange[1];
    } else {
        search.params['begin' + propName] = dateRange[0];
        search.params['end' + propName] = dateRange[1];
    }
    return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
    if (value === undefined) {
        return "";
    }
    var actions = [];
    Object.keys(datas).some((key) => {
        if (datas[key].value == ('' + value)) {
            actions.push(datas[key].label);
            return true;
        }
    })
    if (actions.length === 0) {
        actions.push(value);
    }
    return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
    if (value === undefined) {
        return "";
    }
    var actions = [];
    var currentSeparator = undefined === separator ? "," : separator;
    var temp = value.split(currentSeparator);
    Object.keys(value.split(currentSeparator)).some((val) => {
        var match = false;
        Object.keys(datas).some((key) => {
            if (datas[key].value == ('' + temp[val])) {
                actions.push(datas[key].label + currentSeparator);
                match = true;
            }
        })
        if (!match) {
            actions.push(temp[val] + currentSeparator);
        }
    })
    return actions.join('').substring(0, actions.join('').length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
    var args = arguments,
        flag = true,
        i = 1;
    str = str.replace(/%s/g, function() {
        var arg = args[i++];
        if (typeof arg === 'undefined') {
            flag = false;
            return '';
        }
        return arg;
    });
    return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
    if (!str || str == "undefined" || str == "null") {
        return "";
    }
    return str;
}

// 数据合并
export function mergeRecursive(source, target) {
    for (var p in target) {
        try {
            if (target[p].constructor == Object) {
                source[p] = mergeRecursive(source[p], target[p]);
            } else {
                source[p] = target[p];
            }
        } catch (e) {
            source[p] = target[p];
        }
    }
    return source;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
    let config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
    };

    var childrenListMap = {};
    var nodeIds = {};
    var tree = [];

    for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
    }

    for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
            tree.push(d);
        }
    }

    for (let t of tree) {
        adaptToChildrenList(t);
    }

    function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
                adaptToChildrenList(c);
            }
        }
    }
    return tree;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof(value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && typeof(value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}


// 返回项目路径
export function getNormalPath(p) {
    if (p.length === 0 || !p || p == 'undefined') {
        return p
    };
    let res = p.replace('//', '/')
    if (res[res.length - 1] === '/') {
        return res.slice(0, res.length - 1)
    }
    return res;
}

// 验证是否为blob格式
export async function blobValidate(data) {
    try {
        const text = await data.text();
        JSON.parse(text);
        return false;
    } catch (error) {
        return true;
    }
}

export function getfacilitiesdesname(key) {
    const namejson = {
      tz_id: { type: "text", des: "台账编号" },
      tz_road: { type: "text", des: "所在道路" },
      tz_ssly: { type: "text", des: "所属流域" },
      pics: { type: "img", des: "施工图纸" },
      tz_area_old: { type: "text", des: "区属（资料）" },
      tz_area_new: { type: "text", des: "区属（行政）" },
      tz_ss_name: { type: "text", des: "设施名称（工程资料名称）" },
      tz_ss_road: { type: "text", des: "现况路名" },
      tz_ss_pstz: { type: "text", des: "排水体制" },
      tz_pkbh: { type: "text", des: "排口编号" },
      tz_ss_road_se: { type: "text", des: "设施起止点（资料）" },
      tz_ss_road_start: { type: "text", des: "实际管线起点" },
      tz_ss_road_end: { type: "text", des: "实际管线终点" },
      tz_ss_river: { type: "text", des: "河道流域（排入水体）" },
      tz_gwly: { type: "text", des: "管网流域" },
      tz_pfk: { type: "text", des: "排河口（座）", des1: "排放口" },
      tz_xlymc: { type: "text", des: "小流域名称" },
      tz_ss_dn: { type: "number", des: "管径范围（mm）" },
      tz_ss_data_length: { type: "number", des: "运维设施长度(m)" },
      tz_ss_data_main_length: { type: "number", des: "主管长度（m）" },
      tz_ss_data_minor_length: { type: "number", des: "支管长度（m）" },
      tz_ss_data_jing: { type: "text", des: "检查井数量（座）" },
      tz_ss_data_ysk: { type: "text", des: "雨水口数量（座）" },
      tz_bz_total: { type: "text", des: "箅子数量（块）共计" },
      tz_bz_dan: {
        type: "text",
        des: "单箅（块）",
        des1: "箅子数量（块）单箅",
      },
      tz_bz_shuang: {
        type: "text",
        des: "双箅（块）",
        des1: "箅子数量（块）双箅",
      },
      tz_bz_san: {
        type: "text",
        des: "三箅（块）",
        des1: "箅子数量（块）三箅",
      },
      tz_bz_si: { type: "text", des: "四箅（块）", des1: "箅子数量（块）四箅" },
      tz_bz_duo: {
        type: "text",
        des: "多联箅（块）",
        des1: "箅子数量（块）多联箅",
      },
      tz_jgsj: { type: "text", des: "竣工时间（建设）" },
      tz_gjsj: { type: "text", des: "改建时间" },
      tz_yssj: { type: "text", des: "验收时间" },
      tz_ss_type: { type: "text", des: "管线类型（圆管、方沟、明渠）" },
      tz_ss_cz: {
        type: "text",
        des: "管线材质（混凝土、钢管、铸铁管、pvc、复合管等）",
      },
      tz_dlj: { type: "text", des: "跌落井（座）" },
      tz_jlj: { type: "text", des: "截流井（座）" },
      tz_dhx: { type: "text", des: "倒虹吸（座）" },
      tz_jsk: { type: "text", des: "进水口（是否有U型渠接入雨水管线等）" },
      tz_zm_type: { type: "text", des: "闸门类型" },
      tz_zm_material: { type: "text", des: "闸门材质" },
      tz_ss_info: { type: "text", des: "移交来源" },
      tz_ss_from: { type: "text", des: "移交单位" },
      tz_ss_time: { type: "text", des: "移交时间" },
      tz_ss_unit: { type: "text", des: "责任班组" },
      tz_jssj: { type: "text", des: "接收时间" },
      tz_ss_more: { type: "textarea", des: "备注" },
      tz_xfgj_xxgq: {
        type: "text",
        des: "细分管径 小型管渠 Φ＜DN600mm/截面积<0.283㎡",
      },
      tz_xfgj_zxgj: {
        type: "text",
        des: "细分管径 中型管径 DN600mm≤Φ≤DN1000mm/0.283㎡≤截面积≤0.785㎡",
      },
      tz_xfgj_dxgj: {
        type: "text",
        des: "细分管径 大型管径 DN1000mm＜Φ≤DN1500mm/0.785㎡＜截面积≤1.766㎡",
      },
      tz_xfgj_tdxgj: {
        type: "text",
        des: "细分管径 特大型管径 Φ> DN1500mm以上/截面积> 1.766㎡",
      },
    };
    return namejson[key] ? namejson[key] : "-";
}
