<template>
  <div class="app-container">
    <vxe-grid ref="tableRef" v-bind="gridOptions">
      <template #toolbarButtons>
        <vxe-button status="primary" icon="vxe-icon-add" @click="handleAdd">发起流程</vxe-button>
      </template>
      
      <template #procDefVersion_default="{ row }">
        <span class="version-tag">v{{ row.procDefVersion }}</span>
      </template>

      <template #assigneeUser_default="{ row }">
        <label v-if="row.assigneeName">
          {{ row.assigneeName }} 
          <a-tag v-if="row.assigneeDeptName" color="default" size="small">{{ row.assigneeDeptName }}</a-tag>
        </label>
        <label v-else-if="row.candidate">{{ row.candidate }}</label>
        <label v-else>-</label>
      </template>

      <template #operate="{ row }">
        <vxe-button type="text" status="primary" @click="handleDetail(row)">详情</vxe-button>
        <vxe-button v-if="!row.finishTime" type="text" status="warning" @click="handleStop(row)">取消申请</vxe-button>
        <vxe-button type="text" status="danger" @click="handleDelete(row)">删除</vxe-button>
      </template>
    </vxe-grid>
  </div>
  <a-drawer
      v-model:open="isShowDrawer"
      title="发起流程"
      placement="right"
      width="70%"
      @close="handleDrawerClose"
    >
    <template #extra>
      <vxe-button type="text" status="primary" @click="handleDrawerClose()">关闭</vxe-button>
    </template>
    <SendIndex @success="handleFlowSuccess" />
    </a-drawer>
    <a-drawer
      v-model:open="isShowDetailDrawer"
      title="流程详情"
      placement="right"
      width="90%"
      @close="handleDetailDrawerClose"
    >
      <Detail ref="refDetail"/>
    </a-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted,nextTick } from 'vue'
import { VxeGridProps, VxeGridInstance } from 'vxe-table'
import { Modal, message, Tag } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'

import { myProcessList, stopProcess } from '/@/components/Process/api/process'
import { delDeployment } from '/@/components/Process/api/finished'
import SendIndex from './components/sendIndex.vue'
import Detail from './components/Detail.vue'

interface ProcessItem {
  id: string
  procInsId: string
  procDefName: string
  procDefVersion: number
  formName: string
  finishTime: string | null
  deploymentTime: string
  assigneeName: string
  assigneeDeptName: string
  candidate: string
  taskId: string
  deployId: string
  deploymentId: string
}

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

interface PageResult {
  total: number
  records: ProcessItem[]
}

const tableRef = ref<VxeGridInstance>()
const isShowDrawer = ref(false)
const isShowDetailDrawer = ref(false)

const refDetail = ref()
const loading = ref(false)

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

const gridOptions = reactive<VxeGridProps>({
  border: true,
 
  rowConfig: {
    keyField: 'id',
    isHover: true
  },
  columnConfig: {
    resizable: true
  },
  checkboxConfig: {
    reserve: true,
    checkField: 'checked',
    highlight: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    layouts: ['PrevPage', 'Number', 'NextPage', 'FullJump', 'Sizes', 'Total']
  },
  toolbarConfig: {
    refresh: {
      query: () => handleRefresh()
    },
    zoom: true,
    custom: true,
    export: true,
    print: true,
    slots: {
      buttons: 'toolbarButtons'
    }
  },
  columns: [
    { type: 'checkbox', width: 40, showOverflow: false },
    { 
      title: '流程编号', 
      field: 'procInsId', 
      align: 'center', 
      width: 280,
      showOverflow: true 
    },
    { 
      title: '流程名称', 
      field: 'procDefName', 
      align: 'center', 
      showOverflow: true 
    },
    { 
      field: 'procDefVersion', 
      title: '流程版本', 
      width: 100, 
      align: 'center', 
      slots: { default: 'procDefVersion_default' } 
    },
    { 
      title: '业务表单', 
      field: 'formName', 
      align: 'center', 
      width: 120,
      visible: false
    },
    { 
      title: '流程状态', 
      field: 'finishTime',  
      align: 'center', 
      width: 100,
      formatter: ({ cellValue }) => {
        return !cellValue ? "进行中" : "已结束"
      }
    },
    { 
      title: '耗时', 
      field: 'duration', 
      align: 'center', 
      width: 100,
      formatter: ({ cellValue }) => {
        return cellValue || '-'
      }
    },
    { 
      title: '当前节点', 
      field: 'currentTaskName', 
      align: 'center', 
      width: 120,
      formatter: ({ cellValue }) => {
        return cellValue || '-'
      }
    },
    { 
      title: '办理人', 
      field: 'assigneeName', 
      align: 'center', 
      width: 150,
      slots: { default: 'assigneeUser_default' } 
    },
    { 
      title: '部署时间',
      field: 'deploymentTime', 
      align: 'center', 
      width: 180,
      formatter: ({ cellValue }) => {
        if (!cellValue) return '-'
        return new Date(cellValue).toLocaleString()
      }
    },
    { 
      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)
      }
    }
  }
})

