<template>
  <div class="message-notify-container">
    <el-table
      style="width: 100%; margin-top: 20px"
      border
      :data="localFormData"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
    >
      <el-table-column prop="id" label="序号" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="noticeTitle"
        label="消息主题"
        width="200"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="noticeSource"
        label="消息来源"
        width="220"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="auditObject"
        label="发送对象"
        width="150"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="noticeContent"
        label="消息内容"
        min-width="350"
        header-align="center"
        align="left"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="发送时间"
        width="120"
        align="center"
        sortable
      >
        <template slot-scope="scope">
          <div>{{ scope.row.createTime.split(' ')[0] }}</div>
          <div>{{ scope.row.createTime.split(' ')[1] }}</div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="total, sizes, prev, pager, next"
      :current-page="internalPagination.currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="internalPagination.pageSize"
      :total="internalPagination.total"
      style="margin-top: 20px; text-align: right"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>
<script>
  import { sendMessage } from '@/api/auditTaskProcessing'
  export default {
    name: 'MessageNoticeTab',
    props: {
      id: {
        type: String,
        default: '',
      },
      formData: {
        type: Array,
        default: () => [],
      },
      pagination: {
        type: Object,
        default: () => ({ currentPage: 1, pageSize: 10, total: 0 }),
      },
      selectedProject: {
        type: Object,
        default: () => ({}),
      },
    },
    data() {
      return {
        internalPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        localFormData: [],
      }
    },
    watch: {
      pagination: {
        handler(newVal) {
          if (newVal) {
            this.internalPagination = {
              currentPage: newVal.currentPage || 1,
              pageSize: newVal.pageSize || 10,
              total: newVal.total || 0,
            }
          }
        },
        immediate: true,
        deep: true,
      },
      formData: {
        handler(newVal) {
          this.localFormData = newVal || []
        },
        immediate: true,
        deep: true,
      },
      // id: {
      //   handler(newVal) {
      //     if (newVal) {
      //       // 重置到第一页并重新加载
      //       this.internalPagination.currentPage = 1
      //       this.getNoticeList()
      //     }
      //   },
      //   immediate: false,
      // },
    },
    mounted() {
      // 初始化分页数据
      // if (this.pagination) {
      //   this.internalPagination = {
      //     currentPage: this.pagination.currentPage || 1,
      //     pageSize: this.pagination.pageSize || 10,
      //     total: this.pagination.total || 0,
      //   }
      // }
      // if (this.formData) {
      //   this.localFormData = this.formData
      // }
      // this.getNoticeList()
    },
    methods: {
      // 处理页码变化
      handleCurrentChange(page) {
        this.internalPagination.currentPage = page
        this.getNoticeList()
      },
      // 处理每页条数变化
      handleSizeChange(size) {
        this.internalPagination.pageSize = size
        this.internalPagination.currentPage = 1 // 重置到第一页
        this.getNoticeList()
      },
      // 获取消息通知列表
      async getNoticeList() {
        // 检查是否有子项目
        if (
          !this.selectedProject ||
          !this.selectedProject.children ||
          !Array.isArray(this.selectedProject.children) ||
          this.selectedProject.children.length === 0
        ) {
          this.localFormData = []
          this.internalPagination.total = 0
          return
        }

        try {
          // 获取所有子项目（包含id和auditObject）
          const children = this.selectedProject.children.filter(
            (child) => child.id
          )

          // 为每个子项目发送请求，并保存对应的auditObject
          const promises = children.map((child) => {
            const params = {
              taskId: child.id,
              pageNum: this.internalPagination.currentPage,
              pageSize: this.internalPagination.pageSize,
            }
            // 发送请求并返回结果和对应的auditObject
            return sendMessage(params).then((res) => ({
              res,
              auditObject: child.auditObject,
            }))
          })

          // 并行处理所有请求
          const results = await Promise.all(promises)

          // 合并所有结果，并为每条记录添加auditObject
          let allRecords = []
          let totalCount = 0

          results.forEach(({ res, auditObject }) => {
            if (res && res.code === 200 && res.value) {
              // 为每条记录添加auditObject
              const recordsWithAuditObject = (res.value.records || []).map(
                (record) => ({
                  ...record,
                  auditObject,
                })
              )
              allRecords = allRecords.concat(recordsWithAuditObject)
              totalCount += res.value.total || 0
            }
          })

          // 更新表格数据
          this.localFormData = allRecords
          this.internalPagination.total = totalCount
        } catch (err) {
          console.error('获取消息通知失败', err)
          this.localFormData = []
          this.internalPagination.total = 0
        } finally {
        }
      },
    },
  }
</script>

<style scoped>
  /* 移除最外层容器的 padding */
  div {
    padding: 0;
  }
</style>
