<script lang="ts" setup>
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { ref } from 'vue';

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

import { Button, message, Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import { auditApi, openPcWindowsApi, refuseApi } from './api';
import BindDepart from './components/BindDepartModal.vue';
import BindStore from './components/BindStoreModal.vue';
import BindSubjects from './components/BindSubjectsModal.vue';
import BindTitle from './components/BindTitleModal.vue';
import DoctorBasicInfoCell from './components/cells/DoctorBasicInfoCell.vue';
import DoctorProfessionalInfoCell from './components/cells/DoctorProfessionalInfoCell.vue';
import FormModalDemo from './components/modal.vue';
import DoctorCardModal from './components/DoctorCardModal.vue';
import ScheduleCalendarModal from './components/schedule-calendar/ScheduleCalendarModal.vue';
import ScheduleDrawerComp from './components/ScheduleDrawer.vue';
import StoreSettingModalComp from './components/StoreSettingModal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

const hasTopTableDropDownActions = ref(false);

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

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

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalDemo,
});

const [BindStoreModal, BindStoreModalApi] = useVbenModal({
  connectedComponent: BindStore,
});

const [BindSubjectsModal, BindSubjectsModalApi] = useVbenModal({
  connectedComponent: BindSubjects,
});

const [BindDepartModal, BindDepartModalApi] = useVbenModal({
  connectedComponent: BindDepart,
});

const [BindTitleModal, BindTitleModalApi] = useVbenModal({
  connectedComponent: BindTitle,
});

const [DoctorCardModals, DoctorCardModalApi] = useVbenModal({
  connectedComponent: DoctorCardModal,
});

/** 排班设置抽屉（真排班：每天/按星期 × 全天/上下午/自定义时段） */
const [ScheduleDrawer, ScheduleDrawerApi] = useVbenDrawer({
  connectedComponent: ScheduleDrawerComp,
});

/** 门店统一可预约天数设置弹窗 */
const [StoreSettingModal, StoreSettingModalApi] = useVbenModal({
  connectedComponent: StoreSettingModalComp,
});

const showModal = (data = {}, isUpdate = false) => {
  formModalApi.setData({
    values: data,
    update: isUpdate,
    gridApi,
  });
  formModalApi.open();
};

/** 打开绑定诊所弹窗 */
const showBindStoreModal = (row: Record<string, any>) => {
  BindStoreModalApi.setData({
    values: row,
    gridApi,
  });
  BindStoreModalApi.open();
};

/** 打开绑定诊疗科目弹窗 */
const showBindSubjectsModal = (row: Record<string, any>) => {
  BindSubjectsModalApi.setData({
    values: row,
    gridApi,
  });
  BindSubjectsModalApi.open();
};

/** 打开编辑科室弹窗 */
const showBindDepartModal = (row: Record<string, any>) => {
  BindDepartModalApi.setData({
    values: row,
    gridApi,
  });
  BindDepartModalApi.open();
};

/** 打开编辑职称弹窗 */
const showBindTitleModal = (row: Record<string, any>) => {
  BindTitleModalApi.setData({
    values: row,
    gridApi,
  });
  BindTitleModalApi.open();
};

const showDoctorCard = (row: Record<string, any>) => {
  DoctorCardModalApi.setData({
    id: row.id,
    su_id: row.su_id,
    gridApi,
  });
  DoctorCardModalApi.open();
};

/** 打开排班设置抽屉 */
const showScheduleDrawer = (row: Record<string, any>) => {
  ScheduleDrawerApi.setData({ record: row });
  ScheduleDrawerApi.open();
};

/** 排班日历弹窗（按日期排班，锁定该医生） */
const scheduleCalendarModalRef = ref<InstanceType<typeof ScheduleCalendarModal>>();

/**
 * 打开排班日历（锁定医生模式）
 * 店上下文取医生关联门店（列表行已带 stores）：单店直接进，多店弹窗顶部可切换；
 * 未关联门店时排班无模板归属也无患者入口，直接提示先绑定诊所
 */
