<script setup lang="ts">
import { type VxeFormListeners, type VxeFormProps, VxeUI } from 'vxe-pc-ui';
import { usePagination, useRequest } from 'alova/client';
import { notification } from 'ant-design-vue';
import { getDictionaryMethod } from '@/request/api/dictionary.api';
import dayjs from 'dayjs';
import TongueAnalysisReport from '@/components/TongueAnalysisReport.vue';
import type { DeviceReportModel } from '@/model/device.model';
defineOptions({ name: 'EquipmentConfiguredPage' });
import { h } from 'vue';

import type { EquirementQuery } from '@/model/device.model';
// 接口数据
import { deviceReportMethod } from '@/request/api/device.api';
import { branchMethod } from '@/request/api/system.api';
// 获取组织树
const { data: branch, loading: branchLoading } = useRequest(branchMethod(0, 1, 1));

const model = shallowRef<EquirementQuery>();
// 获取设备类型
const deviceTypes = ref<{ id: string; name: string }[]>([]);
const deviceTypesLoading = ref(false);
// 日期验证
const createTimeStart = ref<string>('');
const createTimeEnd = ref<string>('');
// 禁用结束时间的日期（早于开始时间的日期）
function disabledEndDate(current: any) {
  if (!createTimeStart.value) return false;
  return current && current < dayjs(createTimeStart.value);
}

const searchFormProps = reactive<VxeFormProps<EquirementQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      field: 'orgId',
      title: '组织名称',
      span: 6,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => branchLoading.value),
          options: computed(() => branch.value),
          optionProps: { value: 'id', label: 'label' },
          clearable: true,
        },
        events: {
          change(val: any) {
            insArr.value = [];
            if (val.data.orgId) {
              // 清空表单中的机构名称字段
              if (model.value) {
                model.value.institutionId = '';
              }
              getInstitution(val.data.orgId);
            }
          },
        },
      },
    },
    {
      field: 'deviceType',
      title: '设备名称',
      span: 6,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '请选择',
          loading: deviceTypesLoading.value,
          options: computed(() => deviceTypes.value),
          optionProps: { value: 'id', label: 'name' },
          optionGroupProps: { options: 'groups' },
          clearable: true,
          filterable: true,
        },
      },
    },
    {
      field: 'deviceCode',
      title: '设备ID',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },

    {
      field: 'phone',
      title: '手机号码',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'cardno',
      title: '身份证号码',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'createTime',
      title: '生成时间',
      span: 10,
      slots: {
        default: 'createTimes',
      },
    },
    {
      span: 6,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '清空', status: 'warning' },
        ],
        events: {
          click(slotParams, { name }) {},
        },
      },
    },
  ],
});
const insLoading = ref(false);
const insArr = ref<any[]>([]);
async function getInstitution(orgId: string | number) {
  insLoading.value = true;
  const res = await branchMethod(1, 0, Number(orgId));
  if (res && res.length > 0) {
    insArr.value = res;
  }
  insLoading.value = false;
}
const searchFormEmits: VxeFormListeners<EquirementQuery> = {
  // 查询设备登记
  submit({ data }) {
    model.value = {
      ...data,
      createTimeStart: createTimeStart.value ? dayjs(createTimeStart.value).format('YYYY-MM-DD HH:mm:ss') : '',
      createTimeEnd: createTimeEnd.value ? dayjs(createTimeEnd.value).format('YYYY-MM-DD HH:mm:ss') : '',
    } as any;
  },
  // 重置
  reset({ data }) {
    model.value = { ...data } as any;
    createTimeStart.value = '';
    createTimeEnd.value = '';
  },
};
// 设备列表
const gridRef = ref<any>();
const gridOptions = reactive<any>({
  id: 'tag-list',
  border: true,
  showOverflow: true,
  height: 'auto',
  autoResize: false,
  syncResize: true,
  scrollY: { enabled: true, gt: 0 },
  toolbarConfig: {
    custom: true,
    zoom: true,
    slots: {
      tools: 'toolbar-extra',
    },
  },
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    storage: true,
  },
  columns: [
    { field: 'orgName', title: '组织名称' },
    { field: 'deviceType', title: '设备名称' },
    { field: 'deviceCode', title: '设备ID' },
    { field: 'name', title: '用户姓名' },
    { field: 'phone', title: '手机号' },
    { field: 'cardno', title: '身份证号' },
    { field: 'createTime', title: '生成时间' },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 280,
      showOverflow: false,
      slots: {
        default: 'actionButtons',
      },
    },
  ],
  data: [],
});
const gridEvents: any = {};

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

// 获取设备类型
async function getDeviceType() {
  deviceTypesLoading.value = true;
  const res = await getDictionaryMethod('fdhb_device_type');
  if (res && res.length > 0) {
    deviceTypes.value = res.map((item: any) => ({
      id: item.value,
      name: item.label,
    }));
  }
  deviceTypesLoading.value = false;
}

onMounted(() => {
  getDeviceType();
  model.value = toRaw(searchFormProps.data);
});

