<script setup lang="ts">
import { h } from 'vue';
import { notification, Row } from 'ant-design-vue';
import { usePagination, useRequest } from 'alova/client';
import { patientsHistoryMethod, patientsHistoryPullMethod, searchTagsFromSelectableMethod, carePatientMethod, patientMethod } from '@/request/api/patient.api';
import type { PatientQuery, PatientReportModel, PatientTagVO } from '@/model';
import { list2Groups } from '@/tools/data';
import { branchMethod } from '@/request/api/system.api';
import { VxeButton, type VxeFormListeners, type VxeFormProps, VxeUI } from 'vxe-pc-ui';
import type { VxeGridInstance, VxeGridListeners, VxeGridProps } from 'vxe-table';
import { getDictionaryMethod } from '@/request/api/dictionary.api';
import { usePermission } from '@/core/usePermission';
import ReportAnalysisCountEdit from '@/components/ReportAnalysisCountEdit.vue';
import PatientEdit from '@/components/PatientEdit.vue';
import EditPatient from '@/components/EditPatient.vue';
import PatientTagEdit from '@/components/PatientTagEdit.vue';
import PatientHealthRecordPreview from '@/components/PatientHealthRecordPreview.vue';
import router from '@/router';
import { editRoleMethod } from '@/request/api/system.api';
const { data: branch, loading: branchLoading } = useRequest(branchMethod);
const { data: selectable, loading: tagsLoading } = useRequest(searchTagsFromSelectableMethod, { initialData: [] });

const model = shallowRef<PatientQuery>();
const searchFormProps = reactive<VxeFormProps<PatientQuery>>({
  titleWidth: 120,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    { field: 'patientName', title: '患者姓名', span: 6, itemRender: { name: 'VxeInput' } },
    { field: 'phone', title: '手机号码', span: 6, itemRender: { name: 'VxeInput', props: { maxLength: 11 } } },
    { field: 'cardno', title: '身份证号', span: 6, itemRender: { name: 'VxeInput', props: { maxLength: 18 } } },
    {
      field: 'isHaveHealthAnalysisReport',
      title: '健康分析报告',
      span: 6,
      itemRender: {
        name: 'VxeRadioGroup',
        options: [
          { label: '有', value: true },
          { label: '无', value: false },
        ],
        props: {
          strict: false,
        },
      },
    },
    {
      field: 'tagIds',
      title: '标签',
      span: 6,
      itemRender: {
        name: 'VxeSelect',
        props: {
          loading: tagsLoading,
          options: computed(() =>
            list2Groups(
              selectable.value.filter((tag) => !tag.disabled),
              'category',
              (key) => ({ 1: '系统标签', 2: '个人标签' })[key]!
            )
          ),
          optionProps: { value: 'id', label: 'name' },
          optionGroupProps: { options: 'groups' },
          clearable: true,
          multiple: true,
          filterable: true,
        },
      },
    },
    {
      field: 'source',
      title: '来源渠道',
      span: 6,
      itemRender: {
        name: 'VxeSelect',
        props: {
          loading: tagsLoading,
          placeholder: '请选择',
          options: computed(() => sourceOptions.value),
          optionProps: { value: 'value', label: 'label' },
          clearable: true,
          filterable: true,
        },
      },
    },
    {
      field: 'sourceInsId',
      title: '来源机构',
      span: 6,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => branchLoading.value),
          options: computed(() => branch.value),
          optionProps: { value: 'id' },
          clearable: true,
        },
      },
    },
    {
      field: 'pcrCount',
      title: '调养次数',
      span: 5,
      itemRender: {
        name: 'VxeNumberInput',
        props: {
          placeholder: '请输入',
          controls: false,
          precision: 0,
          step: 1,
        },
      },
    },
    {
      align: 'right',
      span: 24,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { type: 'submit', content: '查询', status: 'primary' },
          { type: 'reset', content: '清空' },
        ],
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<PatientQuery> = {
  submit({ data }) {
    model.value = { ...data };
  },
  reset({ data }) {
    model.value = { ...data };
  },
};
const sourceOptions = ref<any[]>([
  // { label: '小程序', value: 'miniProgram' },
  // { label: 'H5', value: 'h5' },
  // { label: 'APP', value: 'app' },
  // { label: '其他', value: 'other' },
]);
const sourceOptionsLoading = ref(false);
// 获取来源渠道
async function getSourceTypeOptions() {
  sourceOptionsLoading.value = true;
  try {
    const res = await getDictionaryMethod('patient_source_type');
    console.log(res, 'getSourceTypeOptions');
    if (res?.length > 0) {
      sourceOptions.value = res; // 直接使用返回的数据
      sourceOptionsLoading.value = false;
    }
  } catch (error: any) {
    notification.error({
      message: error?.message ?? '获取来源渠道失败',
    });
    sourceOptionsLoading.value = false;
  } finally {
    sourceOptionsLoading.value = false;
  }
}