// 查询页面数据
const findPageList = async (currentPage: number, pageSize: number): Promise<{ page: { total: number }, result: ProcessItem[] }> => {
  srhParams.value.pageNo = currentPage
  srhParams.value.pageSize = pageSize
  const retData = await setData()
  return {
    page: {
      total: retData.total
    },
    result: retData.records
  }
}

// 获取数据
const setData = async (): Promise<PageResult> => {
  try {
    loading.value = true
    const response = await myProcessList({
      pageNum: srhParams.value.pageNo,
      pageSize: srhParams.value.pageSize
    })
    return response || { total: 0, records: [] }
  } catch (error) {
    console.error('获取流程列表失败:', error)
    message.error('获取流程列表失败')
    return { total: 0, records: [] }
  } finally {
    loading.value = false
  }
}

// 初始化数据
const iniData = async () => {
  await findPageList(1, 10)
}

// 取消申请
const handleStop = async (row: ProcessItem) => {
  try {
    Modal.confirm({
      title: '提示',
      icon: createVNode(ExclamationCircleOutlined),
      content: '确定要取消该流程申请吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        loading.value = true
        const params = { instanceId: row.procInsId }
        await stopProcess(params)
        message.success('取消申请成功')
        await handleSuccess()
      },
      onCancel: () => {
        // 用户取消操作
      }
    })
  } catch (error) {
    message.error('取消申请失败')
  } finally {
    loading.value = false
  }
}

// 查看流程记录
const handleDetail = async (row: ProcessItem) => {
  isShowDetailDrawer.value = true
  await nextTick(()=>{
    if (refDetail.value) {
      refDetail.value.iniData(row)
    } else {
      isShowDetailDrawer.value = false
    }
  })
}

// 删除流程
const handleDelete = async (row: ProcessItem) => {
  try {
    Modal.confirm({
      title: '提示',
      icon: createVNode(ExclamationCircleOutlined),
      content: '确定要删除该流程吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        await delDeployment(row.procInsId)
        message.success('删除成功')
        await handleSuccess()
      },
      onCancel: () => {
        // 用户取消操作
      }
    })
  } catch (error) {
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  const ids = await getSelectIds()
  if (ids.length === 0) {
    message.warning('请选择要删除的流程')
    return
  }
  
  try {
    Modal.confirm({
      title: '提示',
      icon: createVNode(ExclamationCircleOutlined),
      content: `确定要删除选中的 ${ids.length} 个流程吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        // await batchDelete({ ids: ids.join(",") }, handleSuccess)
        message.success('批量删除成功')
        await handleSuccess()
      },
      onCancel: () => {
        // 用户取消操作
      }
    })
  } catch (error) {
    message.error('批量删除失败')
  }
}

// 新增流程
const handleAdd = () => {
  isShowDrawer.value = true
}

// 获取选中的ID
const getSelectIds = async (): Promise<string[]> => {
  const ids: string[] = []
  const $table = tableRef.value
  if ($table) {
    const selRecords = $table.getCheckboxRecords()
    selRecords.forEach((ele: ProcessItem) => {
      if (ele.deploymentId) {
        ids.push(ele.deploymentId)
      }
    })
  }
  return ids
}

// 操作成功回调
const handleSuccess = async () => {
  if (tableRef.value) {
    await tableRef.value.commitProxy('query')
  }
}

// 刷新表格
const handleRefresh = async () => {
  await handleSuccess()
}


const handleDrawerClose = () => {
  isShowDrawer.value = false
  handleSuccess()
}

const handleDetailDrawerClose = () => {
  isShowDetailDrawer.value = false
}

// 流程发起成功回调
const handleFlowSuccess = () => {
  isShowDrawer.value = false
  handleSuccess()
}


</script>

<style scoped>
.app-container {
  padding: 16px;
  width: 100%;
  height: 100%;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  flex-wrap: nowrap;
}

.user-name {
  font-weight: 500;
  white-space: nowrap;
}

.dept-tag {
  background: #f0f0f0;
  color: #666;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
}

.version-tag {
  background: #1890ff;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* Vxe Grid 样式调整 */
:deep(.vxe-form--wrapper) {
  background: #fafafa;
  padding: 16px;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  margin-bottom: 16px;
}

:deep(.vxe-form--item-title) {
  font-weight: 500;
  color: #333;
}

:deep(.vxe-grid--wrapper) {
  font-family: inherit;
}

:deep(.vxe-grid--header) {
  background-color: #fafafa;
}

:deep(.vxe-grid--body) {
  background-color: #fff;
}

:deep(.vxe-cell) {
  padding: 8px 4px;
}

:deep(.vxe-toolbar) {
  background: transparent;
  padding: 8px 0;
  margin-bottom: 8px;
}

:deep(.vxe-table--render-wrapper) {
  border-radius: 4px;
}
</style>