<script setup lang="tsx">
import { NDivider } from 'naive-ui';
import { fetchBatchDeletePrivateTest3, fetchGetPrivateTest3List } from '@/service/api/mps/private-test3';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useDownload } from '@/hooks/business/download';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import ButtonIcon from '@/components/custom/button-icon.vue';
import PrivateTest3OperateDrawer from './modules/private-test3-operate-drawer.vue';
import PrivateTest3Search from './modules/private-test3-search.vue';
import {computed, ref, watch} from "vue";
import {useBoolean} from "~/packages/hooks";
import PrivateTest3ImportModal from './modules/private-test3-import-modal.vue';
defineOptions({
  name: 'PrivateTest3List'
});

const appStore = useAppStore();
const { download } = useDownload();
const { hasAuth } = useAuth();
const { bool: importVisible, setTrue: openImportModal } = useBoolean();

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetPrivateTest3List,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    userId: null,
    custId: null,
    custName: null,
    custAcctNo: null,
    custPhoneNo: null,
    checkFlag: null,
    checkTime: null,
    checkUser: null,
    checkType: null,
    checkMsg: null,
    params: {}
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64,
      resizable: true
    },
    {
      key: 'dataId',
      title: '主键',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'userId',
      title: '营销人员营销号',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'custId',
      title: '客户身份证号',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'custName',
      title: '客户姓名',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'custAcctNo',
      title: '客户账号/卡号',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'custPhoneNo',
      title: '客户联系电话',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'checkFlag',
      title: '核对标志（0未核对 1核对通过 9核对失败）',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'checkTime',
      title: '核对时间',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'checkUser',
      title: '核对人员（人工核对时）',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'checkType',
      title: '核对方式（0系统 1人工 2其他1 3其他2 4其他3）',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'checkMsg',
      title: '核对结果',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      fixed: 'right',
      width: 130,
      render: row => {
        const divider = () => {
          if (!hasAuth('mps:privateTest3:edit') || !hasAuth('mps:privateTest3:remove')) {
            return null;
          }
          return <NDivider vertical />;
        };

        const editBtn = () => {
          if (!hasAuth('mps:privateTest3:edit')) {
            return null;
          }
          return (
            <ButtonIcon
              text
              type="primary"
              icon="material-symbols:drive-file-rename-outline-outline"
              tooltipContent={$t('common.edit')}
              onClick={() => edit(row.dataId!)}
            />
          );
        };

        const deleteBtn = () => {
          if (!hasAuth('mps:privateTest3:remove')) {
            return null;
          }
          return (
            <ButtonIcon
              text
              type="error"
              icon="material-symbols:delete-outline"
              tooltipContent={$t('common.delete')}
              popconfirmContent={$t('common.confirmDelete')}
              onPositiveClick={() => handleDelete(row.dataId!)}
            />
          );
        };

        return (
          <div class="flex-center gap-8px">
            {editBtn()}
            {divider()}
            {deleteBtn()}
          </div>
        );
      }
    }
  ]
});

const scrollX = ref(0);
// 计算总宽度函数
const calculateTotalWidth = () => {
    let totalWidth = 0;
    const visibleColumns = columns.value;
    for (let i = 0; i < visibleColumns.length; i++) {
        const column = visibleColumns[i];
        // 获取列的实际渲染宽度
        // 注意：调整大小时会更新 column.width
        let width = column.width;
        // 如果没有显式宽度，则使用minWidth或默认值
        if (!width) {
            width = column.minWidth || 120;
        }
        // 转换为数字类型
        width = typeof width === 'string' ? parseInt(width) : width;
        totalWidth += width;
    }

    // 添加额外的50px余量防止边缘裁剪
    return totalWidth + 50;
};

// 监听列变化并计算宽度
watch(columns, (newColumns) => {
    scrollX.value = calculateTotalWidth();
}, { deep: true });


const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
  useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  const { error } = await fetchBatchDeletePrivateTest3(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

async function handleDelete(dataId: CommonType.IdType) {
  // request
  const { error } = await fetchBatchDeletePrivateTest3([dataId]);
  if (error) return;
  onDeleted();
}

function edit(dataId: CommonType.IdType) {
  handleEdit('dataId', dataId);
}

function handleImport() {
    openImportModal();
}

function handleExport() {
  download('/mps/privateTest3/export', searchParams, `测试三_${new Date().getTime()}.xlsx`);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <PrivateTest3Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard title="测试三列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-add="hasAuth('mps:privateTest3:add')"
          :show-delete="hasAuth('mps:privateTest3:remove')"
          :show-export="hasAuth('mps:privateTest3:export')"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @export="handleExport"
          @refresh="getData"
        >
            <template #after>
                <NButton v-if="hasAuth('mps:privateEbankNew:export')" size="small" ghost @click="handleImport">
                    <template #icon>
                        <icon-material-symbols:upload-rounded class="text-icon"/>
                    </template>
                    {{ $t('common.import') }}
                </NButton>
            </template>
        </TableHeaderOperation>
      </template>

      <!--scroll-x : 所有表格列宽度之和(包含操作列)+操作列宽度-->
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="scrollX"
        :loading="loading"
        remote
        :row-key="row => row.dataId"
        :pagination="mobilePagination"
        class="sm:h-full"
        @update-resize-widths="scrollX = calculateTotalWidth()"
      />

        <PrivateTest3ImportModal v-model:visible="importVisible" @submitted="getDataByPage"/>

      <PrivateTest3OperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
