<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { useRoute } from 'vue-router';

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

import { Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { statDeptExport, statDeptList } from '#/api/biz/statDept';
import { commonDownloadExcel } from '#/utils/file/download';

import { columns, querySchema } from './data';
import DeptTree from './dept-tree.vue';
import statDeptModal from './statDept-modal.vue';

const route = useRoute();

// 获取参数
const id = route.query.id;
const name = route.query.name;
console.log(id, name, 'route.query');
// 左边部门用
const selectDeptId = ref<string[]>([]);
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
  // 不需要直接删除
  fieldMappingTime: [
    [
      'tjrq',
      ['params[beginTjrq]', 'params[endTjrq]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
  handleReset: async () => {
    selectDeptId.value = [];
    // eslint-disable-next-line no-use-before-define
    const { formApi, reload } = tableApi;
    await formApi.resetForm();
    const formValues = formApi.form.values;
    formApi.setLatestSubmissionValues(formValues);
    await reload(formValues);
  },
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
  // columns: columns(),
  columns,
  border: true,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 部门树选择处理
        if (selectDeptId.value.length === 1) {
          formValues.deptId = selectDeptId.value[0];
        } else {
          Reflect.deleteProperty(formValues, 'deptId');
        }
        return await statDeptList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'biz-statDept-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// const [StatDeptModal, modalApi] = useVbenModal({
const [StatDeptModal] = useVbenModal({
  connectedComponent: statDeptModal,
});
/* 
function handleAdd() {
  modalApi.setData({});
  modalApi.open();
}

async function handleEdit(row: Required<StatDeptForm>) {
  modalApi.setData({ id: row.id });
  modalApi.open();
}

async function handleDelete(row: Required<StatDeptForm>) {
  Modal.confirm({
    title: '提示',
    content: '确认要删除当前数据项吗？',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    async onOk() {
      await statDeptRemove(row.id);
      await tableApi.query();
    },
    onCancel() {},
  });
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<StatDeptForm>) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await statDeptRemove(ids);
      await tableApi.query();
    },
  });
}
 */
function handleDownloadExcel() {
  commonDownloadExcel(
    statDeptExport,
    '单位每日数据统计数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
</script>

<template>
  <Page :auto-content-height="true">
    <div class="flex h-full gap-[8px]">
      <DeptTree
        v-model:select-dept-id="selectDeptId"
        class="mm-tree"
        @reload="() => tableApi.reload()"
        @select="() => tableApi.reload()"
      />
      <BasicTable table-title="">
        <template #toolbar-tools>
          <Space>
            <a-button
              v-access:code="['biz:statDept:export']"
              @click="handleDownloadExcel"
            >
              {{ $t('pages.common.export') }}
            </a-button>
            <!-- <a-button
              :disabled="!vxeCheckboxChecked(tableApi)"
              danger
              type="primary"
              v-access:code="['biz:statDept:remove']"
              @click="handleMultiDelete"
            >
              {{ $t('pages.common.delete') }}
            </a-button>
            <a-button
              type="primary"
              v-access:code="['biz:statDept:add']"
              @click="handleAdd"
            >
              {{ $t('pages.common.add') }}
            </a-button> -->
          </Space>
        </template>
        <!-- <template #action="{ row }">
          <Space>
            <ghost-button
              v-access:code="['biz:statDept:edit']"
              @click.stop="handleEdit(row)"
            >
              {{ $t('pages.common.edit') }}
            </ghost-button>

            <ghost-button
              danger
              v-access:code="['biz:statDept:remove']"
              @click.stop="handleDelete(row)"
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Space>
        </template> -->
      </BasicTable>
    </div>
    <StatDeptModal @reload="tableApi.query()" />
  </Page>
</template>
