<template>
  <div style="margin:10px">
    <vxe-grid ref="tableRef" v-bind="gridOptions">
      <template #toolbarButtons>
        <vxe-button status="primary" icon="vxe-icon-add" @click="handleAdd" :loading="loading.add">新增内置表单</vxe-button>
        <vxe-button status="primary" icon="vxe-icon-add" @click="handleAddOther" :loading="loading.addOther">新增外置表单</vxe-button>
        <vxe-button status="primary" icon="vxe-icon-delete" @click="handleBatchDeleteConfirm" :loading="loading.batchDelete">删除</vxe-button>
      </template>
      <template #operate="{ row }">
        <vxe-button type="text" status="primary" @click="handleEdit(row)" :loading="loading.edit === row.formId">修改</vxe-button>
        <vxe-button type="text" status="danger" @click="handleDeleteConfirm(row)" :loading="loading.delete === row.formId">删除</vxe-button>
      </template>
    </vxe-grid>
    <form-modal ref="refFormModal" @callBack="handleSuccess"></form-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from 'vue'
import { VxeGridProps, VxeGridInstance } from 'vxe-table'
import { useRouter } from 'vue-router';
import { listForm, batchDelete, delForm } from "@/components/Process/api/form"
import FormModal from './formModal.vue'
import { Modal, message } from 'ant-design-vue'; // 根据项目实际使用的UI组件调整

const router = useRouter();
const refFormModal = ref();

interface RowVO {
  id: string
  formId: string
  formTp: string
  formName: string
  formUrl: string
  remark: string
  username: string
  nickname: string
}

interface SrhParam {
  username: string
  column: string
  order: string
  pageNo: number
  pageSize: number
}

interface LoadingState {
  add: boolean
  addOther: boolean
  edit: string | null
  delete: string | null
  batchDelete: boolean
  table: boolean
}

const tableRef = ref<VxeGridInstance>(); 
const emit = defineEmits(['callBack']);

// 加载状态管理
const loading = reactive<LoadingState>({
  add: false,
  addOther: false,
  edit: null,
  delete: null,
  batchDelete: false,
  table: false
});

// 操作锁，防止重复点击
const operationLock = ref<Set<string>>(new Set());

const srhParams = ref<SrhParam>({
  username: '',
  column: '',
  order: '',
  pageNo: 1,
  pageSize: 10
});

const tpOptions = [
  { label: '内部表单', value: '1' },
  { label: '外部表单', value: '2' }
]

const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  rowConfig: {
    keyField: 'id'
  },
  columnConfig: {
    resizable: true
  },
  checkboxConfig: {
    reserve: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10
  },
  toolbarConfig: {
    refresh: false,
    zoom: true,
    custom: true,
    export: true,
    print: true,
    slots: {
      buttons: 'toolbarButtons'
    }
  },
  columns: [
    { type: 'checkbox', visible: true, width: '40', showOverflow: false },
    { title: '表单主键', field: 'formId', align: 'center', width: '200' },
    { 
      title: '表单类别', 
      field: 'formTp', 
      align: 'center', 
      width: '200',
      filters: tpOptions,
      filterMultiple: false,
      formatter ({ cellValue }) {
        const item = tpOptions.find(item => item.value === cellValue)
        return item ? item.label : ''
      }
    },
    { title: '表单名称', field: 'formName', align: 'left', minWidth: '200' },
    { title: '表单地址', field: 'formUrl', align: 'left', minWidth: '200' },
    { title: '备注', field: 'remark', align: 'left', minWidth: '200'},
    { 
      title: '操作', 
      align: 'center', 
      width: '200', 
      fixed: 'right', 
      slots: { default: 'operate' }
    }
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      query: ({ page }) => {
        return findPageList(page.currentPage, page.pageSize)
      }
    }
  },
  loading: loading.table
})

// 检查操作是否正在进行
const isOperationInProgress = (operation: string, id?: string): boolean => {
  const key = id ? `${operation}_${id}` : operation;
  return operationLock.value.has(key);
}

// 设置操作状态
const setOperationState = (operation: string, id: string | null, state: boolean) => {
  const key = id ? `${operation}_${id}` : operation;
  
  if (state) {
    operationLock.value.add(key);
    (loading as any)[operation] = id || state;
  } else {
    operationLock.value.delete(key);
    (loading as any)[operation] = id ? null : false;
  }
}

