/**
 * 字典 util
 */
import req from '@/request'
import qs from 'qs'
const portal = window.context.portal
const headers = {
    'Content-type': 'application/x-www-form-urlencoded'
}
/**
 * 获取字典数组
 * @param dictCode 字典Code
 * @return List<Map>
 */
function getDictItemsFromCache(dictCode) {
    if (!dictCode) {
        return '字典Code不能为空!';
    }
    if (sessionStorage.getItem('dict_data')) {
        let dict_data = JSON.parse(sessionStorage.getItem('dict_data'))
        if (dict_data[dictCode]) {
            let distItem = dict_data[dictCode]
            // // 格式使用hotent的，key 是值  value 是显示值
            // distItem.forEach(item=>{
            //     item.key = item.value
            //     item.value = item.name
            // })
            return distItem
        }
    }
}
/**
 * 字典值替换文本通用方法
 * @param dictOptions  字典数组
 * @param text  字典值
 * @return String
 */
function filterDictText(dictOptions, text) {
    // --update-begin----author:sunjianlei---date:20200323------for: 字典翻译 text 允许逗号分隔 ---
    if (text != null && dictOptions instanceof Array) {
        let result = []
        // 允许多个逗号分隔
        let splitText = text.toString().trim().split(',')
        for (let txt of splitText) {
            let dictText = txt
            for (let dictItem of dictOptions) {
                if (txt === dictItem.value.toString()) {
                    dictText = dictItem.text
                    break
                }
            }
            result.push(dictText)
        }
        return result.join(',')
    }
    return text
    // --update-end----author:sunjianlei---date:20200323------for: 字典翻译 text 允许逗号分隔 ---
}

/**
 * 字典值替换文本通用方法(多选)
 * @param dictOptions  字典数组
 * @param text  字典值
 * @return String
 */
function filterMultiDictText(dictOptions, text) {
    //js “!text” 认为0为空，所以做提前处理
    if (text === 0 || text === '0') {
        if (dictOptions) {
            for (let dictItem of dictOptions) {
                if (text == dictItem.value) {
                    return dictItem.text
                }
            }
        }
    }

    if (!text || text == 'null' || !dictOptions || dictOptions.length == 0) {
        return ""
    }
    let re = "";
    text = text.toString()
    let arr = text.split(",")
    dictOptions.forEach(function (option) {
        if (option) {
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] === option.value) {
                    re += option.text + ",";
                    break;
                }
            }
        }
    });
    if (re == "") {
        return text;
    }
    return re.substring(0, re.length - 1);
}

/**
 * 翻译字段值对应的文本
 * @param children
 * @returns string
 */
function filterDictTextByCache(dictCode, key) {
    if (key == null || key.length == 0) {
        return;
    }
    if (!dictCode) {
        return '字典Code不能为空!';
    }
    //优先从缓存中读取字典配置
    if (this.getDictItemsFromCache(dictCode)) {
        let item = this.getDictItemsFromCache(dictCode).filter(t => t["value"] == key)
        if (item && item.length > 0) {
            return item[0]["text"]
        }
    }
}
/** 通过code获取字典数组 */
function getDictItems(dictCode, params) {
    //优先从缓存中读取字典配置
    if (this.getDictItemsFromCache(dictCode)) {
        let desformDictItems = this.getDictItemsFromCache(dictCode).map(item => ({ ...item, label: item.text }))
        return desformDictItems;
    }
}
/** 通过code获取字典数组 */
async function getDictItemsAsync(dictCode, params) {
    //优先从缓存中读取字典配置
    if (this.getDictItemsFromCache(dictCode)) {
        let desformDictItems = this.getDictItemsFromCache(dictCode).map(item => ({ ...item, label: item.text }))
        return desformDictItems;
    }

    //缓存中没有，就请求后台
    return await ajaxGetDictItems_(dictCode).then(({ success, result }) => {
        if (success) {
            let res = result.map(item => ({ ...item, label: item.text }))
            console.log('------- 从DB中获取到了字典-------dictCode : ', dictCode, res)
            return Promise.resolve(res)
        } else {
            console.error('getDictItems error: : ', res)
            return Promise.resolve([])
        }
    }).catch((res) => {
        console.error('getDictItems error: ', res)
        return Promise.resolve([])
    })
}

function ajaxGetDictItems_(code) {
    let data = qs.stringify({
        codes: code
    })
    return new Promise((reslove, reject) => {
        req.request({
            method: 'post',
            url: portal + '/sys/sysDictionary/v1/queryDictItemsByCode',
            data,
            headers
        }).then(res => {
            reslove(res.data)
        }).catch((err) => {
            reject(err)
        })
    })
}
export default {
    getDictItemsFromCache,
    filterDictText,
    filterMultiDictText,
    filterDictTextByCache,
    getDictItems,
    getDictItemsAsync
}
