import { queryResultLoadingAndInfo } from "@/common/methods/request/resultInfo";
import { QueryAccMgrLoginUser } from "@/services/go/ermcp/account";
import { ErmcpLoginUser, ErmcpLoginUserEx } from "@/services/go/ermcp/account/interface";
import { Ref, ref } from "vue";

/**
 * 获取(业务账户, 交易账户, 管理账户)
 * 因没有数据更新推送，为了防止新增的时候，导致数据不能及时更新，故每次进入页面都请求一次数据
 * @param loading
 * @param type 查询类型 1-业务账户 2-交易账户 3-管理账户
 * @param isFilter 是否过滤.false，不过滤，true: 过滤正常账号数据，
 * @returns
 */
export function handlerManagerList(loading: Ref<boolean>, type: 1 | 2 | 3, isFilter = false) {
    const tableList = ref<ErmcpLoginUserEx[]>([]);
    function queryTable(): Promise<ErmcpLoginUserEx[]> {
        return queryResultLoadingAndInfo(QueryAccMgrLoginUser, loading, type)
            .then(res => {
                const result = isFilter ? res.filter((e: ErmcpLoginUserEx) => e.accountstatus === 4) : res
                tableList.value = result
                return result
            })
    }
    /**
     * 根据code 查找业务员、跟单员对应的名字
     * @param code
     * @returns
     */
    function findManagerName(id: number, arr?: ErmcpLoginUserEx[]) {
        let result = '--'
        const temp = arr ? arr : tableList.value
        temp.forEach(el => {
            el.userlist.forEach(e => {
                const { accountname, logincode, userid } = e
                if (userid === id) {
                    result = `${accountname}-${logincode}`
                }
            })
        })
        return result
    }
    /**
     * 获取业务员、跟单员
     * @param roletype '22':业务员 '23':跟单员
     * @returns
     */
    function getBusinesserOrMerchandiser(roletype: '22' | '23', isFilter = false): ErmcpLoginUser[] {
        const result: ErmcpLoginUser[] = []
        tableList.value.forEach(el => {
            if (el.roleid === Number(roletype)) {
                el.userlist.forEach(e => {
                    if (isFilter) {
                        if (e.loginstatus === 1) { // 过滤正常数据
                            result.push(e)
                        }
                    } else {// 不进行数据过滤
                        result.push(e)
                    }
                })
            }
        })
        return result
    }

    return { tableList, queryTable, findManagerName, getBusinesserOrMerchandiser }
}