const findPageList = async (currentPage: number, pageSize: number) => {
  srhParams.value.pageNo = currentPage;
  srhParams.value.pageSize = pageSize;
  const retData = await setData();
  return {
    page: {
      total: retData.total
    },
    result: retData.records
  };
};

async function iniData() {
  await findPageList(1, 10)
}

async function setData() {
  try {
    setOperationState('table', null, true);
    return await listForm({
      pageNo: srhParams.value.pageNo,
      pageSize: srhParams.value.pageSize
    })
  } finally {
    setOperationState('table', null, false);
  }
}

const handleAdd = () => {
  if (isOperationInProgress('add')) return;
  
  setOperationState('add', null, true);
  try {
    router.push({ path: '/flowable/task/flowForm/index' })
  } finally {
    // 路由跳转后不需要重置状态，因为组件会销毁
  }
}

function handleEdit(row: RowVO) {
  if (isOperationInProgress('edit', row.formId)) return;
  
  setOperationState('edit', row.formId, true);
  try {
    if (row.formTp == '1') {
      const url = "/flowable/task/flowForm/index";
      router.push({ path: url, query: { formId: row.formId } })
    } else {
      refFormModal.value.iniData(row)
      setOperationState('edit', row.formId, false);
    }
  } catch (error) {
    setOperationState('edit', row.formId, false);
    console.error('编辑表单失败:', error);
  }
  return false
}

// 删除确认
const handleDeleteConfirm = (row: RowVO) => {
  Modal.confirm({
    title: '确认删除表单',
    content: `您确定要删除表单 "${row.formName}" 吗？此操作不可恢复！`,
    okText: '确认删除',
    cancelText: '取消',
    okType: 'danger',
    onOk: () => handleDelete(row),
    onCancel: () => {
      console.log('取消删除操作');
    }
  });
}

async function handleDelete(row: RowVO) {
  if (isOperationInProgress('delete', row.formId)) return;
  
  setOperationState('delete', row.formId, true);
  try {
    await delForm(row.formId, handleSuccess)
    // message.success('删除成功');
  } catch (error) {
    console.error('删除失败:', error);
    // message.error('删除失败');
  } finally {
    setOperationState('delete', row.formId, false);
  }
}

// 批量删除确认
const handleBatchDeleteConfirm = async () => {
  const ids = await getSelectIds();
  if (ids.length === 0) {
    // message.warning('请选择要删除的表单');
    return;
  }
  
  Modal.confirm({
    title: '确认批量删除',
    content: `您确定要删除选中的 ${ids.length} 个表单吗？此操作不可恢复！`,
    okText: '确认删除',
    cancelText: '取消',
    okType: 'danger',
    onOk: () => handleBatchDelete(ids),
    onCancel: () => {
      console.log('取消批量删除操作');
    }
  });
}

async function handleBatchDelete(ids?: string[]) {
  if (isOperationInProgress('batchDelete')) return;
  
  const selectedIds = ids || await getSelectIds();
  if (selectedIds.length === 0) {
    // message.warning('请选择要删除的表单');
    return;
  }
  
  setOperationState('batchDelete', null, true);
  try {
    await batchDelete({ ids: selectedIds.join(",") }, handleSuccess)
    // message.success(`成功删除 ${selectedIds.length} 个表单`);
  } catch (error) {
    console.error('批量删除失败:', error);
    // message.error('批量删除失败');
  } finally {
    setOperationState('batchDelete', null, false);
  }
}

async function getSelectIds() {
  let ids: string[] = [];
  const $table = tableRef.value;
  if ($table) {
    const selRecords = $table.getCheckboxRecords();
    selRecords.forEach(function (ele) {
      ids.push(ele.formId);
    })
  }
  return ids;
}

const handleSuccess = async () => {
  if (tableRef.value) {
    await tableRef.value.commitProxy('query');
  }
}

const handleAddOther = async () => {
  if (isOperationInProgress('addOther')) return;
  
  setOperationState('addOther', null, true);
  try {
    await nextTick()
    refFormModal.value.iniData({})
  } finally {
    setOperationState('addOther', null, false);
  }
}

// 组件卸载时清理所有操作状态
const cleanup = () => {
  operationLock.value.clear();
  Object.keys(loading).forEach(key => {
    if (typeof (loading as any)[key] === 'boolean') {
      (loading as any)[key] = false;
    } else {
      (loading as any)[key] = null;
    }
  });
}

defineExpose({
  iniData
});
</script>