<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="项目编号" prop="receivableProjectCode">
        <el-input
          v-model="queryParams.receivableProjectCode"
          placeholder="请输入项目编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="receivableProjectName">
        <el-input
          v-model="queryParams.receivableProjectName"
          placeholder="请输入项目名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="集团应收模板编号" prop="invoiceCode">
        <el-input
          v-model="queryParams.invoiceCode"
          placeholder="请输入集团应收模板编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="项目大类" prop="projectCategory">
        <el-input
          v-model="queryParams.projectCategory"
          placeholder="请输入项目大类"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="项目小类" prop="projectType">
        <el-input
          v-model="queryParams.projectType"
          placeholder="请输入项目小类"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="总包" prop="generalContractor">
        <el-input
          v-model="queryParams.generalContractor"
          placeholder="请输入总包"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="客户简称" prop="customerAbbreviation">
        <el-input
          v-model="queryParams.customerAbbreviation"
          placeholder="请输入客户简称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="合同签订方" prop="contractParties">
        <el-input
          v-model="queryParams.contractParties"
          placeholder="请输入合同签订方"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="WBS.元素" prop="wbsElement">
        <el-input
          v-model="queryParams.wbsElement"
          placeholder="请输入WBS.元素"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="行项目" prop="lineItem">
        <el-input
          v-model="queryParams.lineItem"
          placeholder="请输入行项目"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="项目状态" prop="finProjectStatus">
        <el-input
          v-model="queryParams.finProjectStatus"
          placeholder="请输入项目状态"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="业务项目状态" prop="receivableProjectStatus">
        <el-select v-model="queryParams.receivableProjectStatus" placeholder="请选择业务项目状态" clearable @keyup.enter="handleQuery">
          <el-option v-for="dict in project_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增信息</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Sort"-->
