<template>
  <div class="app-container">
    <vxe-grid
      ref="xGrid"
      v-bind="gridOptions"
      @checkbox-change="onSelectChange"
      @checkbox-all="onSelectChange"
    >
      <!-- 搜索表单插槽 -->
      <template #flowNameItem="{ data }">
        <vxe-input v-model="data.procDefName" placeholder="请输入流程名称" clearable @keyup.enter="searchEvent"></vxe-input>
      </template>
      
      <template #taskNameItem="{ data }">
        <vxe-input v-model="data.taskName" placeholder="请输入任务名称" clearable @keyup.enter="searchEvent"></vxe-input>
      </template>
      
      <template #startTimeItem="{ data }">
        <vxe-input type="date" v-model="data.startTime" placeholder="请选择开始时间" clearable></vxe-input>
      </template>
      
      <template #actionItem>
        <vxe-button status="primary" icon="vxe-icon-search" @click="searchEvent">搜索</vxe-button>
        <vxe-button icon="vxe-icon-refresh" @click="resetEvent">重置</vxe-button>
      </template>
      <template #procDefVersion_default="{ row }">
        <span class="version-tag">v{{ row.procDefVersion }}</span>
      </template>
      
      <template #startUser_default="{ row }">
        <div class="user-info">
          <span class="user-name">{{ row.startUserName }}</span>
          <span class="dept-tag">{{ row.startDeptName }}</span>
        </div>
      </template>
      
      <template #action_default="{ row }">
        <vxe-button type="text" icon="vxe-icon-edit" status="primary" @click="handleFlowRecord(row)">流转记录</vxe-button>
        <vxe-button type="text" icon="vxe-icon-edit" status="primary" @click="handleRevoke(row)">撤回</vxe-button>
      </template>
    </vxe-grid>
  </div>
  <a-drawer
      v-model:open="isShowDrawer"
      class="custom-class"
      root-class-name="root-class-name"
      :root-style="{ color: 'blue' }"
      title="流转记录"
      placement="right"
      width="70%"
      >
      <Detail v-if="isShowDrawer" ref="refDetail" />
    </a-drawer>
</template>

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

import XEUtils from 'xe-utils'
import Detail from './components/Detail.vue'
import { finishedList, delDeployment,revokeProcess } from "/@/components/Process/api/finished"


const loading = ref(false)
const isShowDrawer = ref(false)

const refDetail = ref<InstanceType<typeof Detail>>()

interface QueryParams {
  pageNum: number
  pageSize: number
  procDefName?: string
  taskName?: string
  startTime?: string
}

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  procDefName: undefined,
  taskName: undefined,
  startTime: undefined,
})

interface TodoItem {
  taskId: string
  procDefName: string
  taskName: string
  procDefVersion: number
  startUserName: string
  startDeptName: string
  createTime: string
  procInsId: string
  executionId: string
  deployId: string
}

// 表单默认数据
const defaultData = reactive({
  procDefName: '',
  taskName: '',
  startTime: ''
})

// 选中数据
const selectedRowKeys = ref<string[]>([])
const selectRecords = ref<TodoItem[]>([])
const multiple = ref(true)

// Grid 实例
const xGrid = ref<VxeGridInstance>()

const gridOptions = reactive<VxeGridProps<any>>({
  loading: loading.value,
  showOverflow: true,
  border: true,
  height: "100%",
  rowConfig: {
    keyField: 'taskId',
    isHover: true
  },
  columnConfig: {
    resizable: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100],
    layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']
  },
  checkboxConfig: {
    highlight: true,
    range: true
  },
  layouts: ['Top', 'Form', 'Toolbar','Table', 'Bottom', 'Pager'],
  formConfig: {
    data: XEUtils.clone(defaultData, true),
    items: [
      { field: 'procDefName', title: '流程名称', span: 6, itemRender: {}, slots: { default: 'flowNameItem' } },
      { field: 'taskName', title: '任务名称', span: 6, itemRender: {}, slots: { default: 'taskNameItem' } },
      { field: 'startTime', title: '开始时间', span: 6, itemRender: {}, slots: { default: 'startTimeItem' } },
      { span: 6, align: 'center', itemRender: {}, slots: { default: 'actionItem' } }
    ]
  },
  proxyConfig: {
    response: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      query: ({ page }) => {
        return findPageList(page.currentPage, page.pageSize)
      }
    }
  },
  columns: [
    { type: 'checkbox', width: 60, fixed: 'left' },
    { type: 'seq', width: 70, fixed: 'left' },
    { field: 'taskId', title: '任务编号', minWidth: 120, showOverflow: true },
    { field: 'procDefName', title: '流程名称', minWidth: 160, showOverflow: true },
    { field: 'taskName', title: '任务节点', minWidth: 140, showOverflow: true },
    { field: 'procDefVersion', title: '流程版本', width: 100, align: 'center', slots: { default: 'procDefVersion_default' } },
    { field: 'startUser', title: '流程发起人', minWidth: 180, align: 'center', slots: { default: 'startUser_default' } },
    { field: 'createTime', title: '接收时间', width: 140, align: 'center' },
    { field: 'finishTime', title: '审批时间', width: 140, align: 'center' },
    { field: 'duration', title: '耗时', width: 100, align: 'center' },

    { 
      title: '操作', 
      width: 180, 
      fixed: 'right', 
      align: 'center',
      slots: { default: 'action_default' }
    }
  ]
})

const findPageList = async (currentPage: number, pageSize: number) => {
  queryParams.pageNum = currentPage
  queryParams.pageSize = pageSize
  if (gridOptions.formConfig?.data) {
    queryParams.procDefName = gridOptions.formConfig.data.procDefName
    queryParams.taskName = gridOptions.formConfig.data.taskName
    queryParams.startTime = gridOptions.formConfig.data.startTime
  }
  
  try {
    loading.value = true
    const retData = await finishedList(queryParams)
    return {
      page: {
        total: retData.total
      },
      result: retData.records
    }
  } catch (error) {
    console.error('查询数据失败:', error)
    message.error('查询数据失败')
    return {
      page: { total: 0 },
      result: []
    }
  } finally {
    loading.value = false
  }
}

const searchEvent = async () => {
  queryParams.pageNum = 1
  if (xGrid.value) {
    await xGrid.value.commitProxy('query')
  }
}

const resetEvent = () => {
  if (gridOptions.formConfig) {
    gridOptions.formConfig.data = XEUtils.clone(defaultData, true)
  }
  searchEvent()
}

// 多选框选中数据
const onSelectChange = () => {
  if (xGrid.value) {
    const checkedRecords = xGrid.value.getCheckboxRecords()
    selectRecords.value = checkedRecords
    selectedRowKeys.value = checkedRecords.map(item => item.taskId)
    multiple.value = !selectedRowKeys.value.length
  }
}




/** 撤回任务 */
const handleRevoke = (row) => {
  const params = {
    instanceId: row.procInsId
  }
  revokeProcess(params).then((res: any) => {
    message.success(res.msg)
    getList()
  })
}


/** 流程流转记录 */
const handleFlowRecord = async(row) => {
  isShowDrawer.value = true
  await nextTick()
  if (refDetail.value) {
    refDetail.value.iniData(row)
  } 
}


</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>