<template>
  <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
    <cwg-header :title="t('Home.page_ib.item2')" />
    <view class="info-card">
      <!-- 移动端：分类标签在搜索组件下 -->
      <cwg-match-media :max-width="991">
        <view class="search-content mobile-search-content">
          <view class="search-bar">
            <cwg-complex-search :fields="filterFields" v-model="search" @search="handleSearch"
                                @reset="handleReset" />
          </view>
          <view class="search-tabs">
            <view class="crm-cursor tab-item" :class="{ active: search.belongsType == 1 }"
                  @click="chooseBelongsType(1)">
              {{ t('Ib.Custom.Unverified') }}
              <view v-if="statistics.unverifiedNum !== undefined" class="count-badge">({{ statistics.unverifiedNum }})
              </view>
            </view>
            <view class="crm-cursor tab-item" :class="{ active: search.belongsType == 2 }"
                  @click="chooseBelongsType(2)">
              {{ t('Ib.Custom.UnDeposit') }}
              <view v-if="statistics.unDepositNum !== undefined" class="count-badge">({{ statistics.unDepositNum }})
              </view>
            </view>
            <view class="crm-cursor tab-item" :class="{ active: search.belongsType == 3 }"
                  @click="chooseBelongsType(3)">
              {{ t('Ib.Custom.Deposited') }}
              <view v-if="statistics.depositNum !== undefined" class="count-badge">({{ statistics.depositNum }})</view>
            </view>
          </view>
        </view>
      </cwg-match-media>

      <!-- PC端：分类标签和搜索组件在同一行 (搜索在左，标签在右) -->
      <cwg-match-media :min-width="992">
        <view class="search-content pc-search-content">
          <view class="search-bar">
            <cwg-complex-search :fields="filterFields" v-model="search" @search="handleSearch"
                                @reset="handleReset" />
          </view>
          <view class="search-tabs">
            <view class="crm-cursor tab-item cursor-pointer" :data-tooltip="t('Ib.Custom.Unverified')" :class="{ active: search.belongsType == 1 }"
                  @click="chooseBelongsType(1)">
              {{ t('Ib.Custom.Unverified') }}
              <view v-if="statistics.unverifiedNum !== undefined" class="count-badge">({{ statistics.unverifiedNum }})
              </view>
            </view>
            <view class="crm-cursor tab-item cursor-pointer" :data-tooltip="t('Ib.Custom.Unverified')" :class="{ active: search.belongsType == 2 }"
                  @click="chooseBelongsType(2)">
              {{ t('Ib.Custom.UnDeposit') }}
              <view v-if="statistics.unDepositNum !== undefined" class="count-badge">({{ statistics.unDepositNum }})
              </view>
            </view>
            <view class="crm-cursor tab-item cursor-pointer" :data-tooltip="t('Ib.Custom.Unverified')" :class="{ active: search.belongsType == 3 }"
                  @click="chooseBelongsType(3)">
              {{ t('Ib.Custom.Deposited') }}
              <view v-if="statistics.depositNum !== undefined" class="count-badge">({{ statistics.depositNum }})</view>
            </view>
          </view>
        </view>
      </cwg-match-media>

      <cwg-tabel
        ref="tableRef"
        :columns="columns"
        :mobilePrimaryFields="mobilePrimaryFields"
        :queryParams="search"
        :api="listApi"
        :show-operation="true"
        :showPagination="true"
      >
      </cwg-tabel>
      <!-- 跟单全局设置     -->
      <DocumentaryDialog :visible="docVisible" :detail="formInfoRow" @close="closeDoc" @confirm="confirmDoc" />
      <!-- 开户调整     -->
      <PointDialog :visible="pointVisible" :detail="pointForm" @close="closePoint" @confirm="confirmPoint" />
      <!-- 申请成为代理     -->
      <ApplyIbDialog :visible="applyVisible" :detail="applyForm" @close="closeApply" @confirm="confirmApply" />
    </view>
  </cwg-page-wrapper>
</template>