<!--          @click="toggleExpandAll"-->
<!--          :disabled="treeData.length === 0"-->
<!--        >展开/折叠全部</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          icon="Refresh"-->
<!--          @click="refreshTree"-->
<!--        >刷新树</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="default"-->
<!--          plain-->
<!--          icon="Grid"-->
<!--          @click="goToTableView"-->
<!--        >表格视图</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <!-- 树形表格 - 项目信息表头 -->
    <el-table
      ref="treeTable"
      v-loading="loading"
      :data="treeData"
      row-key="accountReceivableId"
      border
      lazy
      :load="loadNodeChildren"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @expand-change="handleExpandChange"
      style="width: 100%"
      class="tree-table"
      :span-method="objectSpanMethod"
    >
      <!-- 项目编号列 - 也是合并显示列 -->
      <el-table-column prop="receivableProjectCode" label="项目编号" width="200">
        <template #default="scope">
          <!-- 项目行显示项目编号 -->
          <div v-if="scope.row.type === 'project'" class="project-cell">
            <el-icon class="project-folder-icon"><Folder /></el-icon>
            <span>{{ scope.row.receivableProjectCode }}</span>
          </div>

          <!-- 汇总信息卡片 - 第一行 -->
          <div v-else-if="scope.row.type === 'summary'" class="merged-cell-content">
            <div class="summary-card">
              <div class="summary-header">
                <el-icon class="summary-header-icon"><Collection /></el-icon>
                <span class="summary-header-title">项目汇总</span>
              </div>
              <div class="summary-grid">
                <!-- 收款节点数量 -->
                <div class="summary-item">
                  <div class="summary-item-header">
                    <el-icon class="summary-item-icon"><List /></el-icon>
                    <span class="summary-item-label">收款节点</span>
                  </div>
                  <div class="summary-item-value">{{ scope.row.nodeCount }}</div>
                  <div class="summary-item-unit">个</div>
                </div>
                <!-- 总欠款金额 -->
                <div class="summary-item">
                  <div class="summary-item-header">
                    <el-icon class="summary-item-icon"><Money /></el-icon>
                    <span class="summary-item-label">总欠款</span>
                  </div>
                  <div class="summary-item-value">{{ formatMoney(scope.row.totalOwed) }}</div>
                  <div class="summary-item-unit">元</div>
                </div>
                <!-- 总回款金额 -->
                <div class="summary-item">
                  <div class="summary-item-header">
                    <el-icon class="summary-item-icon"><DataLine /></el-icon>
                    <span class="summary-item-label">总回款</span>
                  </div>
                  <div class="summary-item-value">{{ formatMoney(scope.row.totalReceived) }}</div>
                  <div class="summary-item-unit">元</div>
                </div>
                <!-- 已回款比例 -->
                <div class="summary-item">
                  <div class="summary-item-header">
                    <el-icon class="summary-item-icon"><Calendar /></el-icon>
                    <span class="summary-item-label">回款比例</span>
                  </div>
                  <div class="summary-item-value">{{ scope.row.paidRate }}%</div>
                  <div class="summary-item-unit">%</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 节点信息卡片 - 后续行 -->
          <div v-else class="merged-cell-content">
            <div class="node-card">
              <!-- 卡片头部 -->
              <div class="node-card-header">
                <div class="node-title-group">
                  <div class="node-icon-wrapper">
                    <el-icon :class="`node-icon ${scope.row.type}`">
                      <component :is="getNodeIcon(scope.row.type)" />
                    </el-icon>
                  </div>
                  <div class="node-info">
                    <span class="node-name">{{ scope.row.name }}</span>
                    <div class="node-meta">
                      <el-tag
                        size="small"
                        :type="getNodeStatusType(scope.row)"
                        class="node-status-tag"
                      >{{ getNodeStatus(scope.row) }}</el-tag>
                      <span class="node-amount-badge">{{ formatMoney(scope.row.amount) }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 卡片主体 -->
              <div class="node-card-body">
                <!-- 第一行信息 -->
                <div class="info-grid">
                  <div class="info-box">
                    <div class="info-box-label">
                      <el-icon><Money /></el-icon>节点金额
                    </div>
                    <div class="info-box-value">{{ formatMoney(scope.row.amount) }}</div>
                    <div class="info-box-sub">占比 {{ scope.row.proportion }}%</div>
                  </div>
                  <div class="info-box">
                    <div class="info-box-label">
                      <el-icon><Calendar /></el-icon>账期
                    </div>
                    <div class="info-box-value">{{ scope.row.period || '-' }}</div>
                    <div class="info-box-sub">{{ scope.row.startDate ? parseTime(scope.row.startDate) : '未开始' }}</div>
                  </div>
                  <div class="info-box">
                    <div class="info-box-label">
                      <el-icon><Timer /></el-icon>到期日
                    </div>
                    <div :class="`info-box-value ${getDueDateClass(scope.row)}`">
                      {{ parseTime(scope.row.dueDate) || '-' }}
                    </div>
                    <div class="info-box-sub">
                      {{ scope.row.overdueDays > 0 ? `已逾期${scope.row.overdueDays}天` : '未逾期' }}
                    </div>
                  </div>
                </div>

                <!-- 第二行信息 -->
                <div class="info-grid">
                  <div class="info-box success">
                    <div class="info-box-label">
                      <el-icon><DataLine /></el-icon>已回款
                    </div>
                    <div class="info-box-value success">{{ formatMoney(scope.row.received) }}</div>
                    <div class="info-box-sub">{{ ((scope.row.received / scope.row.amount) * 100).toFixed(1) }}%</div>
                  </div>
                  <div :class="`info-box ${scope.row.owed > 0 ? 'warning' : ''}`">
                    <div class="info-box-label">
                      <el-icon><Warning /></el-icon>欠款金额
                    </div>
                    <div :class="`info-box-value ${scope.row.owed > 0 ? 'warning' : ''}`">
                      {{ formatMoney(scope.row.owed) }}
                    </div>
                    <div class="info-box-sub">{{ scope.row.owed > 0 ? '待收款' : '已结清' }}</div>
                  </div>
                  <div class="info-box">
                    <div class="info-box-label">
                      <el-icon><User /></el-icon>客户经理
                    </div>
                    <div class="info-box-value">冯俊杰</div>
                    <div class="info-box-sub">负责人</div>
                  </div>
                </div>

                <!-- 进度条 -->
                <div class="progress-section">
                  <div class="progress-header">
                    <div class="progress-title">
                      <el-icon><DataLine /></el-icon>回款进度
                    </div>
                    <span :class="`progress-percentage ${getProgressClass(scope.row)}`">
                                 {{ ((scope.row.received / scope.row.amount) * 100).toFixed(1) }}%
                              </span>
                  </div>
                  <el-progress
                    :percentage="(scope.row.received / scope.row.amount) * 100"
                    :color="getProgressColor(scope.row)"
                    :stroke-width="8"
                    :status="getProgressStatus(scope.row)"
                  />
                </div>

                <!-- 逾期警告 -->
                <div v-if="scope.row.overdueDays > 0" class="overdue-warning">
                  <el-icon class="overdue-icon"><Warning /></el-icon>
                  <span class="overdue-text">该节点已逾期 {{ scope.row.overdueDays }} 天，请及时处理！</span>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 海威项目编号列 -->
      <el-table-column prop="receivableProjectName" label="项目名称" width="150">
        <template #default="scope">
          <span v-if="scope.row.type === 'project'">{{ scope.row.receivableProjectName }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="invoiceCode" label="集团应收模板编号" width="130">
        <template #default="scope">
          <span v-if="scope.row.type === 'project'">{{ scope.row.invoiceCode || scope.row.invoiceCode }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="projectCategory" label="项目大类" width="120">
        <template #default="scope">
          <span v-if="scope.row.type === 'project'">{{ scope.row.projectCategory }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="projectType" label="项目小类" width="120">
        <template #default="scope">
          <span v-if="scope.row.type === 'project'">{{ scope.row.projectType }}</span>
        </template>
      </el-table-column>


      <el-table-column prop="generalContractor" label="总包" min-width="120">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="client-cell">
<!--            <el-icon class="client-icon"><User /></el-icon>-->
            <span>{{ scope.row.generalContractor }}</span>
          </div>
        </template>
      </el-table-column>

      <!-- 客户名称列 -->
      <el-table-column prop="customerAbbreviation" label="客户简称" min-width="120">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="client-cell">
            <el-icon class="client-icon"><User /></el-icon>
            <span>{{ scope.row.customerAbbreviation }}</span>
          </div>
        </template>
      </el-table-column>

      <!-- 合同编号列 -->
      <el-table-column prop="contractParties" label="合同签订方" width="150">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
<!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ scope.row.contractParties }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="wbsElement" label="WBS.元素" width="120">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ scope.row.wbsElement }}</span>
          </div>
        </template>
      </el-table-column>


      <el-table-column prop="lineItem" label="行项目" width="100">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ scope.row.lineItem }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="finProjectStatus" label="项目状态" width="100">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ scope.row.finProjectStatus }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="receivableProjectStatus" label="业务项目状态" width="110">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
              <dict-tag :options="project_status" :value="scope.row.receivableProjectStatus" />

          </div>
        </template>
      </el-table-column>


      <el-table-column prop="settlementMonth" label="结算月份" width="100">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ formatToMonth(scope.row.settlementMonth) }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="totalPrice" label="合同金额" width="120">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ scope.row.totalPrice }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="income" label="收入" width="120">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ scope.row.income }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="invoiceAmount" label="开票金额" width="120">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ scope.row.invoiceAmount }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="managerName" label="项目经理" width="120">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="contract-cell">
            <!--            <el-icon class="contract-icon"><Document /></el-icon>-->
            <span>{{ scope.row.managerName }}</span>
          </div>
        </template>
      </el-table-column>



      <!-- 操作列 -->
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template #default="scope">
          <div v-if="scope.row.type === 'project'" class="action-buttons">
            <el-button link type="primary" size="small" @click="handleUpdate(scope.row)">
              <el-icon><Edit /></el-icon>修改
            </el-button>
            <el-button link type="primary" size="small" @click="handleDetail(scope.row)">
              <el-icon><Document /></el-icon>详情
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </div>
          <div v-else class="action-buttons">
            <el-button v-if="scope.row.type === 'summary'" link type="primary" size="small" @click="handleAddNode(scope.row)">
              <el-icon><Plus /></el-icon>添加节点
            </el-button>
            <template v-else>
              <el-button link type="primary" size="small" @click="handleEditNode(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button link type="primary" size="small" @click="handleCalculateNode(scope.row)">
                <el-icon><Refresh /></el-icon>计算
              </el-button>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页（只对根节点分页） -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="ReceivableTreeList" lang="ts">
