<template>
  <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
    <cwg-header :title="t('Ib.Custom.Manage2')" />

    <view class="account-content">
      <!-- 移动端：按钮在筛选上方 -->
      <cwg-match-media :max-width="991">
        <view class="search-content mobile-search-content">
          <view class="search-bar mobile-add-btn-wrap">
            <button type="primary" class="search-button" @click="addSub">
              <cwg-icon name="icon_add" :size="18" color="#fff"></cwg-icon>
              {{ t('Ib.Report.Title5') }}
            </button>
          </view>
          <view class="search-bar">
            <cwg-complex-search :fields="filterFields" v-model="searchParams" @search="handleSearch" @reset="handleReset" />
          </view>
        </view>
      </cwg-match-media>

      <!-- PC端：按钮和筛选在同一行 -->
      <cwg-match-media :min-width="991">
        <view class="search-content pc-search-content">
          <view class="search-bar">
            <cwg-complex-search :fields="filterFields" v-model="searchParams" @search="handleSearch"
                                @reset="handleReset" noData/>
          </view>
          <view class="search-bar">
            <button type="primary" class="search-button" @click="addSub">
              <cwg-icon name="icon_add" :size="18" color="#fff"></cwg-icon>
              {{ t('Ib.Report.Title5') }}
            </button>
          </view>
        </view>
      </cwg-match-media>

      <cwg-tabel
        ref="tableRef"
        :columns="columns"
        :mobilePrimaryFields="mobilePrimaryFields"
        :queryParams="search"
        :api="listApi"
        :show-operation="true"
        :showPagination="true"
      >
      </cwg-tabel>
    </view>
    <ApplyIbDialog ref="applyIbDialogRef" :visible="applyVisible" @close="closeApplyIb" @confirm="confirmApply"
                   :title="formDia?'Ib.Report.Title5':'Ib.Custom.Commit3'" :isFormApplyIb="formDia"
                   :paramsType="applyType" :detail="applyDetail" />
    <cwg-popup
      :visible="exclusiveVisible"
      :title="t('Ib.Custom.Commit5')"
      :cancelText="t('Btn.Cancel')"
      :confirmText="t('Btn.Confirm')"
      @close="cancelExclusiveCommission"
      @confirm="confirmExclusiveCommission"
    >
      <view class="dia-content">
        <uni-forms ref="exclusiveCommissionFormRef" labelWidth="240">
          <uni-forms-item :label="t('Ib.Custom.Commit5')" prop="selectedPoint">
            <cwg-combox
              v-model:value="exclusiveCommissionForm.selectedPoint"
              :options="exclusiveCommissionForm.pointOptions"
              :placeholder="t('placeholder.choose')"
            />
          </uni-forms-item>
        </uni-forms>
      </view>
    </cwg-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 { useFilters } from '@/composables/useFilters'
  import ApplyIbDialog from '@/pages/ib/components/applyIbDialog.vue'
  import { nextTick } from 'vue'

  const { numberFormat, numberDecimal } = useFilters()
  const { t, locale } = useI18n()
  const { Code } = Config
  const searchParams = ref({})
  const search = reactive({
    ibNo: '',
    name: '',
    cId: '',
  })

  const filterFields = computed(()=>[
    { key: 'ibNo', type: 'input', label: t('Label.IbAccount'), placeholder: t('Label.IbAccount'), defaultValue: '' },
    {
      key: 'name',
      type: 'input',
      label: t('Ib.Custom.NameLabel'),
      placeholder: t('Ib.Custom.NameLabel'),
      defaultValue: '',
    },
    { key: 'cId', type: 'input', label: 'CID', placeholder: 'CID', defaultValue: '' },
    { key: 'date', label: t('placeholder.Start') + ' - ' + t('placeholder.End'), type: 'daterange',defaultValue: ['',''] },
  ])
  const tableRef = ref(null)
  const applyIbDialogRef = ref(null)
  const applyVisible = ref(false)
  const applyType = ref('')
  const applyDetail = ref()
  const formDia = ref(false)
  const exclusiveVisible = ref(false)
  const exclusiveCommissionFormRef = ref(null)
  const exclusiveCommissionForm = ref({
    agentId: '',
    selectedPoint: '',
    pointOptions: [],
  })
  const exclusiveRow = ref<any>(null)
  // 表格列配置
  const columns = computed(() => [
    {
      prop: 'cId',
      label: t('Label.CidAccount'),
      align: 'center',
    },
    {
      prop: 'ibNo',
      label: t('Label.IbAccount'),
      align: 'center',
    },
    {
      prop: 'name',
      label: t('Ib.Custom.NameLabel'),
      align: 'center',
    },
    {
      prop: 'agentNum',
      label: t('Ib.Custom.AgentNum'),
      align: 'center',
    },
    {
      prop: 'customNum',
      label: t('Ib.Custom.CustomerNum'),
      align: 'center',
    },
    {
      prop: 'addTime',
      label: t('Label.ApplyTime'),
      align: 'center',
    },
    {
      prop: 'lastTime',
      label: t('Ib.Custom.LastActiveTime'),
      align: 'center',
    },
    {
      prop: 'action',
      label: t('Label.Action'),
      type: 'action',
      align: 'center',
      menuList: [
        {
          label: t('Ib.Custom.Commit3'),
          type: 'vietnamDistribution',
          btnClick: (row) => handleMenuClick({ type: 'vietnamDistribution', row }),
          show: true,
        },
        {
          label: t('Ib.Custom.Commit5'),
          type: 'exclusiveCommission',
          btnClick: (row) => handleMenuClick({ type: 'exclusiveCommission', row }),
          show: (row) => row.exclusiveCommissionOptions?.length > 0,
        },
      ],
    },
  ])

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


  const listApi = ref(ibApi.IbSubs)

  const handleSearch = (params: any) => {
    // 拦截处理 daterange，将 date 拆分为 startDate 和 endDate
    console.log(params)
    const payload = { ...params }
    Object.assign(search, payload)

    nextTick(() => {
      tableRef.value.refreshTable()
    })
  }

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

  onMounted(() => {
    // applyVisible.value = true
  })
  const handleMenuClick = (item) => {
    if (item.type == 'vietnamDistribution') {
      const { agentId, id } = item.row
      applyDetail.value = {
        id: id || agentId,
      }
      formDia.value = false
      applyType.value = 'vietnam'
      applyVisible.value = true
    } else if (item.type == 'exclusiveCommission') {
      openExclusiveCommission(item.row)
    }
  }
  const addSub = () => {
    formDia.value = true
    applyVisible.value = true
  }
  const closeApplyIb = () => {
    applyDetail.value = {}
    applyVisible.value = false
  }
  const confirmApply = (data) => {
    tableRef.value.refreshTable()
  }

  const normalizePointOptions = (options: any[]) => {
    if (!Array.isArray(options)) return []
    return options.map((o: any) => ({
      text: o.label ?? o.text ?? o.name ?? String(o.value ?? ''),
      value: o.value,
    }))
  }

  const openExclusiveCommission = async (row: any) => {
    exclusiveCommissionForm.value.agentId = row.id
    exclusiveCommissionForm.value.selectedPoint = ''
    exclusiveCommissionForm.value.pointOptions = normalizePointOptions(row?.exclusiveCommissionOptions || [])
    exclusiveVisible.value = true
  }

  const cancelExclusiveCommission = () => {
    exclusiveVisible.value = false
    exclusiveCommissionForm.value.selectedPoint = ''
    exclusiveCommissionForm.value.pointOptions = []
  }

  const confirmExclusiveCommission = async () => {
    try {
      const res = await ibApi.agentHiddenPointAdd({
        agentId: exclusiveCommissionForm.value.agentId,
        point: [{ value: exclusiveCommissionForm.value.selectedPoint }],
      })
      if (res.code == Code.StatusOK) {
        cancelExclusiveCommission()
        tableRef.value?.refreshTable?.()
      }
    } catch (e) {
    }
  }
</script>
<style lang="scss" scoped>
  @import "@/uni.scss";

  .search-content {
    display: flex;
  }

  /* PC 端对齐方式 */
  .pc-search-content {
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: px2rpx(10);
  }

  /* 移动端排版方式 */
  .mobile-search-content {
    flex-direction: column;
    margin-bottom: px2rpx(10);

    .mobile-add-btn-wrap {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      margin-bottom: px2rpx(10);

      .search-button {
        background-color: var(--bs-secondary);
        margin: 0 0 0 auto; /* 强制按钮靠右且消除其它 margin */
      }
    }
  }

  .search-button {
    display: flex;
    align-items: center;
    background-color: var(--bs-secondary);
    line-height: px2rpx(36);
    min-width: px2rpx(120);
    border-radius: px2rpx(8);
  }
</style>