<script setup lang="ts">
  import { computed, ref, onMounted, nextTick } from 'vue'
  import { useI18n } from 'vue-i18n'
  import Config from '@/config/index'

  const { t, locale } = useI18n()
  import { customApi } from '@/service/custom'
  import { ibApi } from '@/service/ib'
  import DocumentaryDialog from '@/pages/ib/components/documentaryDialog.vue'
  import PointDialog from '@/pages/ib/components/pointDialog.vue'
  import ApplyIbDialog from '@/pages/ib/components/applyIbDialog.vue'

  const { Code } = Config
  const statistics = ref({
    unverifiedNum: 0,
    unDepositNum: 0,
    depositNum: 0,
  })

  const search = ref({
    'name': '',
    'email': '',
    'cId': '',
    // 1:未实名 2:未入金 3:已入金
    belongsType: null,
  })

  const filterFields = computed(()=>[
    { key: 'cId', type: 'input', label: 'CID', placeholder: 'CID', defaultValue: '' },
    {
      key: 'name',
      type: 'input',
      label: t('Ib.Custom.NameLabel'),
      placeholder: t('Ib.Custom.NameLabel'),
      defaultValue: '',
    },
    { key: 'email', type: 'input', label: t('Label.Email'), placeholder: t('Label.Email'), defaultValue: '' },
  ])

  const formInfoRow = ref({})
  const pointForm = ref({})
  const applyForm = ref({})
  const applyTable = ref([])
  const docVisible = ref(false)
  const pointVisible = ref(false)
  const applyVisible = ref(false)
  const tableRef = ref(null)


  // 表格列配置
  const columns = computed(()=>[
    {
      prop: 'cId',
      label: t('Label.CidAccount'),
      align: 'center',
    },
    {
      prop: 'name',
      label: t('Ib.Custom.NameLabel'),
      align: 'center',
    },
    {
      prop: 'email',
      label: t('Label.Email'),
      align: 'center',
    },
    {
      prop: 'countryEnName',
      label: t('Label.Nationality'),
      align: 'center',
      width: locale.value == 'en' ? 110 : 0,
    },
    {
      prop: 'addTime',
      label: t('Label.RegistrationTime'),
      align: 'center',
      width: locale.value == 'en' ? 110 : 0,
    },
    {
      prop: 'belongsType',
      label: t('Ib.Custom.CustomerStatus'),
      align: 'center',
      formatter: ({ row }) => row.belongsType == 1 ? t('Ib.Custom.Unverified') :
        row.belongsType == 2 ? t('Ib.Custom.UnDeposit') :
          row.belongsType == 3 ? t('Ib.Custom.Deposited') : '--',
    },
    {
      prop: 'ibStatus',
      label: t('Ib.Custom.ApplyAgent'),
      align: 'center',
      formatter: ({ row }) => row.ibStatus == 2 ? t('Ib.Custom.Yes') : t('Ib.Custom.No'),
    },
    {
      prop: 'action',
      label: t('Label.Action'),
      type: 'action',
      align: 'center',
      menuList: [
        {
          label: t('Documentary.AgentBackground.item1'),
          type: 'documentary',
          btnClick: (row) => handleMenuClick({ type: 'documentary', row }),
          show: true,
        },
        {
          label: t('Home.msg.ibTitle'),
          type: 'applyIb',
          btnClick: (row) => handleMenuClick({ type: 'applyIb', row }),
          show: (row) => row.ibStatus == 1 && row.belongsType != 1,
        },
        {
          label: t('Ib.Custom.AccountAdjust'),
          type: 'Point',
          btnClick: (row) => handleMenuClick({ type: 'Point', row }),
          show: (row) => row.belongsType != 1,
        },
      ],
    },
  ])

  const mobilePrimaryFields = computed(()=>[
    {
      prop: 'cId',
      label: t('Label.CidAccount'),
      align: 'center',
    },
    {
      prop: 'name',
      label: t('Ib.Custom.NameLabel'),
      align: 'center',
    },
    {
      prop: 'email',
      label: t('Label.Email'),
      align: 'center',
    },
    {
      prop: 'more',
      type: 'more',
      width: 20,
      align: 'right',
    },
  ])


  const listApi = ref(null)
  listApi.value = ibApi.customerSubs

  const handleSearch = (params: any) => {
    console.log(params)
    // 合并表单的过滤参数，同时保留当前的 belongsType 标签选中状态
    search.value = {
      ...params,
      belongsType: search.value.belongsType,
    }
    nextTick(() => {
      tableRef.value.refreshTable()
    })
  }

  const handleReset = (params: any) => {
    search.value = {
      ...params,
      belongsType: search.value.belongsType, // 保持当前的分类标签选中
    }
    nextTick(() => {
      tableRef.value.refreshTable()
    })
  }

  //选择belongsType（点击已选中的 tab 可反选取消）
  const chooseBelongsType = (belongsType) => {
    if (search.value.belongsType == belongsType) {
      search.value.belongsType = null // 反选：取消选中
    } else {
      search.value.belongsType = belongsType
    }
    // 切换 tab 时自动重新请求列表
    nextTick(() => {
      tableRef.value.refreshTable()
    })
  }
  // 下拉菜单配置
  const menuList = (row) => {
    return [
      {
        label: t('Documentary.AgentBackground.item1'),
        type: 'documentary',
        row,
        show: true,
      },
      {
        label: t('Home.msg.ibTitle'),
        type: 'applyIb',
        row,
        show: row.ibStatus == 1 && row.belongsType != 1,
      },
      {
        label: t('Ib.Custom.AccountAdjust'),
        type: 'Point',
        row,
        show: row.belongsType != 1,
      },
    ].filter((item) => item.show)
  }
  const handleMenuClick = (item) => {
    if (item.type == 'documentary') {
      const { cId, id, permissionDisplay } = item.row
      formInfoRow.value = {
        cId, id, permissionDisplay,
      }
      docVisible.value = true
    } else if (item.type == 'applyIb') {
      applyForm.value = item.row
      applyVisible.value = true
    } else if (item.type == 'Point') {
      pointForm.value = item.row
      nextTick(() => {
        pointVisible.value = true
      })
    }
  }

  //获取统计数
  const getStatistics = async () => {
    try {
      let res = await ibApi.customerSubsStatistics({})
      if (res.code == Code.StatusOK && res.data) {
        statistics.value = {
          unverifiedNum: res.data.unverifiedNum || 0,
          unDepositNum: res.data.unDepositNum || 0,
          depositNum: res.data.depositNum || 0,
        }
      }
    } catch (error) {
    }
  }
  onMounted(() => {
    getStatistics()
  })

  const closeDoc = () => {
    docVisible.value = false
  }
  const closeApply = () => {
    applyVisible.value = false
  }
  const closePoint = () => {
    pointForm.value = {}
    pointVisible.value = false
  }

  const confirmDoc = () => {
    docVisible.value = false
    tableRef.value.refreshTable()
  }
  const confirmPoint = () => {
    pointVisible.value = false
    tableRef.value.refreshTable()
  }
  const confirmApply = () => {
    applyVisible.value = false
    tableRef.value.refreshTable()
  }