import { ref, reactive, getCurrentInstance, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Folder, Money, DataLine, DocumentChecked, Document, Timer,
  List, Calendar, User, Avatar, Edit, Refresh, Warning, Collection,
  Plus
} from '@element-plus/icons-vue'
import {
  listFinAccountReceivable,delFinAccountReceivable
} from '@/api/oa/erp/finAccountReceivable';
import Default from 'vue-json-pretty';
import { FinAccountReceivableVO } from '@/api/oa/erp/finAccountReceivable/types';
const { proxy } = getCurrentInstance()
const router = useRouter()

const { project_status } = toRefs<any>(
  proxy?.useDict('project_status')
);

// 列表数据
const treeData = ref([])
const total = ref(0)
const loading = ref(false)
const showSearch = ref(true)
const expandAll = ref(false)
const treeTable = ref(null)

const queryFormRef = ref<ElFormInstance>();

// 存储当前展开的项目ID
const expandedProjectIds = ref(new Set())

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  projectNo: undefined,
  clientName: undefined,
  projectStatus: undefined
})


const formatToMonth = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d.getTime())) return date // 如果是无效日期，返回原值

  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  return `${year}-${month}` // 输出格式：2024-01
}


// Mock项目数据（根节点）
let mockProjects = [
  {
    id: 1,
    type: 'project',
    name: 'SF-信源17套通道门&2套清洗设备项目',
    projectNo: 'S-202415275',
    haiweiProjectNo: 'HW-2024001',
    clientName: '广东信源物流设备有限公司',
    clientManager: '冯俊杰',
    contractNo: 'CT-2024-001',
    contractAmount: 177100,
    contractDate: '2024-05-31',
    projectStatus: '进行中',
    hasChildren: true,
    children: []
  },
  {
    id: 2,
    type: 'project',
    name: '某智能仓储项目',
    projectNo: 'S-202412345',
    haiweiProjectNo: 'HW-2024002',
    clientName: '某科技有限公司',
    clientManager: '张三',
    contractNo: 'CT-2024-002',
    contractAmount: 350000,
    contractDate: '2024-03-15',
    projectStatus: '已结算',
    hasChildren: true,
    children: []
  },
  {
    id: 3,
    type: 'project',
    name: '某物流分拣系统',
    projectNo: 'S-202478901',
    haiweiProjectNo: 'HW-2024003',
    clientName: '某物流公司',
    clientManager: '李四',
    contractNo: 'CT-2024-003',
    contractAmount: 520000,
    contractDate: '2024-01-20',
    projectStatus: '进行中',
    hasChildren: true,
    children: []
  }
]