// 查看健康分析报告
function openHistoryPreviewHandle(row: any) {
  console.log(row, '健康分析报告');
  const component = defineAsyncComponent(() => import('@/components/ReportPreview.vue'));
  const id = `drawer:report:preview`;
  const onDestroy = () => {
    VxeUI.drawer.close(id);
  };
  onDestroy();
  VxeUI.drawer.open({
    id,
    mask: true,
    lockView: false,
    padding: false,
    width: window.innerWidth - 256,
    escClosable: true,
    maskClosable: true,
    title: `健康分析报告`,
    slots: {
      default() {
        return h(component, {
          reportId: row.healthAnalysisReportId?.toString(),
          onDestroy,
        });
      },
    },
  });
}
// 脉象报告
function pulseAnalysisReport(row: any) {
  console.log(row, '脉象报告');
  const id = `drawer:report-pulse:preview`;
  const onDestroy = () => {
    VxeUI.drawer.close(id);
  };
  onDestroy();

  // 构建脉象报告URL，可以根据row数据动态生成
  // const reportUrl = `https://hybrid.reborn-tech.com/report.html#/?mid=d78511637507423fb4323ab4cc38210e&access_session=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBJZCI6ImhKbjVEM3JyIiwiYXBwU2VjcmV0IjoiMGYwZDQ1MDIyNmYzMTZkNjY4ZDZlYjhiY2ZiYjRhY2NhNGNjYzQ3ZiJ9.Gnk2gUdO5EsN_C8fvwj9QaWpiNGizzFAypERKPk_u7A&appId=hJn5D3rr`;
  const reportUrl = row?.pulseAnalysisReportUrl;
  VxeUI.drawer.open({
    id,
    title: `脉象报告`,
    maskClosable: true,
    escClosable: true,
    padding: false,
    width: window.innerWidth - 256,
    slots: {
      default() {
        return h(
          'div',
          {
            style: {
              width: '100%',
              height: '100%',
              border: 'none',
              overflow: 'hidden',
              position: 'relative',
            },
          },
          [
            h('iframe', {
              src: reportUrl,
              style: {
                width: '100%',
                height: '100%',
                border: 'none',
                display: 'block',
              },
              allow: 'camera; microphone; geolocation; payment; usb; vr; accelerometer; gyroscope; magnetometer; ambient-light-sensor; cross-origin-isolated',
              sandbox: 'allow-same-origin allow-scripts allow-forms allow-popups allow-presentation allow-downloads',
              onLoad: () => {
                console.log('脉象报告页面加载完成');
              },
              onError: (error: any) => {
                console.error('脉象报告页面加载失败:', error);
                // 可以在这里显示错误提示
              },
            }),
          ]
        );
      },
    },
    onHide() {
      VxeUI.modal.close();
    },
  });
}
// 舌面分析报告
function tongueAndFaceAnalysisReport(row: any) {
  console.log(row, '舌面分析报告');
  const id = `drawer:report-tongue:preview`;
  const onDestroy = () => {
    VxeUI.drawer.close(id);
  };
  VxeUI.drawer.open({
    id,
    title: `舌面分析报告`,
    maskClosable: true,
    escClosable: true,
    padding: false,
    width: window.innerWidth - 256,
    slots: {
      default() {
        return h(TongueAnalysisReport, {
          report: row,
          onDestroy,
          onRefresh() {
            refresh(page.value);
          },
        });
      },
    },
    onHide() {
      VxeUI.modal.close();
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none mt-4">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits">
        <template #createTimes>
          <div class="date-range-container">
            <a-date-picker v-model:value="createTimeStart" placeholder="请选择开始时间" style="flex: 1" :show-time="{ format: 'HH:mm' }" />
            <span class="date-separator">至</span>
            <a-date-picker v-model:value="createTimeEnd" placeholder="请选择结束时间" style="flex: 1" :disabledDate="disabledEndDate" :show-time="{ format: 'HH:mm' }" />
          </div>
        </template>
      </vxe-form>
    </header>
    <main class="flex-auto overflow-hidden">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" :loading="loading">
        <template #toolbar-extra>
          <vxe-button style="margin-right: 12px" icon="vxe-icon-repeat" circle @click="refresh(page)"></vxe-button>
        </template>

        <!-- 动态操作按钮 -->
        <template #actionButtons="{ row }">
          <vxe-button-group mode="text">
            <!-- 健康分析报告 - 根据 healthAnalysisReportId 判断 -->
            <vxe-button v-if="row.healthAnalysisReportId" status="primary" @click="openHistoryPreviewHandle(row)"> 健康分析报告 </vxe-button>
            <!-- 脉象报告 - 根据 pulseAnalysisReportId 判断 -->
            <vxe-button v-if="row.pulseAnalysisReportId" status="primary" @click="pulseAnalysisReport(row)"> 脉象报告 </vxe-button>
            <!-- 舌面分析报告 - 根据 tonguefaceAnalysisReportId 判断 -->
            <vxe-button v-if="row.tonguefaceAnalysisReportId" status="primary" @click="tongueAndFaceAnalysisReport(row)"> 舌面分析报告 </vxe-button>
          </vxe-button-group>
        </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);
}
.date-range-container {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;

  .vxe-input {
    flex: 1;
    min-width: 0;
  }

  .date-separator {
    color: #666;
    font-size: 14px;
    font-weight: 500;
    white-space: nowrap;
    padding: 0 8px;
  }
}
</style>
