<script setup lang="ts">
import { type VxeFormListeners, type VxeFormProps, type VxeGridInstance, type VxeGridListeners, type VxeGridProps, 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 EditEquirement from '@/components/EditEquirement.vue';
import EditOrganization from '@/components/EditOrganization.vue';

import type { EquirementModel, EquirementQuery } from '@/model/device.model';

// 接口数据
import { allTagsSearchMethod } from '@/request/api/follow.api';
import { getDeviceRegisterMethod, deleteDeviceRegisterMethod, updateDeviceRegisterOrganizationMethod } from '@/request/api/device.api';
import { branchMethod } from '@/request/api/system.api';
(notification.config as any)({
  zIndex: 10000, // 直接设置层级
});
// 获取设备列表
const { data: tags, loading: tagsLoading } = useRequest(getDeviceRegisterMethod, {
  initialData: { total: 0, data: [] },
});
const { data: branch, loading: branchLoading } = useRequest(branchMethod(0, 1, 1));

// 获取组织名称
const { data: organizationData, loading: organizationDataLoading } = useRequest(allTagsSearchMethod, {
  initialData: { total: 0, data: [] },
});

const model = shallowRef<EquirementQuery>();

// 获取设备类型
const deviceTypes = ref<{ id: string; name: string }[]>([]);
const deviceTypesLoading = ref(false);

// 日期验证
const updateTimeStart = ref<string>('');
const updateTimeEnd = ref<string>('');
// 禁用结束时间的日期（早于开始时间的日期）
function disabledEndDate(current: any) {
  if (!updateTimeStart.value) return false;
  return current && current < dayjs(updateTimeStart.value);
}

const searchFormProps = reactive<VxeFormProps<EquirementQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      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: '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);
            }
          },
        },
      },
    },
    {
      span: 6,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '清空', status: 'warning' },
          { name: 'add', content: '新增', status: 'primary' },
          { name: 'import', content: '批量修改', status: 'primary' },
        ],
        events: {
          click(slotParams, { name }) {
            if (name === 'add') {
              // 新增
              editEquirement();
            } else if (name === 'import') {
              // 批量修改
              importOrganization();
            }
          },
        },
      },
    },
    {
      field: 'institutionId',
      title: '机构名称',
      span: 6,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => insLoading.value),
          options: computed(() => insArr.value),
          optionProps: { value: 'id', label: 'label' },
          clearable: true,
        },
      },
    },
    {
      field: 'updateBy',
      title: '修改人',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'updateTime',
      title: '修改时间',
      span: 10,
      slots: {
        default: 'createTimes',
      },
    },
  ],
});
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,
      updateTimeStart: updateTimeStart.value ? dayjs(updateTimeStart.value).format('YYYY-MM-DD HH:mm:ss') : '',
      updateTimeEnd: updateTimeEnd.value ? dayjs(updateTimeEnd.value).format('YYYY-MM-DD HH:mm:ss') : '',
    } as any;
  },
  // 重置
  reset({ data }) {
    model.value = { ...data } as any;
    updateTimeStart.value = '';
    updateTimeEnd.value = '';
  },
};
// 设备列表
const gridRef = ref<VxeGridInstance<EquirementModel>>();
const gridOptions = reactive<VxeGridProps<EquirementModel>>({
  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: [
    { type: 'checkbox', width: 100, fixed: 'left', title: '', align: 'center' },
    { field: 'deviceType', title: '设备名称' },
    { field: 'orgName', title: '组织名称' },
    { field: 'institutionName', title: '机构名称' },
    { field: 'deviceCode', title: '设备ID' },
    { field: 'remark', title: '备注' },
    { field: 'updateBy', title: '修改人' },
    { field: 'updateTime', title: '修改时间' },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 120,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '编辑', status: 'primary', name: 'editEquirement' },
          { content: '删除', status: 'primary', name: 'deleteEquirement' },
        ],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'editEquirement') {
              method = editEquirement;
            } else if (name === 'deleteEquirement') {
              method = deleteEquirement;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

// 分页
const { loading, page, pageSize, total, onSuccess, replace, refresh, remove } = usePagination((page, size) => getDeviceRegisterMethod(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 deleteEquirement(model: EquirementModel, index: number) {
  const { deviceCode } = model;
  VxeUI.modal.confirm({
    title: `删除设备`,
    content: `确认要删除 ${deviceCode} 设备吗？`,
    showClose: false,
    onConfirm() {
      deleteDeviceRegisterMethod(model).then(() => {
        notification.success({
          message: `删除设备: ${deviceCode}`,
          description: '操作成功',
        });
        refresh(page.value);
      });
    },
  });
}
// 新增或编辑设备
function editEquirement(model?: EquirementModel, index?: number) {
  VxeUI.modal.open({
    title: model?.id ? `修改设备` : `新增设备`,
    height: 550,
    width: 900,
    escClosable: true,
    destroyOnClose: true,
    id: `equirement-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(EditEquirement, <any>{
          data: model,
          onSubmit(data: EquirementModel) {
            refresh(page.value);
            VxeUI.modal.close(`equirement-modal`);
          },
        });
      },
    },
  });
}

// 批量修改
function importOrganization() {
  const selectedRows = gridRef.value?.getCheckboxRecords() || [];
  if (selectedRows.length === 0) {
    notification.error({ message: '请选择要批量修改的设备' });
    return;
  }
  VxeUI.modal.open({
    title: '批量修改',
    width: 700,
    height: 700,
    escClosable: true,
    destroyOnClose: true,
    id: 'import-organization',
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(EditOrganization, {
          data: selectedRows,
          onSubmit(org: any) {
            const deviceIds = selectedRows.map((item: any) => item.id);
            updateDeviceRegisterOrganizationMethod({ deviceIds, orgId: org.orgId, institutionId: org.institutionId })
              .then(() => {
                notification.success({ message: '批量修改成功' });
                refresh(page.value);
                VxeUI.modal.close('import-organization');
              })
              .catch(() => {
                notification.error({ message: '批量修改失败' });
              });
          },
        });
      },
    },
  });
}
</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="updateTimeStart" placeholder="请选择开始时间" style="flex: 1" :show-time="{ format: 'HH:mm' }" />
            <span class="date-separator">至</span>
            <a-date-picker v-model:value="updateTimeEnd" 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>
      </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>