/** 查询应收款信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFinAccountReceivable(queryParams.value);
  mockProjects = res.rows;

  total.value = res.total;
  loading.value = false;

  treeData.value = mockProjects.map(p => ({
    ...p,
    hasChildren:false,
    type:'project',
    children: [] // 初始为空，等待点击加载
  }))
  expandedProjectIds.value.clear()
  console.log("1111")
  console.log(treeData.value)
}


// 计算逾期天数
const calculateOverdueDays = (dueDate) => {
  if (!dueDate) return 0
  const today = new Date()
  const due = new Date(dueDate)
  if (today > due) {
    const diffTime = today - due
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  }
  return 0
}

// 获取项目汇总数据
const getProjectSummary = (projectId) => {
  if (projectId === 1) {
    return {
      nodeCount: 4,
      totalOwed: 28090,
      totalReceived: 149010,
      paidRate: (149010 / 177100 * 100).toFixed(2)
    }
  } else if (projectId === 2) {
    return {
      nodeCount: 3,
      totalOwed: 0,
      totalReceived: 350000,
      paidRate: (350000 / 350000 * 100).toFixed(2)
    }
  } else if (projectId === 3) {
    return {
      nodeCount: 4,
      totalOwed: 316000,
      totalReceived: 204000,
      paidRate: (204000 / 520000 * 100).toFixed(2)
    }
  }
  return {
    nodeCount: 0,
    totalOwed: 0,
    totalReceived: 0,
    paidRate: 0
  }
}

// 收款节点数据（根据项目ID动态返回）
const getNodeChildren = (row, treeNode, resolve) => {
  // 模拟异步加载
  setTimeout(() => {
    let children = []
    const summary = getProjectSummary(row.accountReceivableId)

    // 第一行：汇总信息
    children.push({
      accountReceivableId: `summary-${row.id}`,
      parentId: row.id,
      type: 'summary',
      name: '项目汇总',
      nodeCount: summary.nodeCount,
      totalOwed: summary.totalOwed,
      totalReceived: summary.totalReceived,
      paidRate: summary.paidRate,
      hasChildren: false
    })

    // 后续行：收款节点
    if (row.accountReceivableId === 4) {
      children.push(
        {
          id: 101,
          parentId: 1,
          type: 'startup',
          name: '启动款',
          amount: 53130,
          proportion: 30,
          received: 53130,
          owed: 0,
          startDate: '2024-05-31',
          dueDate: '2024-06-30',
          period: '30天',
          overdueDays: 0,
          hasChildren: false
        },
        {
          id: 102,
          parentId: 1,
          type: 'delivery',
          name: '发货/到货款',
          amount: 53130,
          proportion: 30,
          received: 53130,
          owed: 0,
          startDate: '2024-06-10',
          dueDate: '2024-07-20',
          period: '30天',
          overdueDays: 0,
          hasChildren: false
        },
        {
          id: 103,
          parentId: 1,
          type: 'initial',
          name: '初验/验收款',
          amount: 53130,
          proportion: 30,
          received: 42750,
          owed: 10380,
          startDate: '2025-05-25',
          dueDate: '2025-06-25',
          period: '30天',
          overdueDays: calculateOverdueDays('2023-06-25'),
          hasChildren: false
        },
        {
          id: 104,
          parentId: 1,
          type: 'warranty',
          name: '质保款',
          amount: 17710,
          proportion: 10,
          received: 0,
          owed: 17710,
          startDate: '2025-06-25',
          dueDate: '2026-06-25',
          period: '12个月',
          overdueDays: 0,
          hasChildren: false
        }
      )
    } else if (row.id === 2) {
      children.push(
        {
          id: 201,
          parentId: 2,
          type: 'startup',
          name: '启动款',
          amount: 105000,
          proportion: 30,
          received: 105000,
          owed: 0,
          startDate: '2024-03-15',
          dueDate: '2024-04-15',
          period: '30天',
          overdueDays: 0,
          hasChildren: false
        },
        {
          id: 202,
          parentId: 2,
          type: 'delivery',
          name: '发货/到货款',
          amount: 105000,
          proportion: 30,
          received: 105000,
          owed: 0,
          startDate: '2024-04-10',
          dueDate: '2024-05-20',
          period: '30天',
          overdueDays: 0,
          hasChildren: false
        },
        {
          id: 203,
          parentId: 2,
          type: 'final',
          name: '终验/验收款',
          amount: 140000,
          proportion: 40,
          received: 140000,
          owed: 0,
          startDate: '2024-07-20',
          dueDate: '2024-08-20',
          period: '30天',
          overdueDays: 0,
          hasChildren: false
        }
      )
    } else if (row.id === 3) {
      children.push(
        {
          id: 301,
          parentId: 3,
          type: 'startup',
          name: '启动款',
          amount: 104000,
          proportion: 20,
          received: 104000,
          owed: 0,
          startDate: '2024-01-20',
          dueDate: '2024-02-20',
          period: '30天',
          overdueDays: 0,
          hasChildren: false
        },
        {
          id: 302,
          parentId: 3,
          type: 'delivery',
          name: '发货/到货款',
          amount: 156000,
          proportion: 30,
          received: 100000,
          owed: 56000,
          startDate: '2024-02-25',
          dueDate: '2024-03-25',
          period: '30天',
          overdueDays: calculateOverdueDays('2024-03-25'),
          hasChildren: false
        },
        {
          id: 303,
          parentId: 3,
          type: 'initial',
          name: '初验/验收款',
          amount: 156000,
          proportion: 30,
          received: 0,
          owed: 156000,
          startDate: '2024-05-30',
          dueDate: '2024-06-30',
          period: '30天',
          overdueDays: 0,
          hasChildren: false
        },
        {
          id: 304,
          parentId: 3,
          type: 'warranty',
          name: '质保款',
          amount: 104000,
          proportion: 20,
          received: 0,
          owed: 104000,
          startDate: '2024-06-30',
          dueDate: '2025-01-20',
          period: '12个月',
          overdueDays: 0,
          hasChildren: false
        }
      )
    }

    resolve(children)

    // 记录展开的项目ID
    nextTick(() => {
      expandedProjectIds.value.add(row.id)
    })
  }, 500)
}

/** 查询列表 */
// function getList() {
//   loading.value = true
//   // 模拟API调用
//   setTimeout(() => {
//     treeData.value = mockProjects.map(p => ({
//       ...p,
//       children: [] // 初始为空，等待点击加载
//     }))
//     total.value = mockProjects.length
//     loading.value = false
//     expandedProjectIds.value.clear()
//   }, 500)
// }