const gridRef = ref<VxeGridInstance<PatientReportModel>>();
const gridOptions = reactive<VxeGridProps<PatientReportModel>>({
  id: 'patient-history-list',
  border: false,
  showOverflow: true,
  height: 'auto',
  autoResize: false,
  syncResize: true,
  scrollY: { enabled: true, gt: 0 },
  toolbarConfig: {
    custom: true,
    zoom: true,
    slots: {
      buttons: 'toolbar-buttons',
      tools: 'toolbar-extra',
    },
  },
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    storage: true,
  },
  columns: [
    { type: 'seq', width: 70, fixed: 'left' },
    { field: 'name', title: '姓名', minWidth: 80 },
    { field: 'phone', title: '手机号码', minWidth: 80 },
    { field: 'gender', title: '性别', minWidth: 40, formatter: 'gender' },
    { field: 'age', title: '年龄', minWidth: 40, formatter: ({ cellValue }) => (cellValue ? `${cellValue}岁` : '') },
    { field: 'pcrCount', title: '调养次数', minWidth: 20 },
    { field: 'diagnosis', title: '诊断', minWidth: 40 },
    { field: 'tags', title: '标签' },
    { field: 'source', title: '来源渠道', minWidth: 40 },
    { field: 'sourceInsName', title: '来源机构', minWidth: 40 },
    { field: 'createTime', title: '创建时间' },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 240,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '查看', status: 'primary', name: 'previewPatientHistoryRecord' },
          { content: '充值', status: 'primary', name: 'resetPatientAnalysisCount' },
          { content: '标签', status: 'primary', name: 'editPatientTags' },
          { content: '调养', status: 'primary', name: 'carePatient', hide: usePermission('fdhb:patient:conditioning:create', true) },
          { content: '编辑', status: 'primary', name: 'editPatient' },
        ].filter((item) => !unref(item.hide)),
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'previewPatientHistoryRecord') {
              method = openHistoryPreviewHandle;
            } else if (name === 'resetPatientAnalysisCount') {
              method = openPatientAnalysisCountResetHandle;
            } else if (name === 'editPatientTags') {
              method = openPatientTagsEditHandle;
            } else if (name === 'carePatient') {
              method = openCarePatientHandle;
            } else if (name === 'editPatient') {
              method = editPatientMethod;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

const { loading, page, pageSize, total, onSuccess, replace, refresh, remove } = usePagination((page, size) => patientsHistoryMethod(page, size, model.value), {
  initialData: { data: [], total: 0 },
  initialPage: 1,
  initialPageSize: 100,
  watchingStates: [model],
  immediate: false,
});
onSuccess(({ data: { data } }) => {
  gridRef.value?.loadData(data);
});

// 获取来源机构
// const insLoading = ref(false);
// const insArr = ref<any[]>([]);
// async function getInstitutionList(orgId: number) {
//   insLoading.value = true;
//   const res = await branchMethod(1, 0, orgId);
//   if (res && res.length > 0) {
//     insArr.value = res;
//   }
//   insLoading.value = false;
// }
onMounted(() => {
  model.value = toRaw(searchFormProps.data);
  // getInstitutionList(1);
  getSourceTypeOptions();
});

function openHistoryPreviewHandle({ report, source, sourceInsName, ...patient }: PatientReportModel, index?: number) {
  const id = `drawer:report-history:preview`;
  const onDestroy = () => {
    VxeUI.drawer.close(id);
  };
  onDestroy();
  console.log(patient, source, sourceInsName, 'patient=======');
  VxeUI.drawer.open({
    id,
    title: `健康档案`,
    maskClosable: true,
    escClosable: true,
    padding: false,
    width: window.innerWidth - 256,
    slots: {
      default() {
        return h(PatientHealthRecordPreview, {
          patient,
          report,
          source,
          sourceInsName,
          onDestroy,
          onRefresh() {
            refresh(page.value);
          },
        });
      },
    },
    onHide() {
      VxeUI.modal.close();
    },
  });
}

function openPatientAnalysisCountResetHandle({ report, ...patient }: PatientReportModel) {
  const id = `modal:patient-analysis-count:reset`;
  const onDestroy = () => {
    VxeUI.modal.close(id);
  };
  onDestroy();
  VxeUI.modal.open({
    id,
    title: `充值`,
    maskClosable: true,
    escClosable: true,
    slots: {
      default() {
        return h(ReportAnalysisCountEdit, {
          patient,
          onDestroy,
        });
      },
    },
  });
}
async function openCarePatientHandle({ report, ...patient }: PatientReportModel) {
  // console.log(patient, 'openCarePatientHandle-patient');
  await carePatientMethod(patient.id).then((res) => {
    notification.success({
      message: ``,
      description: '操作成功',
    });
    router.push({ path: '/care/issueService', query: { id: patient.id } });
  });
}
// 编辑患者
async function editPatientMethod({ report, ...patient }: PatientReportModel) {
  const id = `modal:patient-info-handle:edit`;
  const patientId = patient.id;
  const onDestroy = (_refresh?: boolean) => {
    VxeUI.modal.close(id);
    if (_refresh) refresh(1);
  };
  onDestroy();
  VxeUI.modal.open({
    id,
    title: `编辑患者`,
    maskClosable: true,
    escClosable: true,
    width: 500,
    height: 600,
    slots: {
      default() {
        return h(EditPatient, { data: patientId, onDestroy });
      },
    },
  });
}

function openPatientTagsEditHandle({ report, ...patient }: PatientReportModel) {
  const id = `modal:patient-tags:edit`;
  const onDestroy = (tags?: PatientTagVO[]) => {
    if (tags) refresh(page.value);
    VxeUI.modal.close(id);
  };
  onDestroy();
  VxeUI.modal.open({
    id,
    title: `${patient.name} 标签`,
    maskClosable: true,
    escClosable: true,
    slots: {
      default() {
        return h(PatientTagEdit, {
          id: patient.id,
          onDestroy,
        });
      },
    },
  });
}

function openPatientEditHandle() {
  const id = `modal:patient-info-handle:edit`;
  const onDestroy = (_refresh?: boolean) => {
    VxeUI.modal.close(id);
    if (_refresh) refresh(1);
  };
  onDestroy();
  VxeUI.modal.open({
    id,
    title: `新增患者`,
    maskClosable: false,
    escClosable: true,
    slots: {
      default() {
        return h(PatientEdit, { onDestroy });
      },
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits"></vxe-form>
    </header>
    <main class="flex-auto overflow-hidden">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" :loading="loading">
        <template #toolbar-buttons>
          <vxe-button status="primary" @click="openPatientEditHandle()">新增</vxe-button>
        </template>
        <template #toolbar-extra>
          <vxe-button style="margin-right: 12px" icon="vxe-icon-repeat" circle @click="refresh(page)"></vxe-button>
        </template>
      </vxe-grid>
    </main>
    <footer class="flex-none">
      <vxe-pager
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :layouts="['Home', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
      />
    </footer>
  </div>
</template>
<style scoped lang="scss">
.page-container {
  padding: 0 24px;
  max-height: var(--page-main-container);
}
</style>
