import { ref, reactive } from 'vue'
import { useTradeAPIs } from '@/composables/useTradeAPIs'
import { usePlatformLogger } from '@/composables/usePlatformLogger'
import { usePageFactory } from '@/composables/usePageFactory'
import { useTradeBus } from '@/composables/useTradeBus'

/**
 * 现金冠字号管理入口
 */
export class CashCodeEntry {
  private static readonly ACTION = 'Trade.OperationManage.CASHVIEWER'
  private static enabled = ref(false)
  private static lastEndTime = ref('')
  private static history = reactive<BizItem[]>([])

  private item = reactive<BizItem>({
    startTime: new Date(),
    endTime: null,
    biz: BizType.Other,
    cardNo: '',
    userName: '',
    money: 0,
    txCode: '',
    serialNo: ''
  })

  private bals2Init = reactive<Record<string, number>>({})

  /**
   * 初始化点钞机节点程序
   */
  public static async init(target: any): Promise<boolean> {
    if (!this.enabled.value) return true

    let flag = false
    try {
      const page = usePageFactory().createPage(this.ACTION)
      while (true) {
        flag = await target.ownerContainer.modalInvoke(() => page.initDevice(), '链接冠字号设备，请稍候...')
        if (flag) break

        const result = await target.showComfirmBox('链接冠字号设备失败，是否重试？', ['重试', '关闭功能', '稍后处理'])
        if (result === 2) this.enabled.value = false
        if (result !== 1) break
      }
    } catch (ex) {
      usePlatformLogger().systemErrorInfo('CashCodeEntry.InitDevice:发生异常！', ex)
    }
    return flag
  }

  /**
   * 预处理
   */
  public preview(cardNo: string, userName: string, biz: BizType): boolean {
    if (!CashCodeEntry.enabled.value) return true

    if (useTradeBus().get('__StartTime__')) {
      this.item.startTime = new Date(useTradeBus().get('__StartTime__'))
    }

    this.item.cardNo = cardNo
    this.item.userName = userName
    this.item.biz = biz
    this.item.txCode = useTradeAPIs().tradeModel.code

    const current = useTradeAPIs().getTellerBalanceMoney()
    if (current) {
      Object.assign(this.bals2Init, current)
      useTradeAPIs().onPagePrinted(this.handlePagePrinted)
      return true
    }
    return false
  }

  /**
   * 业务处理
   */
  private proc(serialNo: string): void {
    if (!CashCodeEntry.enabled.value || !this.bals2Init) return

    this.item.serialNo = serialNo
    this.item.endTime = new Date()
    const current = useTradeAPIs().getTellerBalanceMoney()
    this.item.money = current['01'] - this.bals2Init['01']

    if (this.item.money !== 0 || this.item.biz === BizType.Counterfeit) {
      while (true) {
        const key = useTradeAPIs().showComfirmBox(
          '本次交易存在现金处理，是否进行现金冠字号处理？\n',
          '立即提交',
          '等待下一笔业务提交',
          '该交易无点钞操作无需处理'
        )

        if (key === 3) break
        CashCodeEntry.history.push({ ...this.item })

        if (key !== 1) break

        const guid = useTradeAPIs().openTradePage(
          CashCodeEntry.ACTION,
          'Dialog',
          { STATUS_CASHVIEWER: 'init' },
          null,
          '现金业务-冠字号管理'
        )

        const status = useTradeAPIs().viewStateData['STATUS_CASHVIEWER']
        if (status === 'commit' || status === 'cancel') break
      }
    }
  }

  private handlePagePrinted = (e: any): void => {
    this.proc(e.printAttr.serialNumber)
  }
}

/**
 * 业务类型
 */
export enum BizType {
  Deposit = 0,
  Withdrawal = 1,
  Incomplete = 4,
  Counterfeit = 5,
  Other = 6
}

/**
 * 业务项
 */
export interface BizItem {
  startTime: Date | null
  endTime: Date | null
  biz: BizType
  cardNo: string
  userName: string
  money: number
  txCode: string
  serialNo: string
}