/** 加载子节点数据（lazy加载模式） */
function loadNodeChildren(row, treeNode, resolve) {
  if (row.type === 'project') {
    getNodeChildren(row, treeNode, resolve)
  } else {
    resolve([])
  }
}

/** 处理行展开/折叠 */
function handleExpandChange(row, expanded) {
  if (expanded) {
    expandedProjectIds.value.add(row.id)
  } else {
    expandedProjectIds.value.delete(row.id)
  }
}

/** 合并单元格方法 */
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 只对子节点（非project类型）进行合并
  if (row.type !== 'project') {
    // 对于子节点，将所有列合并到第一列（项目编号列）
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: 4  // 合并前4列
      }
    }
    // 其他列隐藏
    if (columnIndex >= 1 && columnIndex <= 3) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
    // 操作列保持原样
    if (columnIndex === 4) {
      return {
        rowspan: 1,
        colspan: 1
      }
    }
  }
  return {
    rowspan: 1,
    colspan: 1
  }
}

/** 展开/折叠全部 */
function toggleExpandAll() {
  expandAll.value = !expandAll.value

  treeData.value.forEach(row => {
    if (row.type === 'project') {
      treeTable.value.toggleRowExpansion(row, expandAll.value)
      if (expandAll.value) {
        expandedProjectIds.value.add(row.id)
      } else {
        expandedProjectIds.value.clear()
      }
    }
  })

  ElMessage.info(expandAll.value ? '已全部展开' : '已全部折叠')
}

