<script lang="ts" setup>
/**
 * 门店详情弹窗（诊所/药店）
 * 布局对齐医生档案：顶部统计 + 左侧竖向 Tabs
 */
import type { Dayjs } from 'dayjs';

import { computed, ref } from 'vue';

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

import dayjs from 'dayjs';
import {
  Avatar,
  Button,
  DatePicker,
  Descriptions,
  Empty,
  Image,
  Select,
  Spin,
  Table,
  Tabs,
  Tag,
  message,
} from 'ant-design-vue';

import DoctorCardModal from '#/views/doctor/doctor/components/DoctorCardModal.vue';
import { getStoreBankCardReportDetail } from '#/views/system/store-bank-card/api';
import {
  getStoreCardApi,
  getStoreCardStatsApi,
  getStoreDrugsByTypeApi,
  openQrCodeApi,
} from '#/views/system/store/api';
import { getSalespersonList } from '#/views/system/store/api/salesperson';
import { resolveAvatarUrl } from '#/views/system/store-input/utils/inputUser';
import AddDoctorFromStoreModal from '#/views/system/store/components/AddDoctorFromStoreModal.vue';
import { canAddStoreDoctor } from '#/views/system/admin/_shared/platform-admin-role';

const RangePicker = DatePicker.RangePicker;

const userStore = useUserStore();
// 是否允许「添加医生」：超管/管理员/省经理/市经理/业务员
const canAddDoctor = computed(() => canAddStoreDoctor(userStore.userInfo));

const storeId = ref(0);
const loading = ref(false);
const activeTab = ref('basic');
const cardData = ref<any>(null);
const searchTime = ref<[Dayjs, Dayjs]>([
  dayjs().startOf('month'),
  dayjs(),
]);

const bankLoading = ref(false);
const bankDetail = ref<any>(null);

const drugType = ref(2);
const drugLoading = ref(false);
const drugList = ref<any[]>([]);

const promoterLoading = ref(false);
const promoterList = ref<any[]>([]);

const generatingQr = ref(false);

const store = computed(() => cardData.value?.store ?? {});
const stats = computed(() => cardData.value?.stats_summary ?? {});
const doctorList = computed(() => cardData.value?.doctor_list ?? []);
const isClinic = computed(() => Number(store.value?.type) === 0);
const isPharmacy = computed(() => Number(store.value?.type) === 1);
/** 按门店类型区分诊所/药店文案，避免药店仍显示「诊所」 */
const storeKindLabel = computed(() => (isPharmacy.value ? '药店' : '诊所'));
const qrTabLabel = computed(() => `${storeKindLabel.value}二维码`);
const modalTitle = computed(() => {
  const name = store.value?.name;
  if (!name) return '门店详情';
  return `${storeKindLabel.value}详情 · ${name}`;
});

const drugTypeOptions = [
  { label: '中药', value: 1 },
  { label: '西药', value: 2 },
  { label: '保健食品', value: 3 },
  { label: '产品服务包', value: 5 },
  { label: '非药品', value: 6 },
  { label: '医疗器械', value: 7 },
];

const drugColumns = [
  { title: '药品名称', dataIndex: 'drug_name', key: 'drug_name', ellipsis: true },
  { title: '规格', dataIndex: 'specification', key: 'specification', width: 140 },
  { title: '售价', dataIndex: 'price', key: 'price', width: 100 },
  { title: '进价', dataIndex: 'buy_price', key: 'buy_price', width: 100 },
];

const promoterColumns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '姓名', dataIndex: 'name', key: 'name' },
  { title: '手机号', dataIndex: 'phone', key: 'phone', width: 140 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
];

const [Modal, modalApi] = useVbenModal({
  class: 'w-[900px] xl:w-[1100px]',
  fullscreenButton: true,
  footer: false,
  draggable: true,
  closeOnClickModal: false,
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const data = modalApi.getData<Record<string, any>>() || {};
    storeId.value = Number(data.storeId || data.id || 0);
    activeTab.value = 'basic';
    searchTime.value = [dayjs().startOf('month'), dayjs()];
    bankDetail.value = null;
    drugList.value = [];
    promoterList.value = [];
    if (storeId.value) {
      loadCard();
    }
  },
});

const [DoctorModal, DoctorModalApi] = useVbenModal({
  connectedComponent: DoctorCardModal,
});

/** 添加医生弹窗：诊所详情医生团队 Tab 内入口 */
const [AddDoctorModal, AddDoctorModalApi] = useVbenModal({
  connectedComponent: AddDoctorFromStoreModal,
});

