<template>
  <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
    <cwg-header :title="t('Home.page_ib.item7')" />

    <view class="account-content">
      <view class="search-content">
        <view class="search-bar">
          <cwg-complex-search :fields="filterFields" v-model="searchParams" @search="handleSearch"
                              @reset="handleReset" />
        </view>
        <view />
      </view>
      <cwg-tabel
        ref="tableRef"
        :columns="columns"
        :mobilePrimaryFields="mobilePrimaryFields"
        :queryParams="search"
        :api="listApi"
        :show-operation="true"
        :showPagination="true"
      >
        <template #remitChannelName="{row}">
          <text>
            {{
              isZh ? row.remitChannelName || '--' : row.remitChannelEnName || '--'
            }}
          </text>
        </template>
        <template #status="{row}">
          <view style="display: flex;flex-direction: column;align-items: center">
            <text v-if="row.status == 1">
              {{ t('State.ToBeProcessed') }}
            </text>
            <text v-if="row.status == 2&&row.submitStatus == 2">
              {{ t('State.Completed') }}
            </text>
            <text v-if="row.status == 2&&row.submitStatus != 2">
              {{ t('State.InTheProcessing') }}
            </text>
            <text v-if="row.status == 3 || row.callbackStatus == 2">
              {{ t('State.Refused') }}
            </text>
            <text v-if="row.status == 5">
              {{ t('State.Cancelled') }}
            </text>
            <button class="cancel-btn btn btn-gray" v-if="row.status == 1" @click.stop="cancel(row.id)">
              {{ t('Btn.Cancel') }}
            </button>
          </view>

        </template>
      </cwg-tabel>
    </view>
    <cwg-confirm-popup />
  </cwg-page-wrapper>
</template>

<script setup lang="ts">
  // 申请历史
  import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { useI18n } from 'vue-i18n' // uni-app 中已集成，但需配置
  import { customApi } from '@/service/custom'
  import { financialApi } from '@/service/financial'
  import Config from '@/config/index'
  import { ibApi } from '@/service/ib'
  import { useRecordingConst } from '@/pages/ib/const/recording'
  import { useFilters } from '@/composables/useFilters'
  import { useConfirm } from '@/hooks/useConfirm'
  import { nextTick } from 'vue'

  const confirm = useConfirm()
  const { numberFormat, numberDecimal } = useFilters()
  const { t, locale } = useI18n()
  const { columnList, mobileList, apiList } = useRecordingConst()
  let { Code } = Config
  const typeList = computed(() => [
    { text: t('Ib.Recording.NewAccount'), value: 1 },
    { text: t('Ib.Recording.LeverageApply'), value: 2 },
    { text: t('Ib.Recording.InternalTransfer'), value: 3 },
    { text: t('Ib.Recording.ActivitiesApply'), value: 4 },
    { text: t('Ib.Recording.MaidAdjust'), value: 5 },
    { text: t('Ib.Recording.BelongingAdjust'), value: 6 },
    { text: t('Ib.Recording.CommissionAllocation'), value: 7 },
    { text: t('Custom.Withdraw.Title'), value: 8 },
    { text: t('Ib.Recording.MamHangUndo'), value: 9 },
    { text: t('Home.page_ib.item9'), value: 10 },
    { text: t('Ib.PammManager.title2'), value: 11 },
    { text: t('Ib.PammManager.title3'), value: 12 },
    { text: t('Ib.Transfer.IbAccountTransfer'), value: 13 },
  ])

  const getCurrentMonthRange = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = now.getMonth()

    // 第一天
    const firstDay = new Date(year, month, 1)
    // 最后一天
    const lastDay = new Date(year, month + 1, 0)

    const format = (date) => {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${d}`
    }

    return [format(firstDay), format(lastDay)]
  }

  const defaultDateRange = getCurrentMonthRange()

  const searchParams = ref({
    types: 1,
    date: defaultDateRange,
    startDate: defaultDateRange[0],
    endDate: defaultDateRange[1],
  })

  const search = reactive({
    types: 1,
    startDate: defaultDateRange[0],
    endDate: defaultDateRange[1],
  })

  const filterFields = computed(() => [
    {
      key: 'types',
      type: 'select',
      label: t('placeholder.choose'),
      placeholder: t('placeholder.choose'),
      options: typeList.value,
      defaultValue: 1,
      isSelect: true,
      clearable: false,
    },
    {
      key: 'date',
      label: t('placeholder.Start') + ' - ' + t('placeholder.End'),
      type: 'daterange',
      defaultValue: defaultDateRange,
    },
  ])

  const tableRef = ref<any>(null)

  const handleSearch = (params: any) => {
    const payload = { ...params }
    Object.assign(search, payload)
    nextTick(() => {
      tableRef.value?.refreshTable?.()
    })
  }

  const handleReset = (params) => {
    searchParams.value = {
      ...params,
      types: 1,
    }
    Object.assign(search, params,{ types: 1,})
    nextTick(() => {
      tableRef.value?.refreshTable?.()
    })
  }

  const isZh = computed(() => {
    return ['cn', 'zhHant'].indexOf(locale.value) != -1
  })
  // 表格列配置 根据types 切换
  const columns = computed(() => {
    return columnList.value[search.types]
  })

  const mobilePrimaryFields = computed(() => {
    return [
      ...mobileList.value[search.types],
      {
        prop: 'more',
        type: 'more',
        width: 20,
        align: 'right',
      },
    ]
  })

  // 接口 根据types 切换
  const listApi = computed(() => {
    let other = {}
    switch (search.types) {
      case 1:
        other = {
          mamType: 0,
        }
        break
      case 4:
        other = {
          type: 4,
        }
        break
      case 11:
      case 12:
        other = {
          mamType: 3,
        }
        break
    }

    return (params) => ibApi[apiList.value[search.types]]({ ...params, ...other })
  })

  const cancel = async (id) => {
    tableRef.value.setDetailVisible(false)
    try {
      await confirm({
        title: t('Msg.SystemPrompt'),
        content: t('Msg.Cancle'),
        confirmText: t('Btn.item6'),
        cancelText: t('Btn.item7'),
      })
      let res = await ibApi.withdrawCancel({ id })
      if (res.code == Code.StatusOK) {
        uni.showToast({
          title: t('Msg.Success'),
          icon: 'success',
        })
        nextTick(() => {
          tableRef.value?.refreshTable?.()
        })
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        })
      }
    } catch (err) {
      err.msg && uni.showToast({
        title: err.msg,
        icon: 'none',
      })
    }
  }

  onMounted(() => {

  })
</script>
<style lang="scss" scoped>
  @import "@/uni.scss";

  .search-content {
    display: flex;
    justify-content: space-between;

    .uni-date {
      width: px2rpx(250) !important;
      flex: none;
    }
  }
  .cancel-btn{
    display: block;
    width: px2rpx(50);
    line-height: px2rpx(16) !important;
  }
</style>