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

import { computed, h, ref } from 'vue';

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

import { Button, Select, message as Message, Modal, Tag } from 'ant-design-vue';

import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  postUpgradeRecordBatchUpdateStatusAsync,
  postUpgradeRecordDeleteAsync,
  postUpgradeRecordPage,
} from '#/api-client';
import { TableAction } from '#/components/table-action';
import { $t } from '#/locales';

import { querySchema, tableSchema } from './schema';

defineOptions({
  name: 'DeviceUpgradeRecord',
});

const formOptions: VbenFormProps = {
  schema: querySchema.value,
  submitOnChange: false,
  handleValuesChange: async (values, changedFields) => {
    // 当升级标识符号失焦时，如果值为空字符串或null，保持为undefined而不是清空
    if (changedFields.includes('upgradeIdentifier')) {
      if (values.upgradeIdentifier === '' || values.upgradeIdentifier === null) {
        // 保持为 undefined，这样不会影响查询
        if (gridApi?.formApi) {
          await gridApi.formApi.setFieldValue('upgradeIdentifier', undefined);
        }
      }
    }
  },
};

// 升级状态选项（与后端 DeviceUpgradeStatusTypeEnum 保持一致）
const upgradeStatusOptions = [
  { label: '未升级', value: 1 },
  { label: '升级中', value: 2 },
  { label: '固件下载中', value: 3 },
  { label: '升级成功', value: 4 },
  { label: '升级失败', value: 5 },
];

const gridOptions: VxeGridProps<any> = {
  checkboxConfig: {
    highlight: true,
  },
  columns: tableSchema.value,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  toolbarConfig: {
    custom: true,
  },
  customConfig: {
    storage: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const currentFormValues = gridApi?.formApi
          ? await gridApi.formApi.getValues()
          : formValues || {};

        const finalFormValues = { ...formValues, ...currentFormValues };

        // 将 upgradeIdentifier 转换为数字类型（如果存在）
        if (
          finalFormValues.upgradeIdentifier !== undefined &&
          finalFormValues.upgradeIdentifier !== null &&
          finalFormValues.upgradeIdentifier !== ''
        ) {
          finalFormValues.upgradeIdentifier = Number(
            finalFormValues.upgradeIdentifier,
          );
        } else {
          // 如果为空字符串，设置为 undefined
          finalFormValues.upgradeIdentifier = undefined;
        }

        const { data } = await postUpgradeRecordPage({
          body: {
            pageIndex: page.currentPage,
            pageSize: page.pageSize,
            ...finalFormValues,
          },
        });
        return data;
      },
    },
  },
};

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

// 获取表格当前选中的记录
const getSelectedRecords = () => {
  if (!gridApi?.grid) return [];
  const gridInstance = gridApi.grid as any;
  if (typeof gridInstance.getCheckboxRecords === 'function') {
    return gridInstance.getCheckboxRecords();
  }
  if (Array.isArray(gridInstance.checkboxRecords)) {
    return gridInstance.checkboxRecords;
  }
  return [];
};

// 批量更新状态
const handleBatchUpdateStatus = () => {
  const records = getSelectedRecords();
  if (!records || records.length === 0) {
    Message.warning('请先勾选要更新状态的升级记录');
    return;
  }

  const ids = records
    .map((r: any) => r.id)
    .filter((id: string | undefined) => !!id);

  if (!ids.length) {
    Message.error('选中的升级记录缺少主键 Id，无法批量更新');
    return;
  }

  const selectedStatus = ref<number | null>(null);

  Modal.confirm({
    title: '批量更新升级状态',
    content: h('div', { style: 'margin-top: 8px;' }, [
      h(
        'div',
        {
          style: 'margin-bottom: 8px;',
        },
        '请选择要更新为的升级状态：',
      ),
      h(Select, {
        style: 'width: 100%',
        placeholder: '请选择升级状态',
        options: upgradeStatusOptions,
        onChange: (value: number) => {
          selectedStatus.value = value;
        },
      }),
    ]),
    okText: $t('common.confirm'),
    cancelText: $t('common.cancel'),
    onOk: async () => {
      if (!selectedStatus.value) {
        Message.warning('请选择升级状态');
        // 阻止弹窗关闭
        return Promise.reject();
      }

      try {
        // 参数通过 JSON Body 传递给后端
        await postUpgradeRecordBatchUpdateStatusAsync({
          body: {
            ids,
            upgradeStatus: selectedStatus.value,
          },
        });
        Message.success('批量更新升级状态成功');
        gridApi.reload();
      } catch (error) {
        console.error('批量更新升级状态失败:', error);
        Message.error('批量更新升级状态失败');
      }
    },
  });
};

// 工具栏按钮
const toolbarActions = computed(() => [
  {
    label: '批量状态更新',
    type: 'default',
    onClick: handleBatchUpdateStatus,
  },
]);

// 删除记录
function onDel(row: any) {
  Modal.confirm({
    title: `${$t('common.confirmDelete')}升级记录 ?`,
    content: `设备：${
      row.deviceName || row.deviceAddress || '-'
    }，升级日期：${
      row.upgradeDate
        ? dayjs(row.upgradeDate).format('YYYY-MM-DD HH:mm:ss')
        : '-'
    }`,
    onOk: async () => {
      try {
        const result = await postUpgradeRecordDeleteAsync({
          body: { id: row.id },
        });
        if (result.data) {
          gridApi.reload();
          Message.success($t('common.deleteSuccess'));
        } else {
          Message.error($t('common.deleteFail'));
        }
      } catch (error) {
        console.error('删除升级记录失败:', error);
        Message.error($t('common.deleteFail'));
      }
    },
  });
}

// 获取升级状态颜色
const getUpgradeStatusColor = (status: string) => {
  const statusMap: Record<string, string> = {
    进行中: 'processing',
    成功: 'success',
    失败: 'error',
    已取消: 'default',
  };
  return statusMap[status] || 'default';
};

// 获取升级结果颜色：upgradeResult 等于 1 显示绿色，为空保持默认，其他显示红色
const getUpgradeResultColor = (
  upgradeResult: number | string | undefined | null,
) => {
  if (upgradeResult == null || upgradeResult === '') return 'default';
  return upgradeResult === 1 ? 'success' : 'error';
};
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <TableAction :actions="toolbarActions" />
      </template>

      <template #upgradeStatus="{ row }">
        <component
          :is="
            h(
              Tag,
              { color: getUpgradeStatusColor(row.upgradeStatusName || '') },
              () => row.upgradeStatusName || '-',
            )
          "
        />
      </template>

      <template #upgradeResult="{ row }">
        <component
          :is="
            h(
              Tag,
              { color: getUpgradeResultColor(row.upgradeResult) },
              () => row.upgradeResultName || '-',
            )
          "
        />
      </template>

      <template #action="{ row }">
        <div style="display: flex; gap: 8px; align-items: center">
          <Button
            size="small"
            type="link"
            style="color: #ff4d4f"
            @click="onDel.bind(null, row)()"
          >
            {{ $t('common.delete') }}
          </Button>
        </div>
      </template>
    </Grid>
  </Page>
</template>

