<template>
  <div style="margin:10px;height: 100%;">
    <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-delete" @click="handleBatchDeleteConfirm" :loading="loading.batchDelete">删除</vxe-button>
      </template>
      <template #operate="{ row }">
        <vxe-button type="text" status="primary" @click="handleDesign(row)" :loading="loading.design === row.id">设计流程</vxe-button>
        <vxe-button type="text" status="danger" @click="handleConfigForm(row)" :loading="loading.config === row.id">配置</vxe-button>
        <vxe-button 
          type="text" 
          status="primary" 
          @click="handleUpdateStateConfirm(row,2)" 
          v-if="row.suspensionState==1" 
          :loading="loading.updateState === row.id"
        >挂起</vxe-button>
        <vxe-button 
          type="text" 
          status="primary" 
          @click="handleUpdateStateConfirm(row,1)" 
          v-else-if="row.suspensionState==2" 
          :loading="loading.updateState === row.id"
        >发布</vxe-button>
        <vxe-button 
          type="text" 
          status="primary" 
          @click="handleUpdateStateConfirm(row,1)" 
          v-else 
          :loading="loading.updateState === row.id"
        >发布</vxe-button>
        <vxe-button type="text" status="danger" @click="handleDeleteConfirm(row)" :loading="loading.delete === row.id">删除</vxe-button>
      </template>
    </vxe-grid>
  </div>
  <flow-link-form ref="refFlowLinkForm" @callBack="handleSuccess"></flow-link-form>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from 'vue'
import { VxeGridProps } from 'vxe-table'
import { listDefinition, delDeployment, batchDelete, updateState } from '/@/components/Process/api/definition';
import { useRouter } from 'vue-router';
import { VxeGridInstance } from 'vxe-table';
import { Modal, message } from 'ant-design-vue'; // 或者使用你项目中的消息组件

import FlowLinkForm from './FlowLinkForm.vue';

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

interface RowVO {
  id: string
  username: string
  nickname: string
  deploymentId: string
  suspensionState: number
  name: string
  version: string
  isLastVersion: boolean
  deploymentTime: string
  formName: string
}

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

interface LoadingState {
  add: boolean
  batchDelete: boolean
  design: string | null
  config: string | null
  updateState: string | null
  delete: string | null
  table: boolean
}

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

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

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

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

const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  height: "100%",
  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: 'name', align: 'left', minWidth: '15%' },
    { title: '流程编号', field: 'deploymentId', align: 'left', minWidth: '18%' },
    { title: '业务表单', field: 'formName', align: 'center', width: '10%', visible: false },
    { title: '流程版本', field: 'version', align: 'center', width: '10%' },
    { title: '最新版本', field: 'isLastVersion', align: 'center', width: '10%' },
    {
      title: '状态', field: 'suspensionState', align: 'center', width: '10%',
      formatter: ({ cellValue }) => {
        const statusMap = {
          '1': '已发布',
          '2': '未发布',
        }
        return statusMap[cellValue] || cellValue
      }
    },
    {
      title: '部署时间', field: 'deploymentTime', align: 'center', width: '10%',
      formatter: ({ cellValue }) => {
        if (!cellValue) return '-'
        return new Date(cellValue).toLocaleString()
      }
    },
    {
      title: '操作',
      align: 'center',
      width: '16%',
      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 listDefinition({
      pageNum: srhParams.value.pageNo,
      pageSize: srhParams.value.pageSize
    })
  } finally {
    setOperationState('table', null, false);
  }
}

function handleConfigForm(row: RowVO) {
  if (isOperationInProgress('config', row.id)) return;
  
  setOperationState('config', row.id, true);
  try {
    refFlowLinkForm.value.iniData(row);
  } finally {
    setOperationState('config', row.id, false);
  }
}

function handleDesign(row: RowVO) {
  if (isOperationInProgress('design', row.id)) return;
  
  setOperationState('design', row.id, true);
  try {
    const url = "/flowable/definition/AddFlow";
    router.push({ path: url, query: { deployId: row.deploymentId } })
  } finally {
    // 路由跳转后不需要重置状态，因为组件会销毁
  }
  return false
}

// 状态更新确认
const handleUpdateStateConfirm = (row: RowVO, status: number) => {
  const actionText = status === 1 ? '发布' : '挂起';
  const actionDesc = status === 1 ? '发布后流程将可用' : '挂起后流程将暂停使用';
  
  Modal.confirm({
    title: `确认${actionText}流程`,
    content: `您确定要${actionText}流程 "${row.name}" 吗？${actionDesc}`,
    okText: `确认${actionText}`,
    cancelText: '取消',
    onOk: () => handleUpdateState(row, status),
    onCancel: () => {
      console.log('取消状态更新操作');
    }
  });
}

async function handleUpdateState(row: RowVO, status: number) {
  if (isOperationInProgress('updateState', row.id)) return;
  
  setOperationState('updateState', row.id, true);
  try {
    const params = { state: status, deployId: row.deploymentId }
    await updateState(params, handleSuccess)
    // 可以在这里添加成功提示
    // message.success(`流程${status === 1 ? '发布' : '挂起'}成功`);
  } catch (error) {
    console.error('更新状态失败:', error);
    // 可以在这里添加错误提示
    // message.error(`流程${status === 1 ? '发布' : '挂起'}失败`);
  } finally {
    setOperationState('updateState', row.id, false);
  }
}

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

async function handleDelete(row: RowVO) {
  if (isOperationInProgress('delete', row.id)) return;
  
  setOperationState('delete', row.id, true);
  try {
    await delDeployment(row.deploymentId, handleSuccess)
    // 可以在这里添加成功提示
    // message.success('删除成功');
  } catch (error) {
    console.error('删除失败:', error);
    // 可以在这里添加错误提示
    // message.error('删除失败');
  } finally {
    setOperationState('delete', row.id, 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);
  }
}

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

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

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

// 组件卸载时清理所有操作状态
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>