/**
 * 打开「添加医生」弹窗：默认绑定当前门店，提交成功后刷新医生团队列表
 */
const openAddDoctorModal = () => {
  AddDoctorModalApi.setData({
    storeId: storeId.value,
    storeName: (store.value as any)?.name || '',
    onSuccess: () => {
      loadCard();
    },
  });
  AddDoctorModalApi.open();
};

function searchTimeParam(): [string, string] {
  return [
    searchTime.value[0].format('YYYY-MM-DD 00:00:00'),
    searchTime.value[1].format('YYYY-MM-DD 23:59:59'),
  ];
}

/** 加载门店卡片概览 */
async function loadCard() {
  if (!storeId.value) return;
  loading.value = true;
  try {
    const res = await getStoreCardApi({
      id: storeId.value,
      search_time: searchTimeParam(),
    });
    cardData.value = res;
    if (isPharmacy.value) {
      drugType.value = 2;
    }
  } catch (e: any) {
    message.error(e?.message || '加载门店详情失败');
  } finally {
    loading.value = false;
  }
}

/** 仅刷新统计 */
async function refreshStats() {
  if (!storeId.value) return;
  try {
    const res = await getStoreCardStatsApi({
      id: storeId.value,
      search_time: searchTimeParam(),
    });
    if (cardData.value) {
      cardData.value = {
        ...cardData.value,
        stats_summary: res.stats_summary,
        search_time: res.search_time,
      };
    }
  } catch (e: any) {
    message.error(e?.message || '刷新统计失败');
  }
}

async function loadBank() {
  if (!storeId.value || bankDetail.value) return;
  bankLoading.value = true;
  try {
    bankDetail.value = await getStoreBankCardReportDetail(storeId.value);
  } catch {
    bankDetail.value = null;
  } finally {
    bankLoading.value = false;
  }
}

async function loadDrugs() {
  if (!storeId.value) return;
  drugLoading.value = true;
  try {
    const res = await getStoreDrugsByTypeApi(storeId.value, drugType.value);
    const list = Array.isArray(res) ? res : res?.items || res?.list || [];
    drugList.value = (list || []).map((item: any) => {
      const drug = item.drug || {};
      return {
        id: item.id,
        drug_name: drug.drug_name || item.drug_name || '-',
        specification: drug.specification || item.specification || '-',
        price: item.price ?? '-',
        buy_price: item.buy_price ?? '-',
      };
    });
  } catch {
    drugList.value = [];
  } finally {
    drugLoading.value = false;
  }
}

async function loadPromoters() {
  if (!storeId.value || promoterList.value.length > 0) return;
  promoterLoading.value = true;
  try {
    const res = await getSalespersonList({
      store_id: storeId.value,
      page: 1,
      pageSize: 100,
    });
    const list = res?.items || res?.list?.items || res || [];
    promoterList.value = Array.isArray(list) ? list : [];
  } catch {
    promoterList.value = [];
  } finally {
    promoterLoading.value = false;
  }
}

function onTabChange(key: string | number) {
  activeTab.value = String(key);
  if (key === 'bank') loadBank();
  if (key === 'drugs') loadDrugs();
  if (key === 'promoters') loadPromoters();
}

function openDoctor(suId: number) {
  DoctorModalApi.setData({ su_id: suId, hideStoresTab: true, readonly: true });
  DoctorModalApi.open();
}

async function ensureQrCode() {
  if (cardData.value?.qr_code || store.value?.qr_code) return;
  generatingQr.value = true;
  try {
    await openQrCodeApi(storeId.value);
    await loadCard();
    message.success('二维码已生成');
  } catch (e: any) {
    message.error(e?.message || '生成二维码失败');
  } finally {
    generatingQr.value = false;
  }
}

function clinicTypeText(v: number) {
  if (v === 1) return '西医诊所';
  if (v === 2) return '中医诊所';
  return '未设置';
}
</script>

