import { reactive, ref } from 'vue'
import type { PageBase } from '../ContractBase/PageBase'
import type { Message } from '../Communication/Message'
import type { AuthConditionElement } from '../ServiceProxy/Ext/ServiceEntitys'
import { AuthDataHelper } from '../ContractBase/AuthDataHelper'
import { EntryBase } from '../ContractBase/EntryBase'

/**
 * 授权逻辑入口
 */
export class AuthorizeEntry extends EntryBase {
    private readonly _powerCode: string

    /**
     * 授权触发器，允许绑定权限编码
     * @param powerCode 权限编码
     */
    constructor(powerCode: string = "0") {
        super()
        this._powerCode = powerCode
    }

    /**
     * 权限编号
     */
    public get PowerCode(): string {
        return this._powerCode
    }

    /**
     * 准备授权数据事件
     */
    public PreviewAuthorize?: (sender: PageBase, args: PreviewAuthorizeEventArgs) => void

    /**
     * 远程授权成功后执行
     */
    public RemoteAuthorized?: () => void

    /**
     * 执行授权操作
     * @returns 授权是否成功
     */
    public RaiseAuthorize(): boolean {
        if (!this.PreviewAuthorize) return false

        const args = new PreviewAuthorizeEventArgs(this.PageData)
        this.PreviewAuthorize(this.PageData, args)

        // 获取内部授权要素
        const openBranch = ref('')
        const authCondition = this.PageData.TradeAPIs.GetAuthElement(
            openBranch.value,
            args.DeAccount,
            args.CrAccount,
            args.SinAmt.toString(),
            args.CTSigns,
            args.OperationType,
            args.DeAccountSeqn
        )

        const pages = args.CustomizePages.length > 0
            ? args.CustomizePages.map((data, index) => ({
                index: index + 1,
                datas: data
            }))
            : [{
                index: 1,
                datas: this.PageData.SaveTradePage(this.PageData.Content)
            }]

        const authManager = new AuthManager()
        authManager.AsksuperResultMessage = (result, dataBus) => {
            switch (result) {
                case AsksuperResultType.Success:
                    if (new AuthDataHelper(this.PageData).AuthWay === "remote" && this.RemoteAuthorized) {
                        this.RemoteAuthorized()
                    }
                    break
                case AsksuperResultType.Failed:
                    this.PageData.TradeAPIs.ShowInfoMessageBox("授权没有通过")
                    break
                case AsksuperResultType.Undo:
                    this.PageData.TradeAPIs.ShowInfoMessageBox("授权已撤销")
                    break
            }
        }

        return authManager.DoAuth(
            this.PageData,
            authCondition,
            args.CustomizeMessage ?? this.MessageData,
            pages,
            this.PowerCode,
            args.EnrollAccount,
            args.EnrollAmt.toString(),
            args.EnrollAccumulation.toString(),
            args.EnrollAccountName,
            args.EnrollDescription,
            openBranch.value
        )
    }
}

/**
 * 准备授权数据事件参数
 */
export class PreviewAuthorizeEventArgs {
    public CustomizePages: Uint8Array[] = []
    public CustomizeMessage: Message | null = null
    public readonly Page: PageBase

    constructor(page: PageBase) {
        this.Page = page
    }

    // 核心要素
    public DeAccount: string = ''
    public CrAccount: string = ''
    public SinAmt: number = 0
    public CTSigns: string = ''
    public OperationType: string = ''
    public DeAccountSeqn: string = ''

    // 查询要素
    public EnrollAccount: string = ''
    public EnrollAccountName: string = ''
    public EnrollAmt: number = 0
    public EnrollAccumulation: number = 0
    public EnrollDescription: string = ''
}

// Vue组件封装
export const useAuthorizeEntry = (powerCode: string = "0") => {
    return reactive(new AuthorizeEntry(powerCode))
}

// 辅助类型
enum AsksuperResultType {
    Success,
    Failed,
    Undo
}

interface AuthManager {
    AsksuperResultMessage?: (result: AsksuperResultType, dataBus: any) => void
    DoAuth: (
        page: PageBase,
        authCondition: AuthConditionElement,
        message: Message | null,
        pages: Array<{ index: number, datas: Uint8Array }>,
        powerCode: string,
        enrollAccount: string,
        enrollAmt: string,
        enrollAccumulation: string,
        enrollAccountName: string,
        enrollDescription: string,
        openBranch: string
    ) => boolean
}