import dayjs from "dayjs";
import {
	chineseToPinYin
} from '@/utils/pinyin.js'
import {
	selectDictLabel,
	toast
} from "@/utils/util.js";
import store from '@/store';

export const callFunction = function(action, data) {
	store.dispatch("app/getIsUseCallSystem", action).then(() => {
		if (data) {
			const {
				join,
				...params
			} = data;
			const keys = Object.keys(params);
			const strParams = keys.reduce((acc, cur) => {
				const str = `${cur} : "${params[cur]}"`;
				return acc ? acc + "," + str : str;
			}, "");
			if (join) {
				const joinkeys = Object.keys(join);
				const joinstr = joinkeys.reduce((acc, cur) => {
					const str = `${cur} : "${join[cur]}"`;
					return acc ? acc + "," + str : str;
				}, "");
				store.state.app.callSystem.evalJS(`window.$join={${joinstr}}`);
			};
			store.state.app.callSystem.evalJS(`${action}({${strParams}})`);
		} else {
			store.state.app.callSystem.evalJS(`${action}()`);
		}
	})
};

const common = {
	install(Vue) {
		Vue.prototype.$formatMoney = (val, zero = "") => {
			if (!val && val !== 0) return zero;
			// 统一用正数处理
			let num = Math.abs(val).toString();
			let decimals = '';
			const symbolStr = Number(val) < 0 ? "-" : "";
			// 判断是否有小数
			if (num.indexOf('.') > -1) {
				decimals = num.split('.')[1]
				num = num.split('.')[0]
			}
			let temp = ''
			let len = num.length
			if (len <= 3) {
				decimals ? temp = '.' + decimals : temp;
				return symbolStr + num + temp
			} else {
				let remainder = len % 3
				decimals ? temp = '.' + decimals : temp
				if (remainder > 0) { // 不是3的整数倍
					return symbolStr + num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g)
						.join(',') + temp
				} else { // 是3的整数倍
					return symbolStr + num.slice(0, len).match(/\d{3}/g).join(',') + temp
				}
			}
		}
		Vue.prototype.$avatar = (url) => {
			return require("@/static/case/icon-avatar.png")
			// return url ? url : require("@/static/case/icon-avatar.png")
		}
		Vue.prototype.$chineseToPinYin = chineseToPinYin;
		Vue.prototype.$dayjs = dayjs;

		Vue.prototype.$selectDictLabel = (dictType, value) => {
			return selectDictLabel(store.state.dict[dictType], value);
		}

		Vue.prototype.$makePhoneCall = (params) => {
			uni.makePhoneCall(params);
		}
		Vue.prototype.$toast = toast;

		Vue.prototype.$callFunction = callFunction;

		Vue.prototype.$showReal = function(type, telephone) {
			if(type == 1){
				if (telephone == null) {
					return "";
				}
				
				if (telephone.length < 7) {
					const phone = telephone.substring(1, telephone.length - 1)
					return telephone.replace(phone, '****')
				}
				
				const phone = telephone.substring(3, telephone.length - 4)
				const normal = telephone.replace(phone, '****');
				return normal;
			}else{
				return telephone;
			}
			
		}
	}
}
export default common;