<script lang="ts" setup>
/**
 * 提现管理页
 * 顶部账户信息卡（银行卡质感）+ 四个记录列表（统一走 useVbenVxeGrid 封装）
 * 状态列统一用主题化状态胶囊（StatusPill 样式），金额涨跌用 --success/--destructive 变量，全量适配暗色
 */
import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { AnalysisChartsTabs, Page, useVbenModal } from '@vben/common-ui';
import { IconifyIcon as VbenIcon } from '@vben/icons';

import { FloatButton, FloatButtonGroup, message, Popover } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';
import DetailModal from '#/views/business/order/product-order/components/detail.vue';

import SettlementDetailDrawer from './components/settlement-detail-drawer.vue';
import Statistics from './components/statistics.vue';
import { getAccountChangeSearchOptions } from './config/account-change-search';
import { accountChangeGridOptions } from './config/account-change-table';
import { formOptions } from './config/search';
import { formOptions3 } from './config/settlement-log-search';
import { formOptions2 } from './config/settlement-search';
import { gridOptions2, gridOptions3 } from './config/settlement-table';
import { gridOptions } from './config/table';

const router = useRouter();

const [Grid, GridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [Grid2] = useVbenVxeGrid({
  formOptions: formOptions2,
  gridOptions: gridOptions2,
});

const settlementDetailDrawerRef =
  ref<InstanceType<typeof SettlementDetailDrawer>>();

const [Grid3] = useVbenVxeGrid({
  formOptions: formOptions3,
  gridOptions: gridOptions3,
});

// 门店侧裁剪掉「冻结金额（用户未确认收货）」筛选项，须在 setup 内按当前角色生成
const [Grid4] = useVbenVxeGrid({
  formOptions: getAccountChangeSearchOptions(),
  gridOptions: accountChangeGridOptions,
});

const [OrderDetailModal, OrderDetailModalApi] = useVbenModal({
  connectedComponent: DetailModal,
});

function showSettlementDetail(row: Record<string, any>) {
  settlementDetailDrawerRef.value?.open(row);
}

function openOrderDetail(row: Record<string, any>) {
  const orderType = Number(row.order_type || 0);
  const orderId = Number(row.order_id || 0);
  const orderNo = String(row.order_no || '');

  if (orderType === 1 && orderId > 0) {
    OrderDetailModalApi.setData({ id: orderId });
    OrderDetailModalApi.open();
    return;
  }

  if (orderType === 2 && orderNo) {
    router.push({
      path: '/business/register/list',
      query: { order_no: orderNo },
    });
    return;
  }

  message.info('暂不支持查看该类型订单详情');
}

const chartTabs = [
  { label: '提现记录', value: 'trends' },
  { label: '结算记录', value: 'visits' },
  { label: '结算明细', value: 'visitsItems' },
  { label: '资金变动记录', value: 'accountChange' },
];

const isShow = ref(true);

function updateShowStatus() {
  isShow.value = !isShow.value;
}

/**
 * 审核状态 → 胶囊配色映射
 * 1待审核=warning 2审核成功=success 3拒绝=danger，统一走主题变量适配暗色
 */
function checkStatusPill(status: number) {
  if (status === 2) return { cls: 'is-success', text: '审核成功' };
  if (status === 3) return { cls: 'is-danger', text: '已拒绝' };
  return { cls: 'is-warning', text: '待审核' };
}

/** 打款状态 → 胶囊配色映射：-1失败 0处理中 1成功 */
function dakuanStatusPill(status: number) {
  if (status === 1) return { cls: 'is-success', text: '打款成功' };
  if (status === -1) return { cls: 'is-danger', text: '打款失败' };
  return { cls: 'is-info', text: '处理中' };
}
</script>

<template>
  <Page
    auto-content-height
    description="提现前请确认好您的打款账户"
    title="提现管理"
  >
    <OrderDetailModal />
    <Statistics v-show="isShow" :grid-api="GridApi" />

    <div class="withdrawal-lists" style="min-height: 500px">
      <AnalysisChartsTabs :tabs="chartTabs" class="mt-3">
        <template #trends>
          <div style="min-height: 500px">
            <Grid>
              <template #toolbar-actions></template>
              <template #toolbar-tools></template>
              <template #user_id="{ row }">
                <span v-if="row.user_type === 1">{{ row.store?.name }}</span>
                <span v-else-if="row.user_type === 2">萧康平台</span>
                <span v-else-if="row.user_type === 3">{{
                  row.supplier?.name
                }}</span>
                <span v-else-if="row.user_type === 4">{{
                  row.delivery_warehouse?.name || row.deliveryWarehouse?.name
                }}</span>
                <span v-else>-</span>
              </template>
              <template #check_status="{ row }">
                <span
                  class="status-pill"
                  :class="checkStatusPill(row.check_status).cls"
                >
                  <i class="pill-dot" />
                  {{ checkStatusPill(row.check_status).text }}
                </span>
              </template>
              <template #check_result="{ row }">
                <span
                  v-if="row.check_status === 2 || row.check_status === 3"
                  class="status-pill"
                  :class="row.check_status === 2 ? 'is-success' : 'is-danger'"
                >
                  <i class="pill-dot" />
                  {{ row.check_result }}
                </span>
                <span v-else class="cell-muted">-</span>
              </template>
              <template #dakuan_status="{ row }">
                <span
                  class="status-pill"
                  :class="dakuanStatusPill(row.dakuan_status).cls"
                >
                  <i class="pill-dot" />
                  {{ dakuanStatusPill(row.dakuan_status).text }}
                </span>
              </template>
              <template #check_id="{ row }">
                <span>{{
                  row.check_admin?.username ||
                  row.check_admin?.nick_name ||
                  '暂无'
                }}</span>
              </template>
              <template #action="{ row }">
                <TableAction :actions="[]" :drop-down-actions="[]" />
              </template>
            </Grid>
          </div>
        </template>
        <template #visits>
          <div style="min-height: 500px">
            <Grid3>
              <template #toolbar-actions></template>
              <template #toolbar-tools></template>
              <template #action="{ row }">
                <TableAction
                  :actions="[
                    {
                      label: '查看明细',
                      type: 'link',
                      size: 'small',
                      onClick: showSettlementDetail.bind(null, row),
                    },
                    {
                      label: '订单详情',
                      type: 'link',
                      size: 'small',
                      onClick: openOrderDetail.bind(null, row),
                    },
                  ]"
                  :drop-down-actions="[]"
                />
              </template>
            </Grid3>
            <SettlementDetailDrawer ref="settlementDetailDrawerRef" />
          </div>
        </template>
        <template #visitsItems>
          <div style="min-height: 500px">
            <Grid2>
              <template #toolbar-actions></template>
              <template #toolbar-tools></template>
              <template #user_id="{ row }">
                <span v-if="row.user_type === 1">{{ row.store?.name }}</span>
                <span v-else-if="row.user_type === 2">萧康平台</span>
                <span v-else-if="row.user_type === 3">{{
                  row.supplier?.name
                }}</span>
                <span v-else-if="row.user_type === 4">{{
                  row.delivery_warehouse?.name || row.deliveryWarehouse?.name
                }}</span>
                <span v-else>-</span>
              </template>
              <template #action="{ row }">
                <TableAction :actions="[]" :drop-down-actions="[]" />
              </template>
            </Grid2>
          </div>
        </template>
        <template #accountChange>
          <div style="min-height: 500px">
            <Grid4>
              <template #toolbar-actions></template>
              <template #toolbar-tools></template>
              <template #change_amount="{ row }">
                <span
                  v-if="Number(row.change_amount) > 0"
                  class="amount-cell is-up"
                >
                  <VbenIcon icon="lucide:trending-up" class="amount-icon" />
                  +{{ Number(row.change_amount).toFixed(2) }}
                </span>
                <span
                  v-else-if="Number(row.change_amount) < 0"
                  class="amount-cell is-down"
                >
                  <VbenIcon icon="lucide:trending-down" class="amount-icon" />
                  {{ Number(row.change_amount).toFixed(2) }}
                </span>
                <span v-else class="cell-muted">0.00</span>
              </template>
              <template #action="{ row }">
                <TableAction
                  :actions="[
                    {
                      label: '订单详情',
                      type: 'link',
                      size: 'small',
                      ifShow: !!row.order_id,
                      onClick: openOrderDetail.bind(null, row),
                    },
                  ]"
                  :drop-down-actions="[]"
                />
              </template>
            </Grid4>
          </div>
        </template>
      </AnalysisChartsTabs>
    </div>
    <FloatButtonGroup :style="{ right: '24px', bottom: '84px' }" shape="circle">
      <Popover placement="left" title="显示余额卡片">
        <template #content>
          <p>点击展开卡片信息，再次点击收起</p>
        </template>
        <FloatButton
          :badge="{ dot: true }"
          :type="isShow === true ? 'primary' : 'dashed'"
          shape="circle"
          @click="updateShowStatus"
        >
          <template #icon>
            <svg
              height="24"
              viewBox="0 0 24 24"
              width="20"
              xmlns="http://www.w3.org/2000/svg"
            >
              <g
                fill="none"
                stroke="currentColor"
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="1.5"
              >
                <path
                  d="M21.5 16.052V7.948a4.14 4.14 0 0 0-1.236-2.945a4.25 4.25 0 0 0-2.985-1.22H6.72a4.25 4.25 0 0 0-2.985 1.22A4.14 4.14 0 0 0 2.5 7.948v8.104c0 1.105.445 2.164 1.236 2.945a4.25 4.25 0 0 0 2.985 1.22H17.28c1.12 0 2.193-.44 2.985-1.22a4.14 4.14 0 0 0 1.236-2.945"
                />
                <path
                  d="M8.552 12.14a2.054 2.054 0 1 0 0-4.108a2.054 2.054 0 0 0 0 4.108m3.081 3.828c0-.812-.324-1.59-.902-2.165a3.09 3.09 0 0 0-4.358 0a3.05 3.05 0 0 0-.902 2.165m9.097-7.049h3.594M14.568 12h1.54m-1.54 3.081h3.594"
                />
              </g>
            </svg>
          </template>
        </FloatButton>
      </Popover>
    </FloatButtonGroup>
  </Page>
