<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="handleProcess(row)"
        >处理</vxe-button>
      </template>
    </vxe-grid>
    <div v-if="isShowDrawer">
      <a-drawer
        destroyOnClose
        v-model:open="isShowDrawer"
        class="custom-class"
        root-class-name="root-class-name"
        :root-style="{ color: 'blue' }"
        title="待办任务"
        placement="right"
        width="90%"
        style="margin: 0px;padding: 0px;"
        >
        <template #extra>
          <div style="float: right">
            <a-tag style="margin-left: 10px">发起人:{{ startUser }}</a-tag>
            <a-tag>任务节点:{{ taskName }}</a-tag>
          </div>
        </template>
        <TodoIndex v-if="isShowDrawer" ref="refTodoIndex" @callback="handleSuccess"/>
      </a-drawer>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted,nextTick } from 'vue'
import { message } from 'ant-design-vue'
import type { VxeGridProps, VxeGridInstance } from 'vxe-table'
import { todoList, delDeployment } from '/@/components/Process/api/todo'
import XEUtils from 'xe-utils'
import TodoIndex from './components/TodoIndex.vue'
const loading = ref(false)
const isShowDrawer = ref(false)
const refTodoIndex = ref()
const startUser = ref()
const taskName = ref()

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)

const xGrid = ref<VxeGridInstance>()

const gridOptions = reactive<VxeGridProps<any>>({
  loading: loading.value,
  showOverflow: true,
  border: true,
 
  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: 'taskType', 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: 180, align: 'center' },
    { 
      title: '操作', 
      width: 120, 
      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 todoList(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 handleProcess = async (row) => {
  isShowDrawer.value = true
  startUser.value = row.startUserName
  taskName.value = row.taskName
  await nextTick(()=>{
    if(refTodoIndex.value) {
      refTodoIndex.value.iniData(row)
    } else {
      isShowDrawer.value = false
    }

  })

}

const handleSuccess = async () => {
  isShowDrawer.value = false
  await searchEvent()
}

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