</script>

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

  .search-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }

  .mobile-search-content {
    flex-direction: column;
    align-items: flex-start;
    gap: px2rpx(10);

    .search-tabs {
      padding: 0;
      margin: 0;
    }
  }

  .pc-search-content {
    flex-direction: row;
    align-items: center;
  }

  .search-bar {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: px2rpx(10);
    margin: px2rpx(16) 0;

    .cwg-combox,
    .uni-easyinput,
    .uni-date {
      width: px2rpx(180) !important;
      flex: none;
    }

    :deep(.uni-easyinput__content) {
      height: px2rpx(35) !important;
      min-height: px2rpx(35) !important;
    }

    :deep(.uni-easyinput__content-input) {
      height: px2rpx(35) !important;
    }

    :deep(.search-btn) {
      height: px2rpx(35);
      min-height: px2rpx(35);
      line-height: px2rpx(35);
      padding: 0 px2rpx(16);
      margin: 0;
      box-sizing: border-box;
    }

    :deep(.form-actions) {
      align-items: center;
    }
  }

  .search-tabs {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: px2rpx(10);
    margin: px2rpx(16) 0;

    .tab-item {
      display: flex;
      align-items: center;
      min-width: px2rpx(100);
      border: 1px solid #F0F0F0;
      border-radius: px2rpx(4);
      margin-right: px2rpx(5);
      height: px2rpx(35);
      line-height: px2rpx(35);
      padding: 0 px2rpx(12);
      box-sizing: border-box;
      font-size: px2rpx(14);
      justify-content: center;

      &.active {
        color: var(--color-white);
        background-color: var(--color-error);
        border-color: var(--color-error);
      }
    }
  }

  .action-btn {
    display: flex;
    //align-items: center;
    justify-content: center;
  }
</style>