<template>
  <Modal :title="modalTitle">
    <AddDoctorModal />
    <Spin :spinning="loading">
      <div v-if="cardData" class="mb-4 flex flex-wrap items-center justify-between gap-3 px-1">
        <div class="text-sm text-muted-foreground">统计时间范围</div>
        <RangePicker
          v-model:value="searchTime"
          format="YYYY-MM-DD"
          @change="refreshStats"
        />
      </div>

      <!-- 顶部统计 -->
      <div
        v-if="cardData"
        class="mb-6 grid grid-cols-1 gap-4 px-1 md:grid-cols-3"
      >
        <div
          class="relative flex flex-col overflow-hidden rounded-xl border border-blue-100 bg-blue-50 p-5 shadow-sm transition-all group hover:shadow-md dark:border-blue-800/50 dark:bg-blue-900/20"
        >
          <span class="text-sm font-semibold text-blue-600/80 dark:text-blue-300/80">
            销售额
          </span>
          <div class="mt-2 text-2xl font-bold text-blue-900 dark:text-blue-100">
            <span class="text-lg">¥</span>
            {{ Number(stats.sales_amount ?? 0).toFixed(2) }}
          </div>
        </div>
        <div
          class="relative flex flex-col overflow-hidden rounded-xl border border-emerald-100 bg-emerald-50 p-5 shadow-sm transition-all group hover:shadow-md dark:border-emerald-800/50 dark:bg-emerald-900/20"
        >
          <span class="text-sm font-semibold text-emerald-600/80 dark:text-emerald-300/80">
            利润
          </span>
          <div class="mt-2 text-2xl font-bold text-emerald-900 dark:text-emerald-100">
            <span class="text-lg">¥</span>
            {{ Number(stats.profit ?? 0).toFixed(2) }}
          </div>
        </div>
        <div
          class="relative flex flex-col overflow-hidden rounded-xl border border-purple-100 bg-purple-50 p-5 shadow-sm transition-all group hover:shadow-md dark:border-purple-800/50 dark:bg-purple-900/20"
        >
          <span class="text-sm font-semibold text-purple-600/80 dark:text-purple-300/80">
            处方量
          </span>
          <div class="mt-2 text-2xl font-bold text-purple-900 dark:text-purple-100">
            {{ stats.prescription_count ?? 0 }}
            <span class="text-xs font-normal text-purple-700/60 dark:text-purple-300/60">
              张
            </span>
          </div>
        </div>
      </div>

      <Tabs
        :active-key="activeTab"
        tab-position="left"
        class="custom-vertical-tabs min-h-[480px]"
        @change="onTabChange"
      >
        <Tabs.TabPane key="basic" tab="门店基本信息">
          <div class="pl-4">
            <Descriptions bordered :column="2" size="small">
              <Descriptions.Item label="名称">
                {{ store.name || '-' }}
              </Descriptions.Item>
              <Descriptions.Item label="ID">{{ store.id }}</Descriptions.Item>
              <Descriptions.Item label="类型">
                {{ isPharmacy ? '药店' : '诊所' }}
              </Descriptions.Item>
              <Descriptions.Item v-if="isClinic" label="诊所类型">
                {{ clinicTypeText(Number(store.clinic_type)) }}
              </Descriptions.Item>
              <Descriptions.Item label="联系人">
                {{ store.contact || '-' }}
              </Descriptions.Item>
              <Descriptions.Item label="手机号">
                {{ store.mobile || '-' }}
              </Descriptions.Item>
              <Descriptions.Item label="地址" :span="2">
                {{ store.position || store.address || '-' }}
              </Descriptions.Item>
              <Descriptions.Item label="ERP ID">
                {{ store.erp_id || '-' }}
              </Descriptions.Item>
              <Descriptions.Item label="MES ID">
                {{ store.mes_id || '-' }}
              </Descriptions.Item>
              <Descriptions.Item label="银行卡报备">
                {{ store.bank_card_report_status_text || '-' }}
              </Descriptions.Item>
              <Descriptions.Item label="业务员">
                {{ store.new_admin?.nick_name || '-' }}
              </Descriptions.Item>
            </Descriptions>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="bank" tab="银行卡">
          <div class="pl-4">
            <Spin :spinning="bankLoading">
              <template v-if="bankDetail">
                <Descriptions bordered :column="2" size="small">
                  <Descriptions.Item label="户名">
                    {{ bankDetail.bank_user_name || bankDetail.account_name || store.bank_user_name || '-' }}
                  </Descriptions.Item>
                  <Descriptions.Item label="卡号">
                    {{ bankDetail.bank_card || bankDetail.card_no || store.bank_card || '-' }}
                  </Descriptions.Item>
                  <Descriptions.Item label="开户行">
                    {{ bankDetail.bank_name || store.bank_name || '-' }}
                  </Descriptions.Item>
                  <Descriptions.Item label="联行号">
                    {{ bankDetail.bank_no || store.bank_no || '-' }}
                  </Descriptions.Item>
                  <Descriptions.Item label="报备状态">
                    {{ bankDetail.report_status_text || store.bank_card_report_status_text || '-' }}
                  </Descriptions.Item>
                  <Descriptions.Item label="账户类型">
                    {{ bankDetail.bank_account_type ?? store.bank_account_type ?? '-' }}
                  </Descriptions.Item>
                </Descriptions>
              </template>
              <Empty v-else description="暂无银行卡报备信息，展示门店预留信息">
                <Descriptions bordered :column="2" size="small" class="mt-4 text-left">
                  <Descriptions.Item label="户名">
                    {{ store.bank_user_name || '-' }}
                  </Descriptions.Item>
                  <Descriptions.Item label="卡号">
                    {{ store.bank_card || '-' }}
                  </Descriptions.Item>
                  <Descriptions.Item label="开户行">
                    {{ store.bank_name || '-' }}
                  </Descriptions.Item>
                  <Descriptions.Item label="联行号">
                    {{ store.bank_no || '-' }}
                  </Descriptions.Item>
                </Descriptions>
              </Empty>
            </Spin>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane v-if="isClinic" key="doctors" tab="诊所医生团队">
          <div class="pl-4">
            <div v-if="canAddDoctor" class="mb-3">
              <Button
                type="primary"
                size="small"
                @click="openAddDoctorModal"
              >
                添加医生
              </Button>
            </div>
            <Empty v-if="doctorList.length === 0" description="暂无医生" />
            <div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2">
              <div
                v-for="item in doctorList"
                :key="item.su_id"
                class="flex items-center gap-3 rounded-lg border border-gray-100 p-3 dark:border-slate-700"
              >
                <Avatar :src="resolveAvatarUrl(item.doctor?.avatar)" :size="48" />
                <div class="min-w-0 flex-1">
                  <Button type="link" class="!px-0" @click="openDoctor(item.doctor?.su_id || item.su_id)">
                    {{ item.doctor?.name || '未知医生' }}
                  </Button>
                  <div class="text-xs text-muted-foreground">
                    {{ item.doctor?.mobile || '-' }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane v-if="isPharmacy" key="drugs" tab="药店药品">
          <div class="pl-4">
            <div class="mb-3 flex items-center gap-2">
              <span class="text-sm text-muted-foreground">药品类型</span>
              <Select
                v-model:value="drugType"
                :options="drugTypeOptions"
                style="width: 160px"
                @change="loadDrugs"
              />
            </div>
            <Table
              :columns="drugColumns"
              :data-source="drugList"
              :loading="drugLoading"
              :pagination="false"
              row-key="id"
              size="small"
              :scroll="{ y: 360 }"
            />
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="qr" :tab="qrTabLabel">
          <div class="flex flex-col items-center gap-4 py-6 pl-4">
            <template v-if="cardData?.qr_code || store.qr_code">
              <Image
                :src="cardData?.qr_code || store.qr_code"
                :width="200"
                :preview="true"
              />
              <div class="text-sm text-muted-foreground">
                {{ store.name }} {{ qrTabLabel }}
              </div>
            </template>
            <template v-else>
              <Empty :description="`尚未生成${storeKindLabel}二维码`" />
              <Button type="primary" :loading="generatingQr" @click="ensureQrCode">
                生成{{ storeKindLabel }}二维码
              </Button>
            </template>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="promoters" tab="门店推广员">
          <div class="pl-4">
            <Table
              :columns="promoterColumns"
              :data-source="promoterList"
              :loading="promoterLoading"
              :pagination="false"
              row-key="id"
              size="small"
              :scroll="{ y: 360 }"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'name'">
                  {{ record.name || record.nick_name || '-' }}
                </template>
                <template v-if="column.key === 'status'">
                  <Tag>{{ record.status ?? '-' }}</Tag>
                </template>
              </template>
            </Table>
          </div>
        </Tabs.TabPane>
      </Tabs>
    </Spin>
  </Modal>
  <DoctorModal />
</template>

<style scoped>
:deep(.custom-vertical-tabs .ant-tabs-nav) {
  width: 140px;
}
:deep(.custom-vertical-tabs .ant-tabs-tab) {
  padding: 12px 16px;
  margin-bottom: 4px;
  border-radius: 6px;
  transition: all 0.3s;
}
:deep(.custom-vertical-tabs .ant-tabs-tab-active) {
  background-color: var(
    --ant-primary-color-active-deprecated-f-12,
    rgba(22, 119, 255, 0.08)
  );
}
</style>
