import type { Message } from './Message'
import type { PageBase } from './PageBase'
import type { ITradeHelper } from './ITradeHelper'
import type { TradeBusHelper } from './TradeBusHelper'
import type { TradeInfoHelper } from './TradeInfoHelper'
import type { TradeAPIsHelper } from './TradeAPIsHelper'
import type { TradeResourcesHelper } from './TradeResourcesHelper'

/**
 * 入口基类，包括Message和PageBase
 */
export class EntryBase implements ITradeHelper {
    #region 数据属性
    private _messageData: Message | null = null
    private _pageData: PageBase | null = null

    public get MessageData(): Message | null {
        return this._messageData
    }
    private set MessageData(value: Message | null) {
        this._messageData = value
    }

    public get PageData(): PageBase | null {
        return this._pageData
    }
    private set PageData(value: PageBase | null) {
        this._pageData = value
    }
    #endregion

    /**
     * 加载数据
     * @param page 
     * @param message 
     * @returns 
     */
    public LoadData(page: PageBase, message: Message): boolean {
        let flag = true
        
        // 检测参数变化
        if (page !== null && page === this.PageData) {
            if (message === this.MessageData || 
                (message.FileData === this.MessageData?.FileData && 
                 this.getDiffFields(message, this.MessageData).length === 0)) {
                flag = false // 参数与历史登记一致，未作修改
            }
        }
        
        this.PageData = page
        this.MessageData = message
        return this.OnLoadData(flag)
    }

    private getDiffFields(newMsg: Message, oldMsg: Message): string[] {
        const newFields = Object.keys(newMsg)
        const oldFields = Object.keys(oldMsg)
        return newFields.filter(key => newMsg[key] !== oldMsg[key])
    }

    /**
     * 加载数据时触发
     * @param changed 标识数据是否发生改变
     * @returns 
     */
    protected OnLoadData(changed: boolean): boolean {
        return true
    }

    #region ITradeHelper
    public get TradeBus(): TradeBusHelper {
        if (!this.PageData) throw new Error('PageData is null')
        return this.PageData.TradeBus
    }

    public get TradeInfo(): TradeInfoHelper {
        if (!this.PageData) throw new Error('PageData is null')
        return this.PageData.TradeInfo
    }

    public get TradeAPIs(): TradeAPIsHelper {
        if (!this.PageData) throw new Error('PageData is null')
        return this.PageData.TradeAPIs
    }

    public get TradeResources(): TradeResourcesHelper {
        if (!this.PageData) throw new Error('PageData is null')
        return this.PageData.TradeResources
    }
    #endregion
}

// Vue组件封装
export const useEntryBase = () => {
    return {
        EntryBase,
        createEntry: () => reactive(new EntryBase())
    }
}