/** 刷新树 */
function refreshTree() {
  getList()
}

/** 格式化日期 */
function parseTime(date) {
  if (!date) return ''
  return date.substring(0, 10)
}

/** 格式化金额 */
function formatMoney(value) {
  if (value === undefined || value === null) return ''
  return new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value)
}

/** 获取项目状态标签类型 */
function getStatusType(status) {
  const map = {
    '进行中': 'primary',
    '已结算': 'success',
    '已终止': 'danger'
  }
  return map[status] || 'info'
}

/** 获取节点状态 */
function getNodeStatus(node) {
  if (node.received === 0) return '待回款'
  if (node.owed === 0) return '已完成'
  if (node.owed > 0) {
    const today = new Date()
    const dueDate = new Date(node.dueDate)
    return today > dueDate ? '逾期' : '部分回款'
  }
  return '待处理'
}

/** 获取节点状态标签类型 */
function getNodeStatusType(node) {
  if (node.received === 0) return 'info'
  if (node.owed === 0) return 'success'
  if (node.owed > 0) {
    const today = new Date()
    const dueDate = new Date(node.dueDate)
    return today > dueDate ? 'danger' : 'warning'
  }
  return 'info'
}

/** 获取节点类型图标 */
function getNodeIcon(type) {
  const icons = {
    'startup': Money,
    'delivery': Money,
    'kpi': DataLine,
    'initial': DocumentChecked,
    'final': Document,
    'warranty': Timer
  }
  return icons[type] || Document
}

