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

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

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

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteCustomerComplaint,
  exportCustomerComplaint,
  getCustomerComplaintList,
} from '#/api/archive/operationsManagement/operationsManagement';
import { commonDownloadExcel } from '#/utils/file/download';

import { columns, querySchema } from './config-data';
import ExtraDrawer from './drawer.vue';

const showSearchForm = ref(true) as any;
const router = useRouter();
const [Drawer, drawerApi] = useVbenDrawer({
  connectedComponent: ExtraDrawer,
});
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',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'enterTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};
// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await getCustomerComplaintList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'operations-management-customercomplaint-index',
};
const [BasicTable, BasicTableApi] = useVbenVxeGrid({
  showSearchForm,
  formOptions,
  gridOptions,
});

const handleTaskClick = (taskId: number) => {
  router.push(`/schedule/detail/${taskId}`);
};

// 单个删除客户投诉
async function confirmEvent(row: any) {
  await deleteCustomerComplaint([row.id]);
  await BasicTableApi.reload();
}

// 批量删除客户投诉
function deleteHandle() {
  const checkRecords = BasicTableApi.grid.getCheckboxRecords();
  const ids = checkRecords.map((item: any) => item.id);
  if (ids.length <= 0) {
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteCustomerComplaint(ids);
    await BasicTableApi.reload();
  });
}

// 导出客户投诉数据
async function exportHandle() {
  await commonDownloadExcel(
    exportCustomerComplaint,
    '客户投诉数据',
    BasicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}

// 编辑客户投诉
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 新增客户投诉
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}
</script>
<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="客户投诉列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="danger"
            :disabled="
              !(BasicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
            v-access:code="['operations:customercomplaint:remove']"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['operations:customercomplaint:add']"
          >
            新增客户投诉
          </ElButton>
          <!-- <ElButton
            type="primary"
            plain
            @click="exportHandle"
            v-access:code="['operations:customercomplaint:export']"
          >
            导出
          </ElButton> -->
          <ElButton @click="() => (showSearchForm = !showSearchForm)">
            展开/折叠
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['operations:customercomplaint:edit']"
          >
            编辑
          </ElButton>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="() => handleTaskClick(row.taskId)"
            v-access:code="['operations:customercomplaint:view']"
          >
            查看
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['operations:customercomplaint:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <Drawer @reload="BasicTableApi.reload()" />
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
