<template>
  <el-dialog v-model="visible" title="请选择关联审批单" width="800px" append-to-body>
    <el-input v-model="searchQuery" placeholder="搜索流程分类、申请人" clearable />
    <el-tabs v-model="activeTab" class="mt-3" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="dict in tabsData"
        :key="dict.value"
        :label="dict.label"
        :name="dict.value"
      />
      <!-- <el-tab-pane label="已办" name="done" />
      <el-tab-pane label="抄送我" name="cc" />
      <el-tab-pane label="已发起" name="initiated" /> -->
    </el-tabs>

    <!-- <div class="filter-row">
      <el-select placeholder="全部审批" class="filter-select">
      </el-select>
      <el-select placeholder="全部状态" class="filter-select">
      </el-select>
    </div> -->

    <el-scrollbar height="400px">
      <div class="approval-list">
        <div v-for="(item) in filteredApprovals" :key="item.id" class="approval-item">
<!--          <el-checkbox v-model="item.selected" />-->
          <el-checkbox :checked="isInSelectionData(item)" @change="(checked) => { handleSelectionDataChange(checked, item) }"/>
          <div class="approval-content">
            <div class="approval-header">
              <span class="approval-title">{{ item.name }}</span>
              <!-- <el-tag :type="item.statusTagType">{{ item.status }}</el-tag> -->
              <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="item.status" />
            </div>
            <div class="approval-details">
              <p>流程分类：{{ item.categoryName }}</p>
              <p>流程名称：{{ item.name }}</p>
              <!-- <p>费用汇总：{{ item.total }}</p> -->
            </div>
            <div class="approval-footer">
              <div class="left_box"
                ><el-avatar :src="item.avatar" size="small" />
                <span class="approval-user">{{ item.startUser.nickname }}</span></div
              >
              <span class="approval-time">发起时间：{{ formatTime(item.startTime, 'yyyy-MM-dd HH:mm:ss') }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { formatTime } from '@/utils'
import * as FormApi from '@/api/bpm/form'

const visible = ref(false)
const searchQuery = ref('')
const activeTab = ref('initiated')
console.log('DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS', DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'update:visible', 'confirm'])
const tabsData = ref([
  // {label:'待审批',value:-1},
  { label: '审批中', value: 1 },
  { label: '审批通过', value: 2 }
  // {label:'审批不通过',value:3},
  // {label:'已取消',value:4},
])
// 模拟审批单数据
const approvals = ref([
  {
    title: '费用报销',
    status: '已通过',
    statusTagType: 'success',
    categoryName: '差旅费',
    reason: '去北京出差',
    total: '1000.00',
    user: '姬军',
    time: '09-08 13:34',
    avatar: '', // 可设置头像URL
    selected: false
  }
  // 更多数据...
])
/** 打开弹窗 */
const open = async () => {
  // activityId.value = id
  // resetForm()

  // // 加载部门、用户列表
  const linkData = await FormApi.getLinkAudit({ pageNo: 1, pageSize: 100, status: 1 })
  console.log('linkData', linkData)
  linkData.list.forEach((item) => {
    item.nickname = item.startUser && item.startUser.nickname
    item.selected = false
  })
  approvals.value = linkData.list
  // deptList.value = deptData // 保存扁平结构的部门数据
  // deptTree.value = handleTree(deptData) // 转换成树形结构
  // userList.value = await UserApi.getSimpleUserList()

  // // 初始状态下，过滤列表等于所有用户列表
  // filteredUserList.value = [...userList.value]
  // selectedUserIdList.value = selectedList?.map((item: any) => item.id) || []
  // dialogVisible.value = true
  // console.log(111111)
  visible.value = true
}

// Tab切换处理
const handleTabClick = async (tab, el) => {
  console.log(tab, el, tab.props.label, tab.props.name)
  const linkData = await FormApi.getLinkAudit({ pageNo: 1, pageSize: 100, status: tab.props.name })
  console.log('linkData', linkData)
  linkData.list.forEach((item) => {
    item.nickname = item.startUser && item.startUser.nickname
    item.selected = false
  })
  approvals.value = linkData.list
  // activeTab.value = tab.name
}

// 初始化时设置已选状态
// approvals.value.forEach((item) => {
//   item.selected = props.modelValue.some((selectedItem) => selectedItem.id === item.id)
// })
const filteredApprovals = computed(() => {
  // 这里可以添加搜索和筛选逻辑
  // return approvals.value
  if (!searchQuery.value) return approvals.value
  return approvals.value.filter((item) => {
    // console.log(item.categoryName,item.name,searchQuery.value);
    return item.categoryName.includes(searchQuery.value) || item.name.includes(searchQuery.value)
  })
})

const selectionData = ref([...props.modelValue])

const isInSelectionData = (item) => {
  return selectionData.value.some((selectedItem) => selectedItem.id === item.id)
}

const handleSelectionDataChange = (checked, item) => {
  if (checked) {
    selectionData.value.push(item)
  } else {
    const idx = selectionData.value.indexOf((selectedItem) => selectedItem.id === item.id)
    if (idx !== -1) {
      selectionData.value.splice(idx, 1)
    }
  }
}

const confirmSelection = () => {
  // const selectedApprovals = approvals.value.filter((item) => item.selected)
  const arr = selectionData.value.map((item) => {
    const { categoryName, startUser, startTime, status, id } = item
    return {
      categoryName,
      startTime,
      status,
      id,
      nickname: startUser.nickname
    }
  })
  emit('update:modelValue', arr)
  emit('confirm', arr)

  // 处理确认逻辑
  visible.value = false
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

<style scoped>
.filter-row {
  display: flex;
  margin: 15px 0;
  gap: 10px;
}

.filter-select {
  flex: 1;
}

.approval-list {
  margin-top: 10px;
}

.approval-item {
  display: flex;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
  align-items: flex-start;
}

.approval-content {
  flex: 1;
  margin-left: 10px;
}

.approval-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.approval-title {
  font-weight: bold;
}

.approval-details p {
  margin: 4px 0;
  color: #606266;
}

.approval-footer {
  display: flex;
  align-items: center;
  margin-top: 10px;
  color: #909399;
  font-size: 13px;
  justify-content: space-between;
}
.left_box {
  align-items: center;
  display: flex;
}
.approval-user {
  margin: 0 10px;
}
</style>