/** 获取到期日样式 */
function getDueDateClass(node) {
  if (node.owed === 0) return ''
  const today = new Date()
  const dueDate = new Date(node.dueDate)
  return today > dueDate ? 'danger' : 'warning'
}

/** 获取进度条颜色 */
function getProgressColor(node) {
  const rate = node.received / node.amount
  if (rate >= 1) return '#67C23A'
  if (rate >= 0.5) return '#E6A23C'
  return '#F56C6C'
}

/** 获取进度条状态 */
function getProgressStatus(node) {
  const rate = node.received / node.amount
  if (rate >= 1) return 'success'
  if (rate > 0) return 'active'
  return 'exception'
}

/** 获取进度条文字样式 */
function getProgressClass(node) {
  const rate = node.received / node.amount
  if (rate >= 1) return 'success'
  if (rate >= 0.5) return 'warning'
  return 'danger'
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增项目 */
function handleAdd() {

  router.push({
    path: '/fin/finAccountReceivable/add',
    query: {
      type: 'add',
      pageNum: queryParams.value.pageNum,
    }
  });

}

/** 修改项目 */
function handleUpdate(row) {
  router.push({
    path: '/fin/finAccountReceivable/add',
    query: {
      type: 'edit',
      accountReceivableId: row.accountReceivableId,
      pageNum: queryParams.value.pageNum
    }
  });
}

/** 查看详情 */
function handleDetail(row) {
  router.push({
    path: '/fin/finAccountReceivable/add',
    query: {
      type: 'view',
      accountReceivableId: row.accountReceivableId,
      pageNum: queryParams.value.pageNum
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: FinAccountReceivableVO) => {
  const _receivableIds = row?.accountReceivableId;
  const receivableProjectCode = row?.receivableProjectCode;
  await proxy?.$modal.confirm('是否确认删除项目编号为"' + receivableProjectCode + '"的数据项？').finally(() => (loading.value = false));
  await delFinAccountReceivable(_receivableIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};


/** 添加节点 */
function handleAddNode(row) {
  const projectId = row.parentId
  const project = treeData.value.find(p => p.id === projectId)
  ElMessage.info(`为项目 ${project?.projectNo} 添加收款节点`)
}

/** 编辑节点 */
function handleEditNode(row) {
  ElMessage.info(`编辑节点：${row.name}`)
}

/** 计算节点 */
function handleCalculateNode(row) {
  const paidRate = row.received > 0 ? (row.received / row.amount * 100).toFixed(2) : 0
  ElMessage.success(`${row.name}：应回款 ${formatMoney(row.amount)} 元，已回款 ${formatMoney(row.received)} 元，回款比例 ${paidRate}%`)
}

/** 跳转到表格视图 */
function goToTableView() {
  router.push('/receivable')
}

/** 判断当前项目是否展开 */
function isProjectExpanded(projectId) {
  return expandedProjectIds.value.has(projectId)
}

onMounted(() => {
  getList();
});

onActivated(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.mb8 {
  margin-bottom: 8px;
}

/* 树形表格样式 */
.tree-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 确保展开图标可见 */
:deep(.el-table__expand-icon) {
  font-size: 18px;
  color: #409EFF;
  background-color: #ecf5ff;
  border-radius: 4px;
  padding: 2px;
  margin-right: 8px;
  transition: all 0.3s;
}

:deep(.el-table__expand-icon:hover) {
  background-color: #409EFF;
  color: white;
}

:deep(.el-table__expand-icon .el-icon) {
  font-weight: bold;
}

:deep(.el-table__placeholder) {
  display: inline-block;
  width: 26px;
  margin-right: 8px;
}

/* 项目单元格样式 */
.project-cell, .client-cell, .contract-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.project-folder-icon {
  color: #E6A23C;
  font-size: 18px;
}

.client-icon {
  color: #409EFF;
  font-size: 16px;
}

.contract-icon {
  color: #67C23A;
  font-size: 16px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 1px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 合并单元格内容容器 */
.merged-cell-content {
  width: 100%;
  padding: 10px 0;
}

/* 汇总信息卡片 */
.summary-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 20px;
  color: white;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
  margin: 5px 0;
}

.summary-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.summary-header-icon {
  font-size: 24px;
  color: white;
  background: rgba(255, 255, 255, 0.2);
  padding: 8px;
  border-radius: 12px;
}

.summary-header-title {
  font-size: 18px;
  font-weight: 600;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.summary-item {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  padding: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s;
}

.summary-item:hover {
  transform: translateY(-4px);
  background: rgba(255, 255, 255, 0.15);
}

.summary-item-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.summary-item-icon {
  font-size: 20px;
  color: rgba(255, 255, 255, 0.9);
}

.summary-item-label {
  font-size: 13px;
  opacity: 0.8;
}

.summary-item-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.summary-item-unit {
  font-size: 12px;
  opacity: 0.6;
}

/* 节点卡片 */
.node-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  margin: 10px 0;
}

.node-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  border-color: #409EFF;
}

.node-card-header {
  padding: 16px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  border-bottom: 1px solid #dcdfe6;
}

.node-title-group {
  display: flex;
  align-items: center;
  gap: 14px;
}

.node-icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.node-icon {
  font-size: 22px;
}

.node-icon.startup { color: #409EFF; }
.node-icon.delivery { color: #67C23A; }
.node-icon.kpi { color: #E6A23C; }
.node-icon.initial { color: #9B59B6; }
.node-icon.final { color: #3498DB; }
.node-icon.warranty { color: #F56C6C; }

.node-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.node-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.node-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.node-status-tag {
  margin-right: 8px;
}

.node-amount-badge {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.node-card-body {
  padding: 20px;
}

/* 信息网格 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.info-box {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 12px;
  border-left: 4px solid #409EFF;
  transition: all 0.3s;
}

.info-box:hover {
  background: #ecf5ff;
}

.info-box.warning {
  border-left-color: #E6A23C;
}

.info-box.success {
  border-left-color: #67C23A;
}

.info-box.danger {
  border-left-color: #F56C6C;
}

.info-box-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #909399;
  margin-bottom: 6px;
  text-transform: uppercase;
}

.info-box-label .el-icon {
  font-size: 14px;
}

.info-box-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.info-box-value.success {
  color: #67C23A;
}

.info-box-value.warning {
  color: #E6A23C;
}

.info-box-value.danger {
  color: #F56C6C;
}

.info-box-sub {
  font-size: 12px;
  color: #909399;
}

/* 进度条区域 */
.progress-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #dcdfe6;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.progress-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.progress-title .el-icon {
  font-size: 16px;
  color: #409EFF;
}

.progress-percentage {
  font-size: 18px;
  font-weight: bold;
}

.progress-percentage.success {
  color: #67C23A;
}

.progress-percentage.warning {
  color: #E6A23C;
}

.progress-percentage.danger {
  color: #F56C6C;
}

/* 逾期警告 */
.overdue-warning {
  margin-top: 16px;
  padding: 12px 16px;
  background: #fef0f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #F56C6C;
  border: 1px solid #fcdcdc;
}

.overdue-icon {
  font-size: 18px;
}

.overdue-text {
  font-size: 14px;
  font-weight: 500;
}

/* 行样式 */
:deep(.el-table .el-table__row--level-0) {
  background-color: #ffffff;
}

:deep(.el-table .el-table__row--level-0:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table .el-table__row--level-1) {
  background-color: #fafafa;
}

:deep(.el-table .el-table__row--level-1 .el-table__cell) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

/* 汇总行特殊样式 */
:deep(.el-table .el-table__row--level-1:first-child .el-table__cell) {
  background-color: #f0f9eb;
}

/* 节点行交替背景 */
:deep(.el-table .el-table__row--level-1:nth-child(odd)) {
  background-color: #ffffff;
}

:deep(.el-table .el-table__row--level-1:nth-child(even)) {
  background-color: #fafafa;
}

/* 响应式 */
@media (max-width: 1200px) {
  .summary-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .node-card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .summary-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
