<script setup lang="tsx">
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteMobileBankSignupCompany, fetchGetMobileBankSignupCompanyList } from '@/service/api/original/mobile-bank-signup-company';
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 MobileBankSignupCompanyOperateDrawer from './modules/mobile-bank-signup-company-operate-drawer.vue';
import MobileBankSignupCompanySearch from './modules/mobile-bank-signup-company-search.vue';
import {computed, ref, watch} from "vue";
import {useBoolean} from "~/packages/hooks";
import MobileBankSignupCompanyImportModal from './modules/mobile-bank-signup-company-import-modal.vue';
defineOptions({
  name: 'MobileBankSignupCompanyList'
});

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: fetchGetMobileBankSignupCompanyList,
  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
    branchName: null,
    branchCode: null,
    customerName: null,
    idType: null,
    idNumber: null,
    mainAccount: null,
    signupDate: null,
    authMethod: null,
    serialNumber: null,
    teller: null,
    importTime: null,
    params: {}
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64,
      resizable: true
    },
    // {
    //   key: 'id',
    //   title: '自增主键',
    //   align: 'center',
    //   minWidth: 120,
    //   ellipsis: true,
    //   resizable: true
    // },
    {
      key: 'branchName',
      title: '机构名称',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'branchCode',
      title: '机构号',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'customerName',
      title: '客户名称',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'idType',
      title: '证件类型',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'idNumber',
      title: '证件号码',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'mainAccount',
      title: '签约主账户',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'signupDate',
      title: '签约日期',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'authMethod',
      title: '认证方式',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'serialNumber',
      title: '流水号',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'teller',
      title: '柜员',
      align: 'center',
      minWidth: 120,
      ellipsis: true,
      resizable: true
    },
    {
      key: 'importTime',
      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('original:mobileBankSignupCompany:edit') || !hasAuth('original:mobileBankSignupCompany:remove')) {
    //         return null;
    //       }
    //       return <NDivider vertical />;
    //     };
    //
    //     const editBtn = () => {
    //       if (!hasAuth('original:mobileBankSignupCompany:edit')) {
    //         return null;
    //       }
    //       return (
    //         <ButtonIcon
    //           text
    //           type="primary"
    //           local-icon="drive-file-rename-outline-outline"
    //           tooltipContent={$t('common.edit')}
    //           onClick={() => edit(row.id!)}
    //         />
    //       );
    //     };
    //
    //     const deleteBtn = () => {
    //       if (!hasAuth('original:mobileBankSignupCompany:remove')) {
    //         return null;
    //       }
    //       return (
    //         <ButtonIcon
    //           text
    //           type="error"
    //           local-icon="delete-outline"
    //           tooltipContent={$t('common.delete')}
    //           popconfirmContent={$t('common.confirmDelete')}
    //           onPositiveClick={() => handleDelete(row.id!)}
    //         />
    //       );
    //     };
    //
    //     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 fetchBatchDeleteMobileBankSignupCompany(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

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

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

function handleImport() {
    openImportModal();
}

function handleExport() {
  download('/original/mobileBankSignupCompany/export', searchParams, `企业网银签约明细_${new Date().getTime()}.xlsx`);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <MobileBankSignupCompanySearch 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="false"
          :show-delete="false"
          :show-export="false"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @export="handleExport"
          @refresh="getData"
        >
            <template #after>
                <NButton v-if="hasAuth('original:mobileBankSignupCompany:import')" size="small" ghost @click="handleImport">
                    <template #icon>
                        <SvgIcon local-icon="upload-rounded"/>
                    </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.id"
        :pagination="mobilePagination"
        class="sm:h-full"
        @update-resize-widths="scrollX = calculateTotalWidth()"
      />

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

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

<style scoped></style>
