<script setup lang="ts">
import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Card,
  Empty,
  Input,
  Popover,
  Space,
  Tag,
  message,
} from 'ant-design-vue';

import {
  getPlatformSalespersonListApi,
  openAdminAccountApi,
} from '#/views/business/store/settings/api';
import QrCodePreview from '#/views/business/store/settings/components/SalespersonQrCodePreview.vue';
import SalespersonCommissionDrawer from '#/views/system/store/components/SalespersonCommissionDrawer.vue';
import SalespersonCreateModal from '#/views/business/store/settings/components/SalespersonCreateModal.vue';
import SalespersonUserBindDrawer from '#/views/business/store/settings/components/SalespersonUserBindDrawer.vue';

const listData = ref<{ total: number; items: any[] }>({ total: 0, items: [] });
const loading = ref(false);
const storeKeyword = ref('');
const nickName = ref('');
const phone = ref('');
const page = ref(1);
const pageSize = ref(20);
const openingAccountId = ref(0);

const commissionDrawerRef = ref<InstanceType<typeof SalespersonCommissionDrawer>>();

const [QrCodePreviewModal, QrCodePreviewApi] = useVbenModal({
  connectedComponent: QrCodePreview,
});

const [SalespersonCreateModalComponent, SalespersonCreateModalApi] = useVbenModal({
  connectedComponent: SalespersonCreateModal,
});

async function getList() {
  loading.value = true;
  try {
    const res = await getPlatformSalespersonListApi({
      page: page.value,
      pageSize: pageSize.value,
      store_keyword: storeKeyword.value,
      nick_name: nickName.value,
      phone: phone.value,
    });
    listData.value = {
      total: res?.total ?? 0,
      items: res?.items ?? [],
    };
  } finally {
    loading.value = false;
  }
}

getList();

function openCommission(item: any) {
  const sid = item.qr_code?.store_id;
  if (!sid) {
    message.warning('缺少门店信息');
    return;
  }
  commissionDrawerRef.value?.open({
    id: sid,
    name: item.store_name || '',
    salespersonId: item.id,
  });
}

function openQrCode(item: any) {
  QrCodePreviewApi.setData({ values: item });
  QrCodePreviewApi.open();
}

function openCreateModal() {
  SalespersonCreateModalApi.setData({
    getList,
    mode: 'platform',
  });
  SalespersonCreateModalApi.open();
}

function openEditModal(item: any) {
  SalespersonCreateModalApi.setData({
    values: item,
    getList,
    update: true,
  });
  SalespersonCreateModalApi.open();
}

async function handleOpenAdminAccount(item: any) {
  openingAccountId.value = item.id;
  try {
    await openAdminAccountApi({
      salesperson_id: item.id,
      store_id: item.qr_code?.store_id,
    });
    message.success('后台账号开通成功，默认密码 Xk123456@');
    getList();
  } finally {
    openingAccountId.value = 0;
  }
}

function splitTypeLabel(type: number) {
  return Number(type) === 1 ? '百分比' : '固定金额';
}

function splitTypeColor(type: number) {
  return Number(type) === 1 ? 'blue' : 'orange';
}

function tcmBaseLabel(type: number) {
  return Number(type) === 1 ? '处方总价' : '药店利润';
}
</script>

<template>
  <Page auto-content-height title="推广员管理">
    <SalespersonCreateModalComponent />
    <SalespersonCommissionDrawer ref="commissionDrawerRef" />
    <QrCodePreviewModal />

    <div class="mb-4 flex flex-wrap items-center gap-3">
      <Input
        v-model:value="storeKeyword"
        allow-clear
        class="w-52"
        placeholder="诊所名称/拼音首拼"
      />
      <Input
        v-model:value="nickName"
        allow-clear
        class="w-40"
        placeholder="推广员名称"
      />
      <Input
        v-model:value="phone"
        allow-clear
        class="w-40"
        placeholder="手机号"
      />
      <Button type="primary" @click="getList">查询</Button>
      <Button type="primary" @click="openCreateModal">新增推广员</Button>
    </div>

    <Empty v-if="!loading && !listData.items.length" description="暂无推广员" />

    <div
      v-else
      class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
    >
      <Card
        v-for="item in listData.items"
        :key="item.id"
        :loading="loading"
        class="rounded-lg shadow-sm"
      >
        <div class="mb-3 flex items-start justify-between gap-2">
          <div>
            <h3 class="text-lg font-semibold">{{ item.nick_name || '未知' }}</h3>
            <p class="text-sm text-gray-500">{{ item.store_name }}</p>
          </div>
          <Space direction="vertical" align="end" size="small">
            <Tag :color="splitTypeColor(item.split_type)">
              西药·{{ splitTypeLabel(item.split_type) }}
              <template v-if="Number(item.split_type) === 1">
                · {{ item.split }}%
              </template>
            </Tag>
            <Tag v-if="Number(item.tcm_split) > 0" color="green">
              中药·{{ item.tcm_split }}%·{{ tcmBaseLabel(item.tcm_base_type) }}
            </Tag>
            <Tag :color="item.has_admin_account ? 'success' : 'default'">
              {{ item.has_admin_account ? '已开通后台' : '未开通后台' }}
            </Tag>
          </Space>
        </div>

        <div class="mb-3 space-y-1 text-sm text-gray-600">
          <div>{{ item.phone }}</div>
          <Popover trigger="click" title="获客记录">
            <template #content>
              <div class="w-[420px]">
                <SalespersonUserBindDrawer :open="true" :salesperson-id="item.id" />
              </div>
            </template>
            <div class="flex cursor-pointer justify-between hover:text-blue-500">
              <span>累计获客</span>
              <span class="font-medium text-blue-600">{{
                item.count?.user_number ?? 0
              }}</span>
            </div>
          </Popover>
          <div class="flex justify-between">
            <span>待结算</span>
            <span class="text-orange-600">¥{{ item.count?.pending_amount || '0.00' }}</span>
          </div>
        </div>

        <Space wrap>
          <Button size="small" @click="openEditModal(item)">编辑</Button>
          <Button size="small" type="primary" @click="openCommission(item)">
            分成与结算
          </Button>
          <Button
            v-if="item.qr_code?.qr_code"
            size="small"
            @click="openQrCode(item)"
          >
            二维码
          </Button>
          <Button
            v-if="!item.has_admin_account"
            size="small"
            :loading="openingAccountId === item.id"
            @click="handleOpenAdminAccount(item)"
          >
            开通后台
          </Button>
        </Space>
      </Card>
    </div>
  </Page>
</template>
