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

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

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

import {
  openAdminAccountApi,
  salespersonListApi,
} from '#/views/business/store/settings/api';
import QrCodePreview from '#/views/business/store/settings/components/SalespersonQrCodePreview.vue';
import SalespersonCommissionDrawer from '#/views/business/store/settings/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 bindDrawerOpen = ref(false);
const bindDrawerSalespersonId = ref(0);
const openingAccountId = ref(0);

const getList = () => {
  salespersonListApi().then((res) => {
    listData.value = {
      total: res?.total ?? 0,
      items: res?.items ?? [],
    };
  });
};

getList();

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

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

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

function openCommissionDrawer(item: any) {
  commissionDrawerRef.value?.open({
    id: item.id,
    nick_name: item.nick_name,
  });
}

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

function openCreateModal() {
  SalespersonCreateModalApi.setData({ getList });
  SalespersonCreateModalApi.open();
}

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

function openBindDrawer(item: any) {
  bindDrawerSalespersonId.value = item.id;
  bindDrawerOpen.value = true;
}

async function handleOpenAdminAccount(item: any) {
  openingAccountId.value = item.id;
  try {
    await openAdminAccountApi({ salesperson_id: item.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>
  <div>
    <SalespersonCreateModalComponent />
    <QrCodePreviewModal />
    <SalespersonCommissionDrawer ref="commissionDrawerRef" @settled="getList" />

    <div v-if="!listData.items.length" class="py-12">
      <Empty description="暂无推广员">
        <Button type="primary" @click="openCreateModal">新增推广员</Button>
      </Empty>
    </div>

    <template v-else>
      <div class="mb-4 flex items-center justify-between">
        <span class="text-sm text-gray-600"
          >共 {{ listData.total }} 位推广员</span
        >
        <Button type="primary" @click="openCreateModal">新增推广员</Button>
      </div>
      <div
        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"
          class="rounded-lg shadow-sm"
        >
          <div class="mb-3 flex items-start justify-between gap-2">
            <h3 class="text-lg font-semibold">{{ item.nick_name || '未知' }}</h3>
            <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-4 space-y-1.5 text-sm text-gray-600">
            <div>{{ item.phone }}</div>
            <div>加入：{{ item.created_at }}</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 pt-1 hover:text-blue-500"
                @click="openBindDrawer(item)"
              >
                <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="font-medium text-orange-600"
                >¥{{ item.count?.pending_amount || '0.00' }}</span
              >
            </div>
            <div class="flex justify-between">
              <span>已结算</span>
              <span class="font-medium text-green-600"
                >¥{{ item.count?.settled_amount || '0.00' }}</span
              >
            </div>
          </div>

          <Space wrap class="w-full">
            <Button size="small" type="primary" @click="openCommissionDrawer(item)">
              分成与结算
            </Button>
            <Button size="small" @click="openEditModal(item)">编辑</Button>
            <Button
              v-if="Number(item.split_type) === 0"
              size="small"
              type="primary"
              @click="openEditModal(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>
    </template>
  </div>
</template>