</template>

<style scoped lang="scss">
/* ===== 列表区卡片壳：与账户卡同一套圆角/描边视觉 ===== */
.withdrawal-lists {
  :deep(.card-box) {
    border-radius: 14px;
    border: 1px solid hsl(var(--border));
    box-shadow: 0 1px 2px rgb(0 0 0 / 4%);
  }
}

/* ===== 状态胶囊：主题变量配色（success/warning/destructive），自动适配暗色 ===== */
.status-pill {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  height: 22px;
  padding: 0 9px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 500;
  line-height: 1;
  white-space: nowrap;

  .pill-dot {
    flex-shrink: 0;
    width: 5px;
    height: 5px;
    border-radius: 50%;
    background: currentColor;
  }

  &.is-success {
    color: hsl(var(--success));
    background: hsl(var(--success) / 0.12);
  }

  &.is-warning {
    color: hsl(var(--warning));
    background: hsl(var(--warning) / 0.14);
  }

  &.is-danger {
    color: hsl(var(--destructive));
    background: hsl(var(--destructive) / 0.1);
  }

  &.is-info {
    color: hsl(var(--muted-foreground));
    background: hsl(var(--muted) / 0.6);
  }
}

/* ===== 资金变动金额：涨绿跌红走主题变量，数字用等宽字体对齐 ===== */
.amount-cell {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-family: 'DIN Alternate', ui-monospace, SFMono-Regular, Menlo, monospace;
  font-weight: 600;
  font-variant-numeric: tabular-nums;

  &.is-up {
    color: hsl(var(--success));
  }

  &.is-down {
    color: hsl(var(--destructive));
  }
}

.amount-icon {
  width: 14px;
  height: 14px;
}

.cell-muted {
  color: hsl(var(--muted-foreground));
}
</style>
