import { QueryQuoteDayRsp } from '@/services/go/quote/interface';
import { addSubscribeQuotation, removeSubscribeQuotation } from '@/services/socket/quota';
import TimerUtils from '@/utils/timer/timerUtil';
import { v4 } from 'uuid';
import { onBeforeUnmount, onMounted, Ref, ref, watchEffect } from "vue";

/**
 * 处理行情按需订阅
 * @param tableList 全部表格数据
 * @param codeKey 需要订阅商品code对应的key
 * @param itemTableHeight 表格每一行的高度
 * @param selector 当前的滚动区域的选择器
 */
export function handleSubcriteOnDemandQuote<T extends object>(tableList: Ref<T[]>, codeKey = 'goodscode', itemTableHeight = 31, selector = '.ant-table-body') {
    const beforeScrollTop = ref<number>(0)
    const uuid = v4();
    onMounted(() => {
        listenSrcoll(document.querySelector(selector)!)
    });
    onBeforeUnmount(() => {
        removeSubscribeQuotation(uuid);
        TimerUtils.clearTimeout('subscribeQuote')
    })
    // 第一次自动订阅当前可视区域的数据
    const stop = watchEffect(() => {
        const len = tableList.value.length
        if (len) {
            const end = len > 16 ? 16 : len;
            subscribeAction(0, end)
        }
    })
    function listenSrcoll(ele: Element) {
        ele.addEventListener('scroll', (event: any) => {
            stop && stop()
            debounceSroll(event)
        }, true)
    }
    // 判断滚动方向
    function srollDrection(event: any) {
        const { scrollTop, offsetHeight } = event.target
        const diffSrollTop = scrollTop - beforeScrollTop.value
        if (diffSrollTop === 0) {
            // 横向滚动
            return
        } else if (diffSrollTop > 0) {
            // 向下滚动
            caclcuteSubcribeNum(scrollTop, offsetHeight)
        } else {
            // 向上滚动
            caclcuteSubcribeNum(scrollTop, offsetHeight)
        }
        beforeScrollTop.value = scrollTop
    }
    /**
     *
     * @param scrollTop 当前滚动条所处的位置
     * @param offsetHeight 当前滚动范围的可视区域的高度
     */
    function caclcuteSubcribeNum(scrollTop: number, offsetHeight: number) {
        // 可视区域的列表行数
        const rowNum = Math.ceil(offsetHeight / itemTableHeight) - 1;
        const tableIndex = scrollTop < itemTableHeight ? 0 : Math.ceil(scrollTop / itemTableHeight)
        // 开始订阅
        subscribeAction(tableIndex, tableIndex + rowNum)
    }
    // 防抖
    function debounceSroll(event: any) {
        TimerUtils.clearTimeout('subscribeQuote')
        TimerUtils.setTimeout(() => {
            srollDrection(event)
        }, 200, 'subscribeQuote')
    }
    // 开始订阅
    function subscribeAction(start: number, end: number) {
        removeSubscribeQuotation(uuid);
        const result: Array<{ exchangeCode: 250, goodsCode: string, subState: 0 }> = []
        for (let i = start; i < end; i++) {
            const obj = tableList.value[i] as unknown as any
            if (Reflect.has(obj, codeKey)) {
                result.push({ exchangeCode: 250, goodsCode: obj[codeKey], subState: 0 })
            } else {
                console.warn(`订阅商品的code对应的key${codeKey}不存在，请手动传入！`)
            }

        }
        console.log('开始订阅', result)
        addSubscribeQuotation(uuid, result);
    }
}

// 处理行情订阅，注意这里不是按需订阅
export function handleSubcriteQuote() {
    const uuid = v4();
    function subscribeAction(goodscode: string[]) {
        removeSubscribeQuotation(uuid);
        const goodsList = goodscode.map(el => {
            return { exchangeCode: 250, goodsCode: el, subState: 0 };
        })
        //  行情订阅
        addSubscribeQuotation(uuid, goodsList);
    }
    onBeforeUnmount(() => {
        removeSubscribeQuotation(uuid);
    });
    return { subscribeAction }
}

function isPrice(price1: number | string, price2: number | string) {
    if (price2 && price2 !== '--' && price1 && price1 !== '--') {
        return true
    } else {
        return false
    }
}

/**
 * 处理行情价格颜色
 * @param price1
 * @param price2
 * @returns
 */
export function handleQuotePriceColor(record: QueryQuoteDayRsp) {
    const { presettle, bid } = record
    let result = ''
    if (isPrice(bid, presettle)) {
        if (bid === presettle) {
            result = ''
        } else if (bid > presettle) {
            result = 'up-quote-color'
        } else {
            result = 'down-quote-color'
        }
    }
    return result
}

// 涨跌 最新价 - 昨结价
export function quoteChange(record: QueryQuoteDayRsp, decimalplace = 2) {
    const { presettle, last } = record
    let result = '--'
    if (isPrice(last, presettle)) {
        result = (last - presettle).toFixed(decimalplace)
    }
    return result
}

// 幅度（最新价 - 昨结价） / 100 %
export function quoteAmplitude(record: QueryQuoteDayRsp, decimalplace = 2) {
    const result = quoteChange(record, decimalplace)
    return result === '--' ? '--' : (+result / 100).toFixed(decimalplace) + '%'
}

// (最高价 - 最低价 ) / 最新价  * 100 %
export function quoteAmplituOfVibration(record: QueryQuoteDayRsp, decimalplace = 2) {
    const { highest, lowest, last } = record
    let result = '--'
    if (isPrice(highest, lowest)) {
        if (last && (last as unknown as any) !== '--') {
            result = ((highest - lowest) / last * 100).toFixed(decimalplace) + '%'
        }
    }
    return result
}