import {ref, computed, Ref} from 'vue' import XEUtils from "xe-utils"; import {BizException, ExceptionEnum} from "@/utils/BizException"; import {stringIsBlank} from "@/utils/blank-utils"; declare type CodeType = keyof T & string | ((item: T) => string); function cyRefList(code: CodeType, errMsg: (item: T) => string = () => '请勿重复添加') { const list: Ref = ref([]) const watchFunc: Function[] = [] const codeIsFunction = typeof code === 'function' const codeKey = computed(() => { return XEUtils.eachAndReturnList(list.value, (item) => { if (codeIsFunction) { return code(item) } return item[code] }); }); function sendListening(items: any) { return new Promise(resolve => { watchFunc.forEach(item => item(items)) resolve(true) }) } const listProxy = { push: function (...items: T[]) { const msgList: string[] = [] items.forEach((item: T) => { let key: string; if (codeIsFunction) { key = code(item) } else { key = item[code] as string } if (stringIsBlank(key)) { BizException(ExceptionEnum.MESSAGE_ERROR, "没有找到唯一值"); } if (codeKey.value.includes(key)) { const msg = errMsg(item) msgList.push(msg) } }) if (msgList.length === 1) { BizException(ExceptionEnum.MESSAGE_ERROR, msgList[0]); } else if (msgList.length > 0) { BizException(ExceptionEnum.MESSAGE_HTML_ERROR, msgList.join("
")); } sendListening(items).then(r => { }); // @ts-ignore return list.value.push(...items) }, watchPush: function (cb: (value: T) => void) { const index = watchFunc.push(cb) function stop() { watchFunc.splice(index, 0) } return stop }, delIndex: function (index: number) { list.value.splice(index, 1); }, clear: function () { list.value = [] }, isEmpty() { return list.value === null || list.value.length === 0 }, emptyError(errorMsg = '请先选择数据') { if (this.isEmpty()) { BizException(ExceptionEnum.MESSAGE_ERROR, errorMsg) } }, forEach(cb: (item: T, index: number) => void) { for (let i = 0, len = list.value.length; i < len; i++) { const item = list.value[i] cb(item, i) } }, eachAndReturnList(iteration: (item: T, index: number) => any) { return XEUtils.eachAndReturnList(list, iteration) }, } return [list, listProxy] } export default cyRefList