const showScheduleCalendar = (row: Record<string, any>) => {
  const stores = (Array.isArray(row.stores) ? row.stores : [])
    .filter((s: any) => s?.store?.id)
    .map((s: any) => ({ id: Number(s.store.id), name: String(s.store.name || '') }));
  if (stores.length === 0) {
    message.warning('该医生未关联任何诊所，请先绑定诊所后再排班');
    return;
  }
  scheduleCalendarModalRef.value?.ModalApi?.setData({
    storeId: stores[0]!.id,
    storeName: stores[0]!.name,
    storeOptions: stores,
    lockedDoctorId: Number(row.su_id || 0),
    lockedDoctorName: String(row.name || ''),
  });
  scheduleCalendarModalRef.value?.ModalApi?.open();
};

/** 打开门店统一设置弹窗 */
const showStoreSettingModal = () => {
  StoreSettingModalApi.open();
};

const openPcWindows = (id: number) => {
  openPcWindowsApi(id).then(() => {
    message.success('开通成功!');
    gridApi.query();
  });
};

const audit = (id: number) => {
  auditApi(id).then(() => {
    message.success('审核成功!');
    gridApi.query();
  });
};

const refuse = (id: number) => {
  refuseApi(id).then(() => {
    message.success('审核成功!');
    gridApi.query();
  });
};
</script>

<template>
  <Page auto-content-height title="医生管理">
    <FormModal />
    <BindStoreModal />
    <BindSubjectsModal />
    <BindDepartModal />
    <BindTitleModal />
    <DoctorCardModals />
    <ScheduleDrawer />
    <ScheduleCalendarModal ref="scheduleCalendarModalRef" />
    <StoreSettingModal />
    <Grid>
      <template #toolbar-actions>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              onClick: showModal.bind(null),
            },
            {
              label: '排班统一设置',
              type: 'default',
              icon: 'ant-design:setting-outlined',
              onClick: showStoreSettingModal,
            },
          ]"
          :drop-down-actions="[]"
        >
          <template #more>
            <Button style="margin-left: 16px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #doctor_basic_info="{ row }">
        <DoctorBasicInfoCell
          :row="row"
          :on-open-card="showDoctorCard"
          :on-refresh="() => gridApi.query()"
        />
      </template>
      <template #doctor_professional_info="{ row }">
        <DoctorProfessionalInfoCell
          :row="row"
          :on-edit-depart="showBindDepartModal"
          :on-edit-title="showBindTitleModal"
          :on-edit-subjects="showBindSubjectsModal"
          :on-edit-stores="showBindStoreModal"
        />
      </template>
      <template #service-user="{ row }">
        <Tag v-if="row.service_user?.status === 2" color="success">已通过</Tag>
        <Tag v-else-if="row.service_user?.status === 0" color="blue">
          待激活
        </Tag>
        <Tag v-else-if="row.service_user?.status === 1" color="warning">
          待审核
        </Tag>
        <Tag v-else-if="row.service_user?.status === 3" color="error">
          已拒绝
        </Tag>
        <Tag v-else-if="row.service_user?.status === -1" color="error">
          已停用
        </Tag>
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '医生卡片',
              type: 'link',
              icon: 'ant-design:idcard-outlined',
              size: 'small',
              onClick: showDoctorCard.bind(null, row),
            },
            {
              label: '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              onClick: showModal.bind(null, row, true),
            },
            {
              label: '排班设置',
              type: 'link',
              icon: 'ant-design:calendar-outlined',
              size: 'small',
              onClick: showScheduleDrawer.bind(null, row),
            },
            {
              label: '排班日历',
              type: 'link',
              icon: 'ant-design:schedule-outlined',
              size: 'small',
              onClick: showScheduleCalendar.bind(null, row),
            },
            {
              label: '开通PC端',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              onClick: openPcWindows.bind(null, row.id),
            },
          ]"
          :drop-down-actions="[
            {
              label: '审核通过',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              ifShow: row.service_user?.status === 1,
              onClick: audit.bind(null, row.id),
            },
            {
              label: '拒绝审核',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              ifShow: row.service_user?.status === 1,
              onClick: refuse.bind(null, row.id),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
