<template>
  <div class="receivable-form-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2>{{ title }}</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="submitForm" :loading="buttonLoading" v-if="!isFormDisabled">保存</el-button>
        <el-button @click="resetForm" v-if="!isFormDisabled">重置</el-button>
        <!--        <el-button @click="handleCalculate" v-if="formData.id">重新计算</el-button>-->
      </div>
    </div>

    <el-divider />

    <!-- 表单内容 -->
    <el-form ref="receivableFormRef" :model="formData" :rules="formRules" :disabled="isFormDisabled" label-width="160px" class="receivable-form">
      <!-- 合同信息区域 - 可折叠 -->
      <div class="form-section" v-loading="loading">
        <div class="section-header" @click="toggleSection('contract')">
          <span class="section-title">合同基本信息</span>
          <el-icon class="section-icon">
            <ArrowDown v-if="!collapsed.contract" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <el-divider />
        <div class="section-content" v-show="!collapsed.contract">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="海威-项目编号" prop="projectCode">
                <el-input
                  v-if="!formData.accountReceivableId"
                  v-model="formData.projectCode"
                  placeholder="请选择项目"
                  readonly
                  @click="showProjectSelectDialog"
                  suffix-icon="Search"
                />
                <el-input v-if="formData.accountReceivableId" v-model="formData.projectCode" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="formData.projectName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同编号" prop="contractCode">
                <el-input
                  v-if="formData.projectId && formData.projectId !== '' && formData.contractFlag === CONTRACT_FLAG.NO"
                  v-model="formData.contractCode"
                  placeholder="请选择合同"
                  readonly
                  @click="showContractSelectDialog"
                  suffix-icon="Search"
                />
                <el-input v-else v-model="formData.contractCode" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同名称" prop="contractName">
                <el-input v-model="formData.contractName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签单月份" prop="contractDate">
                <el-date-picker v-model="formData.contractDate" type="month" readonly style="width: 100%" format="YYYY-MM" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同签订日期" prop="contractDate">
                <el-date-picker v-model="formData.contractDate" type="date" readonly style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外部合同编号" prop="externalContractCode">
                <el-input v-model="formData.externalContractCode" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="内部合同编号" prop="internalContractCode">
                <el-input v-model="formData.internalContractCode" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="oneCustomerName">
                <el-input v-model="formData.oneCustomerName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签订主体" prop="twoCustomerName">
                <el-input v-model="formData.twoCustomerName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务方向" prop="businessDirection">
                <dict-tag :options="business_direction" :value="formData.businessDirection" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="部门" prop="deptName">
                <el-input v-model="formData.deptName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户经理" prop="managerName">
                <el-input v-model="formData.managerName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="软控-订单号" prop="mesnacOrderNo">
                <el-input v-model="formData.mesnacOrderNo" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="软控-项目号" prop="mesnacProjectCode">
                <el-input v-model="formData.mesnacProjectCode" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单号" prop="orderContractCode">
                <el-input v-model="formData.orderContractCode" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务项目状态" prop="projectStatus">
                <dict-tag :options="project_status" :value="formData.projectStatus" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 基本信息区域 - 可折叠 -->
      <div class="form-section" v-loading="loading">
        <div class="section-header" @click="toggleSection('basic')">
          <span class="section-title">财务自填信息</span>
          <el-icon class="section-icon">
            <ArrowDown v-if="!collapsed.basic" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <el-divider />
        <div class="section-content" v-show="!collapsed.basic">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="集团应收模板编号" prop="invoiceCode">
                <el-input v-model="formData.invoiceCode" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目大类" prop="projectCategory">
                <el-input v-model="formData.projectCategory" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目小类" prop="projectType">
                <el-input v-model="formData.projectType" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总包" prop="generalContractor">
                <el-input v-model="formData.generalContractor" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户简称" prop="customerAbbreviation">
                <el-input v-model="formData.customerAbbreviation" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同签订方" prop="contractParties">
                <el-input v-model="formData.contractParties" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="WBS.元素" prop="wbsElement">
                <el-input v-model="formData.wbsElement" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="行项目" prop="lineItem">
                <el-input v-model="formData.lineItem" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目状态" prop="finProjectStatus">
                <el-input v-model="formData.finProjectStatus" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结算月份" prop="settlementMonth">
                <el-date-picker v-model="formData.settlementMonth" type="month" placeholder="请选择" style="width: 100%" format="YYYY-MM" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 财务信息区域 - 可折叠 -->
      <div class="form-section" v-loading="loading">
        <div class="section-header" @click="toggleSection('financial')">
          <span class="section-title">财务信息</span>
          <el-icon class="section-icon">
            <ArrowDown v-if="!collapsed.financial" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <el-divider />
        <div class="section-content" v-show="!collapsed.financial">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="开票金额" prop="invoiceAmount">
                <el-input v-model="formData.invoiceAmount" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收入" prop="income">
                <el-input v-model="formData.income" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同金额-人民币(主)" prop="totalPrice">
                <el-input v-model="formData.totalPrice" readonly>
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同金额-人民币(海威)" prop="totalPriceHighway">
                <el-input v-model="formData.totalPriceHighway" readonly>
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="背靠背比例" prop="backToBackRatio">
                <el-input v-model="formData.backToBackRatio" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="币种" prop="currency">
                <el-input v-model="formData.currency" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同金额-原币(海威)" prop="totalPriceOri">
                <el-input v-model="formData.totalPriceOri" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="汇率" prop="exchangeRate">
                <el-input v-model="formData.exchangeRate" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="付款方式" prop="paymentMethod">
                <el-input v-model="paymentDescription" type="textarea" :rows="4" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 收款节点信息区域 - 合并展示 -->
      <div class="form-section" v-loading="stageLoading">
        <div class="section-header" @click="toggleSection('paymentNodes')">
          <span class="section-title">收款节点信息</span>
          <el-icon class="section-icon">
            <ArrowDown v-if="!collapsed.paymentNodes" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <el-divider />
        <div class="section-content" v-show="!collapsed.paymentNodes">
          <div
            v-for="finAccountReceivableStage in finAccountReceivableStageList"
            :key="finAccountReceivableStage.receivableStageId"
            class="node-section"
          >
            <div class="node-title">{{ finAccountReceivableStage.stageName }}</div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="金额" prop="paymentAmount" label-width="90px">
                  <el-input v-model="finAccountReceivableStage.paymentAmount" placeholder="金额" readonly>
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="比例(%)" prop="paymentPercentage" label-width="96px">
                  <el-input v-model="finAccountReceivableStage.paymentPercentage" placeholder="比例" readonly>
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="finAccountReceivableStage.paymentStageId !== PAYMENT_STAGE_ID.WARRANTY">
                <el-form-item label="账期" prop="paymentDeadline" label-width="90px">
                  <el-input v-model="finAccountReceivableStage.paymentDeadline" placeholder="账期" readonly>
                    <template #append>天</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="finAccountReceivableStage.paymentStageId === PAYMENT_STAGE_ID.WARRANTY">
                <el-form-item label="质保条款" prop="paymentDeadline" label-width="90px">
                  <el-input v-model="finAccountReceivableStage.paymentDeadline" placeholder="质保条款" readonly> </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="已回款金额" prop="receivedAmount" label-width="90px">
                  <el-input
                    v-model="finAccountReceivableStage.receivedAmount"
                    placeholder="已回款"
                    @change="handleReceivedAmountChange(finAccountReceivableStage)"
                  >
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <!-- 基准日期字段 - 根据节点类型显示不同标签 -->
              <el-col :span="6" v-if="finAccountReceivableStage.paymentStageId === PAYMENT_STAGE_ID.DELIVERY">
                <el-form-item label="合同交货期" prop="stageRequiredDate" label-width="90px">
                  <el-date-picker v-model="finAccountReceivableStage.stageRequiredDate" type="date" placeholder="选择日期" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="6" v-if="getStageConfig(finAccountReceivableStage.paymentStageId).showStageRealDate">
                <el-form-item
                  :label="getStageConfig(finAccountReceivableStage.paymentStageId).stageRealDateLabel"
                  prop="stageRealDate"
                  label-width="90px"
                >
                  <el-date-picker
                    v-model="finAccountReceivableStage.stageRealDate"
                    type="date"
                    :placeholder="getStageConfig(finAccountReceivableStage.paymentStageId).stageRealDatePlaceholder"
                    style="width: 100%"
                    @change="handleDateChange(finAccountReceivableStage)"
                  />
                </el-form-item>
              </el-col>

              <!-- 到期日显示 -->
              <el-col :span="6" v-if="finAccountReceivableStage.paymentStageId !== PAYMENT_STAGE_ID.WARRANTY">
                <el-form-item label="到期日" prop="dueDate" label-width="90px">
                  <div class="date-display">{{ formatDate(finAccountReceivableStage.dueDate) }}</div>
                </el-form-item>
              </el-col>

              <!-- 结算日期字段（用于验收/初验/终验节点） -->
              <el-col
                :span="6"
                v-if="
                  finAccountReceivableStage.paymentStageId === PAYMENT_STAGE_ID.INITIAL_INSPECTION ||
                  finAccountReceivableStage.paymentStageId === PAYMENT_STAGE_ID.FINAL_INSPECTION ||
                  finAccountReceivableStage.paymentStageId === PAYMENT_STAGE_ID.ACCEPTANCE
                "
              >
                <el-form-item label="结算日期" prop="settlementDate" label-width="90px">
                  <el-date-picker
                    v-model="formData.settlementMonth"
                    type="date"
                    readonly
                    style="width: 100%"
                    @change="handleSettlementDateChange(finAccountReceivableStage)"
                  />
                </el-form-item>
              </el-col>

              <!-- 质保时间和质保日期（用于质保节点） -->
              <el-col :span="6" v-if="finAccountReceivableStage.paymentStageId === PAYMENT_STAGE_ID.WARRANTY">
                <el-form-item label="质保时间" prop="warrantyPeriod" label-width="90px">
                  <el-input
                    v-model="finAccountReceivableStage.warrantyPeriod"
                    placeholder="质保时间(天)"
                    @change="handleWarrantyChange(finAccountReceivableStage)"
                  >
                    <template #append>天</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="finAccountReceivableStage.paymentStageId === PAYMENT_STAGE_ID.WARRANTY">
                <el-form-item label="质保日期" prop="warrantyDate" label-width="90px">
                  <div class="date-with-status">
                    <span :class="getWarrantyStatusClass(finAccountReceivableStage.warrantyDate)">
                      {{ formatDate(finAccountReceivableStage.warrantyDate) }}
                    </span>
                    <el-tag
                      v-if="finAccountReceivableStage.warrantyDate"
                      :type="getWarrantyStatusType(finAccountReceivableStage.warrantyDate)"
                      size="small"
                      effect="light"
                      class="status-tag"
                    >
                      {{ getWarrantyStatus(finAccountReceivableStage.warrantyDate) }}
                    </el-tag>
                    <el-tag v-else size="small" type="info" effect="light" class="status-tag"></el-tag>
                  </div>
                </el-form-item>
              </el-col>

              <!-- 欠款金额显示 -->
              <el-col :span="6">
                <div class="calc-info">
                  <span class="label">欠款金额:</span>
                  <span class="value warning">{{ formatMoney(calculateOwedAmount(finAccountReceivableStage)) }}元</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>

      <!-- 汇总信息区域 - 只读 -->
      <div class="form-section summary-section">
        <div class="section-header" @click="toggleSection('summary')">
          <span class="section-title">汇总信息</span>
          <el-icon class="section-icon">
            <ArrowDown v-if="!collapsed.summary" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <el-divider />
        <div class="section-content" v-show="!collapsed.summary">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">节点总比例</div>
                <div class="summary-value">{{ totalProportion.toFixed(2) }}%</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">总回款金额</div>
                <div class="summary-value">{{ formatMoney(totalReceived) }}元</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">总欠款合计</div>
                <div class="summary-value warning">{{ formatMoney(totalOwed) }}元</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">已回款比例</div>
                <div class="summary-value">{{ (paymentRate * 100).toFixed(2) }}%</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 账龄信息区域 - 单独的区域 -->
      <div class="form-section aging-section">
        <div class="section-header" @click="toggleSection('aging')">
          <span class="section-title">账龄信息</span>
          <el-icon class="section-icon">
            <ArrowDown v-if="!collapsed.aging" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <el-divider />
        <div class="section-content" v-show="!collapsed.aging">
          <el-table :data="agingData" border stripe style="width: 100%">
            <el-table-column prop="stageName" label="收款节点" min-width="120" />
            <el-table-column prop="paymentAmount" label="应收金额" min-width="120" align="right">
              <template #default="{ row }"> {{ formatMoney(row.paymentAmount) }}元 </template>
            </el-table-column>
            <el-table-column prop="receivedAmount" label="已回款" min-width="120" align="right">
              <template #default="{ row }"> {{ formatMoney(row.receivedAmount) }}元 </template>
            </el-table-column>
            <el-table-column prop="owedAmount" label="欠款金额" min-width="120" align="right">
              <template #default="{ row }">
                <span :class="getOwedAmountClass(row)">{{ formatMoney(row.owedAmount) }}元</span>
              </template>
            </el-table-column>
            <el-table-column prop="baseDate" label="基准日期" min-width="120" align="center">
              <template #default="{ row }">
                {{ row.baseDate ? formatDate(row.baseDate) : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="aging" label="账龄(年)" min-width="100" align="center">
              <template #default="{ row }">
                <span :class="getAgingClass(row.aging)">
                  {{ row.aging }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="agingStatus" label="账龄状态" min-width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getAgingStatusType(row.aging)" size="small" effect="light">
                  {{ getAgingStatus(row.aging) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <!-- 账龄统计信息 -->
          <el-row :gutter="20" class="aging-statistics">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">平均账龄</div>
                <div class="stat-value">{{ averageAging }}年</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">最长账龄</div>
                <div class="stat-value warning">{{ maxAging }}年</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">超1年欠款</div>
                <div class="stat-value warning">{{ formatMoney(overOneYearOwed) }}元</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">超2年欠款</div>
                <div class="stat-value danger">{{ formatMoney(overTwoYearOwed) }}元</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 账龄分析区域 - 简洁卡片式 -->
      <div class="form-section analysis-section">
        <div class="section-header" @click="toggleSection('analysis')">
          <span class="section-title">账龄分析</span>
          <el-icon class="section-icon">
            <ArrowDown v-if="!collapsed.analysis" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <el-divider />
        <div class="section-content" v-show="!collapsed.analysis">
          <!-- 账龄区间卡片 -->
          <el-row :gutter="20">
            <el-col :span="4" v-for="(item, index) in agingRangeData" :key="index">
              <div class="aging-card" :class="getCardClass(item.range)">
                <div class="card-header">{{ item.range }}</div>
                <div class="card-value">{{ formatMoney(item.amount) }}</div>
                <div class="card-unit">元</div>
                <div class="card-percentage">{{ calculatePercentage(item.amount) }}%</div>
              </div>
            </el-col>
          </el-row>

          <!-- 坏账计提卡片 -->
          <el-row :gutter="20" class="bad-debt-row">
            <el-col :span="8" :offset="8">
              <div class="bad-debt-card">
                <div class="card-header">
                  <el-icon><Warning /></el-icon>
                  坏账计提
                </div>
                <div class="card-value danger">{{ formatMoney(badDebtProvision) }}</div>
                <div class="card-unit">元</div>
                <!--                <div class="card-badge">-->
                <!--                  <el-tag type="danger" size="large" effect="dark">建议100%计提</el-tag>-->
                <!--                </div>-->
              </div>
            </el-col>
          </el-row>

          <!-- 账龄分布比例图 -->
          <div class="distribution-bar">
            <div
              v-for="(item, index) in agingRangeData"
              :key="index"
              class="distribution-segment"
              :class="getSegmentClass(item.range)"
              :style="{ width: getSegmentWidth(item.amount) }"
              :title="`${item.range}: ${formatMoney(item.amount)}元 (${calculatePercentage(item.amount)}%)`"
            >
              <span class="segment-label" v-if="getSegmentWidth(item.amount) !== '0%'">{{ item.range }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 备注信息区域 - 可折叠 -->
      <div class="form-section">
        <div class="section-header" @click="toggleSection('remark')">
          <span class="section-title">备注信息</span>
          <el-icon class="section-icon">
            <ArrowDown v-if="!collapsed.remark" />
            <ArrowRight v-else />
          </el-icon>
        </div>
        <el-divider />
        <div class="section-content" v-show="!collapsed.remark">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="回款计划" prop="repaymentPlan">
                <el-date-picker v-model="formData.repaymentPlan" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="原计划" prop="originalPlan">
                <el-date-picker v-model="formData.originalPlan" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>

    <!-- 项目选择弹窗组件 -->
    <ProjectSelectDialog v-model:visible="projectSelectDialogVisible" projectCategory="1" @project-selected="handleProjectSelected" />

    <!-- 合同选择弹窗组件 -->
    <ContractSelectDialog v-model:visible="contractSelectDialogVisible" @contract-selected="handleContractSelected" />
  </div>
</template>

<script setup name="FinAccountReceivableEdit" lang="ts">
import { ref, reactive, computed, onMounted, toRefs, getCurrentInstance, ComponentInternalInstance, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowDown, ArrowRight, Warning } from '@element-plus/icons-vue';
import {
  addFinAccountReceivable,
  getFinAccountReceivable,
  getErpContractPaymentMethodJoinList,
  getErpFinAccountReceivableStageList,
  updateFinAccountReceivable
} from '@/api/oa/erp/finAccountReceivable';
import { FinAccountReceivableStageVO } from '@/api/oa/erp/finAccountReceivableStage/types';

// 项目选择组件
import ProjectSelectDialog from '../../components/ProjectSelectDialog.vue';

// 合同选择组件
import ContractSelectDialog from '../../components/ContractSelectDialog.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

const route = useRoute();
const router = useRouter();
const receivableFormRef = ref(null);
const routeParams = ref<Record<string, any>>({});

// 状态变量
const loading = ref(false);
const stageLoading = ref(false);
const buttonLoading = ref(false);
const title = ref('新增应收款项目');

const CONTRACT_FLAG = {
  YES: '1',
  NO: '2'
};

// 折叠面板状态
const collapsed = ref({
  basic: false,
  contract: false,
  financial: false,
  paymentNodes: false,
  summary: false,
  aging: false,
  analysis: false,
  remark: false
});

// 付款阶段ID常量
const PAYMENT_STAGE_ID = {
  START: 1, // 启动
  ADVANCE_REFUND: 2, // 预付回款
  DELIVERY: 3, // 发货
  COMPLETE: 4, // 完工回款
  INITIAL_INSPECTION: 5, // 初验回款
  FINAL_INSPECTION: 6, // 终验回款
  ACCEPTANCE: 7, // 验收
  WARRANTY: 8 // 质保
};

const isFormDisabled = computed(() => {
  return routeParams.value.type === 'view' || routeParams.value.type === 'approval';
});

const finAccountReceivableStageList = ref<FinAccountReceivableStageVO[]>([]);

// 项目选择弹窗相关
const projectSelectDialogVisible = ref(false);

// 显示项目选择弹窗
const showProjectSelectDialog = () => {
  projectSelectDialogVisible.value = true;
};

// 处理项目选择
const handleProjectSelected = (result: any) => {
  const project = result.project;
  const erpContractInfoList = project.erpContractInfoVoList;
  let totalPrice = project.amount;
  if (erpContractInfoList && erpContractInfoList.length > 1) {
    totalPrice = result.contract?.totalPrice;
  }
  console.log(result.project);
  console.log(result.contract)
  Object.assign(formData.value, {
    contractFlag: project.contractFlag,
    projectId: project.projectId,
    projectName: project.projectName,
    projectCode: project.projectCode,
    deptName: project.deptName,
    managerName: project.managerName,
    projectStatus: project.projectStatus,
    contractId: result.contract?.contractId,
    contractCode: result.contract?.contractCode,
    contractName: result.contract?.contractName,
    contractDate: result.contract?.contractDate,
    externalContractCode: result.contract?.externalContractCode,
    internalContractCode: result.contract?.internalContractCode,
    oneCustomerName: result.contract?.oneCustomerName,
    twoCustomerName: result.contract?.twoCustomerName,
    businessDirection: result.contract?.businessDirection,
    orderContractCode: project.projectCode,
    mesnacOrderNo: result.contract?.orderContractCode,
    mesnacProjectCode: result.contract?.projectContractCode,
    totalPrice: totalPrice,
    totalPriceHighway: totalPrice,
    totalPriceOri: totalPrice
  });
  getErpFinAccountReceivableStages();
};

// 合同选择弹窗相关
const contractSelectDialogVisible = ref(false);

// 显示合同选择弹窗
const showContractSelectDialog = () => {
  contractSelectDialogVisible.value = true;
};

// 处理合同选择
const handleContractSelected = (contract: any) => {
  Object.assign(formData.value, {
    contractId: contract.contractId,
    contractCode: contract.contractCode,
    contractName: contract.contractName,
    contractDate: contract.contractDate,
    externalContractCode: contract.externalContractCode,
    internalContractCode: contract.internalContractCode,
    oneCustomerName: contract.oneCustomerName,
    twoCustomerName: contract.twoCustomerName,
    businessDirection: contract.businessDirection,
    mesnacOrderNo: contract.orderContractCode,
    mesnacProjectCode: contract.projectContractCode,
  });
  getErpFinAccountReceivableStages();
};

/** 新增时查询应收款节点信息列表 */
const getErpFinAccountReceivableStages = async () => {
  if (formData.value.contractId && formData.value.contractId !== '') {
    const res = await getErpContractPaymentMethodJoinList({ contractId: formData.value.contractId });
    finAccountReceivableStageList.value = res.data;
    initializeStageCalculations();
  }
};

/** 编辑时查询应收款节点信息列表 */
const getEditErpFinAccountReceivableStages = async () => {
  const res = await getErpFinAccountReceivableStageList({ accountReceivableId: formData.value.accountReceivableId });
  finAccountReceivableStageList.value = res.data;
  initializeStageCalculations();
};

// 初始化各节点的计算字段
const initializeStageCalculations = () => {
  if (!finAccountReceivableStageList.value) return;

  finAccountReceivableStageList.value.forEach((stage) => {
    // 初始化已回款金额
    if (!stage.receivedAmount) {
      stage.receivedAmount = '0';
    }

    stage.paymentAmount = formData.value.totalPrice*stage.paymentPercentage/100;
    // 根据节点类型初始化相应字段
    switch (stage.paymentStageId) {
      case PAYMENT_STAGE_ID.WARRANTY:
        // 质保节点
        if (!stage.warrantyPeriod) {
          stage.warrantyPeriod = stage.paymentDeadline || '';
        }
        break;
      default:
        // 其他节点
        if (stage.stageRealDate && stage.paymentDeadline) {
          stage.dueDate = calculateDueDate(stage.stageRealDate, stage.paymentDeadline);
        }
        break;
    }
  });

  // 计算质保日期
  updateWarrantyDate();
};

// 计算到期日
const calculateDueDate = (startDate: string | Date, days: string | number) => {
  if (!startDate || !days) return null;

  const date = new Date(startDate);
  date.setDate(date.getDate() + parseInt(days.toString()));
  return date;
};

// 处理日期变化
const handleDateChange = (stage: any) => {
  if (stage.stageRealDate && stage.paymentDeadline) {
    stage.dueDate = calculateDueDate(stage.stageRealDate, stage.paymentDeadline);
  }
  updateWarrantyDate();
};

// 处理已回款金额变化
const handleReceivedAmountChange = (stage: any) => {
  const amount = parseFloat(stage.paymentAmount) || 0;
  const received = parseFloat(stage.receivedAmount) || 0;

  if (received > amount) {
    ElMessage.warning('已回款金额不能大于应收金额');
    stage.receivedAmount = amount.toString();
  }
};

// 处理结算日期变化
const handleSettlementDateChange = (stage: any) => {
  if (stage.paymentStageId === PAYMENT_STAGE_ID.FINAL_INSPECTION || stage.paymentStageId === PAYMENT_STAGE_ID.ACCEPTANCE) {
    updateWarrantyDate();
  }
};

// 处理质保时间变化
const handleWarrantyChange = (stage: any) => {
  updateWarrantyDate();
};

// 更新质保日期
const updateWarrantyDate = () => {
  const warrantyStage = finAccountReceivableStageList.value.find((stage) => stage.paymentStageId === PAYMENT_STAGE_ID.WARRANTY);

  if (!warrantyStage) return;

  // 查找基准日期（优先级：终验 > 验收 > 初验）
  let baseDate = null;
  const finalInspectionStage = finAccountReceivableStageList.value.find((stage) => stage.paymentStageId === PAYMENT_STAGE_ID.FINAL_INSPECTION);
  const acceptanceStage = finAccountReceivableStageList.value.find((stage) => stage.paymentStageId === PAYMENT_STAGE_ID.ACCEPTANCE);
  const initialInspectionStage = finAccountReceivableStageList.value.find((stage) => stage.paymentStageId === PAYMENT_STAGE_ID.INITIAL_INSPECTION);

  if (finalInspectionStage?.settlementDate) {
    baseDate = finalInspectionStage.settlementDate;
  } else if (acceptanceStage?.settlementDate) {
    baseDate = acceptanceStage.settlementDate;
  } else if (initialInspectionStage?.settlementDate) {
    baseDate = initialInspectionStage.settlementDate;
  } else {
    // 如果没有验收相关日期，尝试使用 stageRealDate
    if (finalInspectionStage?.stageRealDate) {
      baseDate = finalInspectionStage.stageRealDate;
    } else if (acceptanceStage?.stageRealDate) {
      baseDate = acceptanceStage.stageRealDate;
    } else if (initialInspectionStage?.stageRealDate) {
      baseDate = initialInspectionStage.stageRealDate;
    }
  }

  if (baseDate && warrantyStage.warrantyPeriod) {
    const date = new Date(baseDate);
    date.setDate(date.getDay() + parseInt(warrantyStage.warrantyPeriod.toString()));
    warrantyStage.warrantyDate = date;
  }
};

// 计算欠款金额
const calculateOwedAmount = (stage: any) => {
  const amount = parseFloat(stage.paymentAmount) || 0;
  const received = parseFloat(stage.receivedAmount) || 0;
  return Math.max(0, amount - received);
};

// 获取节点的基准日期（用于账龄计算）
const getBaseDateForAging = (stage: any) => {
  if (!stage) return null;

  switch (stage.paymentStageId) {
    case PAYMENT_STAGE_ID.START:
    case PAYMENT_STAGE_ID.ADVANCE_REFUND:
    case PAYMENT_STAGE_ID.DELIVERY:
    case PAYMENT_STAGE_ID.COMPLETE:
      return stage.dueDate;
    case PAYMENT_STAGE_ID.INITIAL_INSPECTION:
    case PAYMENT_STAGE_ID.FINAL_INSPECTION:
    case PAYMENT_STAGE_ID.ACCEPTANCE:
      if (stage.dueDate && stage.dueDate !== '') {
        return stage.dueDate;
      } else {
        return stage.settlementDate;
      }
    case PAYMENT_STAGE_ID.WARRANTY:
      return stage.warrantyDate;
    default:
      return null;
  }
};

// 计算单个节点的账龄
const calculateStageAging = (stage: any) => {
  const owedAmount = calculateOwedAmount(stage);
  if (owedAmount <= 0.1) {
    return '-';
  }

  const baseDate = getBaseDateForAging(stage);
  if (!baseDate) {
    return '-';
  }

  const todayDate = new Date();
  const baseDateTime = new Date(baseDate).getTime();
  const todayTime = todayDate.getTime();

  if (todayTime <= baseDateTime) {
    return '0.00';
  }

  const diffDays = (todayTime - baseDateTime) / (1000 * 60 * 60 * 24);
  const agingYears = (diffDays / 365).toFixed(2);

  return agingYears;
};

// 账龄数据 - 用于表格显示
const agingData = computed(() => {
  if (!finAccountReceivableStageList.value) return [];

  return finAccountReceivableStageList.value
    .map((stage) => ({
      stageName: stage.stageName,
      paymentAmount: parseFloat(stage.paymentAmount) || 0,
      receivedAmount: parseFloat(stage.receivedAmount) || 0,
      owedAmount: calculateOwedAmount(stage),
      baseDate: getBaseDateForAging(stage),
      aging: calculateStageAging(stage),
      paymentStageId: stage.paymentStageId
    })); // 只显示有欠款的节点
});

// 平均账龄
const averageAging = computed(() => {
  const validAging = agingData.value.map((item) => parseFloat(item.aging)).filter((aging) => !isNaN(aging) && aging > 0);

  if (validAging.length === 0) return '0.00';

  const sum = validAging.reduce((acc, curr) => acc + curr, 0);
  return (sum / validAging.length).toFixed(2);
});

// 最长账龄
const maxAging = computed(() => {
  const validAging = agingData.value.map((item) => parseFloat(item.aging)).filter((aging) => !isNaN(aging) && aging > 0);

  if (validAging.length === 0) return '0.00';

  return Math.max(...validAging).toFixed(2);
});

// 超1年欠款
const overOneYearOwed = computed(() => {
  return agingData.value
    .filter((item) => {
      const aging = parseFloat(item.aging);
      return !isNaN(aging) && aging >= 1;
    })
    .reduce((sum, item) => sum + item.owedAmount, 0);
});

// 超2年欠款
const overTwoYearOwed = computed(() => {
  return agingData.value
    .filter((item) => {
      const aging = parseFloat(item.aging);
      return !isNaN(aging) && aging >= 2;
    })
    .reduce((sum, item) => sum + item.owedAmount, 0);
});

// 账龄区间数据 - 动态从finAccountReceivableStageList获取
const agingRangeData = computed(() => {
  if (!finAccountReceivableStageList.value) return [];

  // 定义账龄区间
  const ranges = [
    { range: '0-1年', min: 0, max: 1, condition: (aging: number) => aging >= 0 && aging < 1 },
    { range: '1-2年', min: 1, max: 2, condition: (aging: number) => aging >= 1 && aging < 2 },
    { range: '2-3年', min: 2, max: 3, condition: (aging: number) => aging >= 2 && aging < 3 },
    { range: '3-4年', min: 3, max: 4, condition: (aging: number) => aging >= 3 && aging < 4 },
    { range: '4-5年', min: 4, max: 5, condition: (aging: number) => aging >= 4 && aging < 5 },
    { range: '5年以上', min: 5, max: Infinity, condition: (aging: number) => aging >= 5 }
  ];

  // 计算每个区间的总欠款
  return ranges.map((range) => {
    let totalAmount = 0;

    finAccountReceivableStageList.value.forEach((stage) => {
      const owedAmount = calculateOwedAmount(stage);
      if (owedAmount > 0.1) {
        const aging = parseFloat(calculateStageAging(stage));
        if (range.condition(aging)) {
          totalAmount += owedAmount;
        }
      }
    });

    return {
      range: range.range,
      amount: totalAmount
    };
  });
});

// 坏账计提
const badDebtProvision = computed(() => {
  const zeroOneYear = agingRangeData.value.find((item) => item.range === '0-1年');
  const oneTwoYear = agingRangeData.value.find((item) => item.range === '1-2年');
  const twoThreeYear = agingRangeData.value.find((item) => item.range === '2-3年');
  const threeFourYear = agingRangeData.value.find((item) => item.range === '3-4年');
  const fourFiveYear = agingRangeData.value.find((item) => item.range === '4-5年');
  const fiveYearPlus = agingRangeData.value.find((item) => item.range === '5年以上');

  return (
    (zeroOneYear?.amount || 0) * 0.02 +
    (oneTwoYear?.amount || 0) * 0.05 +
    (twoThreeYear?.amount || 0) * 0.1 +
    (threeFourYear?.amount || 0) * 0.5 +
    (fourFiveYear?.amount || 0) * 0.8 +
    (fiveYearPlus?.amount || 0) * 1
  );
});

// 计算百分比
const calculatePercentage = (amount: number) => {
  if (totalOwed.value === 0) return '0.00';
  return ((amount / totalOwed.value) * 100).toFixed(2);
};

// 获取卡片样式类
const getCardClass = (range: string) => {
  const classMap: Record<string, string> = {
    '0-1年': 'card-green',
    '1-2年': 'card-blue',
    '2-3年': 'card-yellow',
    '3-4年': 'card-orange',
    '4-5年': 'card-red',
    '5年以上': 'card-dark-red'
  };
  return classMap[range] || '';
};

// 获取分段样式类
const getSegmentClass = (range: string) => {
  const classMap: Record<string, string> = {
    '0-1年': 'segment-green',
    '1-2年': 'segment-blue',
    '2-3年': 'segment-yellow',
    '3-4年': 'segment-orange',
    '4-5年': 'segment-red',
    '5年以上': 'segment-dark-red'
  };
  return classMap[range] || '';
};

// 获取分段宽度
const getSegmentWidth = (amount: number) => {
  if (totalOwed.value === 0) return '0%';
  const percentage = (amount / totalOwed.value) * 100;
  return `${percentage}%`;
};

// 获取欠款金额样式类
const getOwedAmountClass = (row: any) => {
  if (row.owedAmount > 100000) return 'amount-large';
  if (row.owedAmount > 50000) return 'amount-medium';
  return '';
};

// 获取账龄样式类
const getAgingClass = (aging: string) => {
  if (aging === '-') return '';

  const years = parseFloat(aging);
  if (years >= 2) return 'aging-danger';
  if (years >= 1) return 'aging-warning';
  if (years >= 0.5) return 'aging-notice';
  return '';
};

// 获取账龄状态
const getAgingStatus = (aging: string) => {
  if (aging === '-') return '无欠款';

  const years = parseFloat(aging);
  if (years >= 2) return '严重逾期';
  if (years >= 1) return '逾期';
  if (years >= 0.5) return '关注';
  return '正常';
};

// 获取账龄状态类型
const getAgingStatusType = (aging: string) => {
  if (aging === '-') return 'info';

  const years = parseFloat(aging);
  if (years >= 2) return 'danger';
  if (years >= 1) return 'warning';
  if (years >= 0.5) return 'primary';
  return 'success';
};

// 获取质保状态
const getWarrantyStatus = (warrantyDate: string | Date | null) => {
  if (!warrantyDate) return null;

  const today = new Date();
  const warrantyDateTime = new Date(warrantyDate).getTime();
  const todayTime = today.getTime();

  const diffDays = (warrantyDateTime - todayTime) / (1000 * 60 * 60 * 24);

  if (diffDays < 0) return '已过期';
  if (diffDays <= 30) return '临近过期';
  if (diffDays <= 90) return '即将到期';
  return '有效';
};

// 获取质保状态类型（用于el-tag）
const getWarrantyStatusType = (warrantyDate: string | Date | null) => {
  if (!warrantyDate) return 'info';

  const today = new Date();
  const warrantyDateTime = new Date(warrantyDate).getTime();
  const todayTime = today.getTime();

  const diffDays = (warrantyDateTime - todayTime) / (1000 * 60 * 60 * 24);

  if (diffDays < 0) return 'danger';
  if (diffDays <= 30) return 'warning';
  if (diffDays <= 90) return 'primary';
  return 'success';
};

// 获取质保状态样式类
const getWarrantyStatusClass = (warrantyDate: string | Date | null) => {
  const status = getWarrantyStatus(warrantyDate);
  switch (status) {
    case '已过期':
      return 'status-expired';
    case '临近过期':
      return 'status-approaching';
    case '即将到期':
      return 'status-upcoming';
    case '有效':
      return 'status-valid';
    default:
      return '';
  }
};

// 日期格式化函数
const formatDate = (date: string | Date | null) => {
  if (!date) return '';

  const d = new Date(date);
  if (isNaN(d.getTime())) return '';

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
};

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

// Stage配置映射
const STAGE_CONFIG = {
  [PAYMENT_STAGE_ID.DELIVERY]: {
    showDeadline: true,
    deadlineLabel: '账期',
    deadlinePlaceholder: '账期',
    deadlineUnit: '天',
    showStageRealDate: true,
    stageRealDateLabel: '实际发货日期',
    stageRealDatePlaceholder: '选择实际发货日期'
  },
  [PAYMENT_STAGE_ID.START]: {
    showDeadline: true,
    deadlineLabel: '账期',
    deadlinePlaceholder: '账期',
    deadlineUnit: '天',
    showStageRealDate: true,
    stageRealDateLabel: '启动日期',
    stageRealDatePlaceholder: '选择启动日期'
  },
  [PAYMENT_STAGE_ID.ADVANCE_REFUND]: {
    showDeadline: true,
    deadlineLabel: '账期',
    deadlinePlaceholder: '账期',
    deadlineUnit: '天',
    showStageRealDate: true,
    stageRealDateLabel: '预付回款日期',
    stageRealDatePlaceholder: '选择预付回款日期'
  },
  [PAYMENT_STAGE_ID.COMPLETE]: {
    showDeadline: true,
    deadlineLabel: '账期',
    deadlinePlaceholder: '账期',
    deadlineUnit: '天',
    showStageRealDate: true,
    stageRealDateLabel: '完工日期',
    stageRealDatePlaceholder: '选择完工日期'
  },
  [PAYMENT_STAGE_ID.INITIAL_INSPECTION]: {
    showDeadline: true,
    deadlineLabel: '账期',
    deadlinePlaceholder: '账期',
    deadlineUnit: '天',
    showStageRealDate: true,
    stageRealDateLabel: '初验单取得日期',
    stageRealDatePlaceholder: '选择初验日期',
    isSettlementStage: true
  },
  [PAYMENT_STAGE_ID.FINAL_INSPECTION]: {
    showDeadline: true,
    deadlineLabel: '账期',
    deadlinePlaceholder: '账期',
    deadlineUnit: '天',
    showStageRealDate: true,
    stageRealDateLabel: '终验单取得日期',
    stageRealDatePlaceholder: '选择终验日期',
    isSettlementStage: true
  },
  [PAYMENT_STAGE_ID.ACCEPTANCE]: {
    showDeadline: true,
    deadlineLabel: '账期',
    deadlinePlaceholder: '账期',
    deadlineUnit: '天',
    showStageRealDate: true,
    stageRealDateLabel: '验收单取得日期',
    stageRealDatePlaceholder: '选择验收日期',
    isSettlementStage: true
  },
  [PAYMENT_STAGE_ID.WARRANTY]: {
    showDeadline: true,
    deadlineLabel: '质保条款',
    deadlinePlaceholder: '质保条款',
    deadlineUnit: '月',
    showStageRealDate: false
  }
};

// 获取stage配置
const getStageConfig = (stageId) => {
  return (
    STAGE_CONFIG[stageId] || {
      showDeadline: true,
      deadlineLabel: '账期',
      deadlineUnit: '天',
      showStageRealDate: false
    }
  );
};

// 表单数据
const formData = ref<any>({
  id: undefined,
  accountReceivableId: undefined,
  invoiceCode: '',
  projectCode: '',
  projectCategory: '',
  projectType: '',
  contractDate: '',
  externalContractCode: '',
  internalContractCode: '',
  generalContractor: '',
  customerAbbreviation: '',
  contractParties: '',
  oneCustomerName: '',
  twoCustomerName: '',
  businessDirection: '',
  deptName: '',
  managerName: '',
  mesnacOrderNo: '',
  mesnacProjectCode: '',
  orderContractCode: '',
  projectStatus: '',
  totalPrice: '',
  totalPriceHighway: '',
  totalPriceOri: '',
  currency: 'CNY',
  exchangeRate: 1,
  paymentMethod: '',
  repaymentPlan: '',
  originalPlan: '',
  remark: '',
  backToBackRatio: '',
  invoiceAmount: '',
  income: '',
  wbsElement: '',
  lineItem: '',
  finProjectStatus: '',
  settlementMonth: ''
});

// 表单验证规则
const formRules = {
  projectCode: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }]
};

// 汇总计算
const totalProportion = computed(() => {
  if (!finAccountReceivableStageList.value) return 0;

  return finAccountReceivableStageList.value.reduce((sum, stage) => {
    return sum + (parseFloat(stage.paymentPercentage) || 0);
  }, 0);
});

const totalReceived = computed(() => {
  if (!finAccountReceivableStageList.value) return 0;

  return finAccountReceivableStageList.value.reduce((sum, stage) => {
    return sum + (parseFloat(stage.receivedAmount) || 0);
  }, 0);
});

const totalOwed = computed(() => {
  if (!finAccountReceivableStageList.value) return 0;

  return finAccountReceivableStageList.value.reduce((sum, stage) => {
    return sum + calculateOwedAmount(stage);
  }, 0);
});

const totalReceivable = computed(() => {
  const totalAmount = parseFloat(formData.value.totalPrice) || 0;
  return Math.max(0, totalAmount - totalReceived.value);
});

const paymentRate = computed(() => {
  const totalAmount = parseFloat(formData.value.totalPrice) || 0;
  return totalAmount > 0 ? totalReceived.value / totalAmount : 0;
});

const paymentDescription = computed(() => {
  return finAccountReceivableStageList.value.map((item) => `${item.paymentDescription}。`).join('\n'); // 使用换行符连接
});

// 方法
const toggleSection = (section: string) => {
  collapsed.value[section as keyof typeof collapsed.value] = !collapsed.value[section as keyof typeof collapsed.value];
};

const goBack = () => {
  const obj = {
    path: '/fin/finAccountReceivable',
    query: {
      t: Date.now(),
      pageNum: routeParams.value.pageNum
    }
  };
  proxy?.$tab.closeOpenPage(obj);
};

const resetForm = () => {
  if (formData.value.accountReceivableId) {
    // 如果是修改，重新加载原数据
    loadData(formData.value.accountReceivableId);
  } else {
    // 如果是新增，清空表单
    formData.value = {
      id: undefined,
      accountReceivableId: undefined,
      invoiceCode: '',
      projectCode: '',
      projectCategory: '',
      projectType: '',
      contractDate: '',
      externalContractCode: '',
      internalContractCode: '',
      generalContractor: '',
      customerAbbreviation: '',
      contractParties: '',
      oneCustomerName: '',
      twoCustomerName: '',
      businessDirection: '',
      deptName: '',
      managerName: '',
      mesnacOrderNo: '',
      mesnacProjectCode: '',
      orderContractCode: '',
      projectStatus: '',
      totalPrice: '',
      totalPriceHighway: '',
      totalPriceOri: '',
      currency: 'CNY',
      exchangeRate: 1,
      paymentMethod: '',
      repaymentPlan: '',
      originalPlan: '',
      remark: '',
      backToBackRatio: '',
      invoiceAmount: '',
      income: '',
      wbsElement: '',
      lineItem: '',
      finProjectStatus: '',
      settlementMonth: ''
    };
    finAccountReceivableStageList.value = [];
  }
};

const loadData = async (accountReceivableId: string) => {
  loading.value = true;
  stageLoading.value = true;
  try {
    const res = await getFinAccountReceivable(accountReceivableId);
    console.log(res.data);
    const erpProjectInfo = res.data.erpProjectInfoVo;
    const erpContractInfo = res.data.erpContractInfoVo;
    console.log("--")
    Object.assign(formData.value, res.data, erpProjectInfo,erpContractInfo);
    Object.assign(formData.value, {
      projectCategory: res.data.projectCategory,
      oneCustomerName: res.data.oneCustomerName,
      twoCustomerName: res.data.twoCustomerName,
      managerName: res.data.managerName,
      remark: res.data.remark,
    });

    await getEditErpFinAccountReceivableStages();
  } finally {
    loading.value = false;
    stageLoading.value = false;
  }
};

const handleCalculate = () => {
  ElMessage.success(`计算完成：总欠款 ${formatMoney(totalOwed.value)} 元，回款比例 ${(paymentRate.value * 100).toFixed(2)}%`);
};

const submitForm = () => {
  receivableFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        const finAccountReceivableForm = {
          ...formData.value,
          finAccountReceivableStageList: finAccountReceivableStageList.value
        };

        console.log(finAccountReceivableForm);
        if (formData.value.accountReceivableId) {
          await updateFinAccountReceivable(finAccountReceivableForm);
        } else {
          await addFinAccountReceivable(finAccountReceivableForm);
        }
        proxy?.$modal.msgSuccess('操作成功');
        goBack();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

// 监听节点数据变化，自动更新账龄
watch(
  finAccountReceivableStageList,
  () => {
    // 账龄数据会自动通过computed更新
  },
  { deep: true }
);

// 初始化
onMounted(() => {
  routeParams.value = route.query;
  const accountReceivableId = route.query.accountReceivableId as string;
  if (accountReceivableId) {
    title.value = '修改应收款项目';
    loadData(accountReceivableId);
  }
});
</script>

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

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

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.header-right {
  display: flex;
  gap: 10px;
}

.receivable-form {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表单折叠区域样式 */
.form-section {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px 15px;
  background-color: white;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: 5px 0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.section-icon {
  font-size: 18px;
  color: #909399;
}

.el-divider {
  margin: 10px 0;
}

.section-content {
  padding: 10px 0;
}

/* 收款节点子区域样式 */
.node-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
  transition: all 0.3s;
}

.node-section:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.node-title {
  font-size: 15px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px dashed #dcdfe6;
}

/* 计算信息样式 */
.calc-info {
  height: 32px;
  line-height: 32px;
  padding: 0 10px;
  background-color: #f0f2f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.calc-info .label {
  color: #606266;
  font-size: 12px;
}

.calc-info .value {
  font-weight: bold;
  font-size: 14px;
}

.calc-info .value.warning {
  color: #e6a23c;
}

/* 汇总信息样式 */
.summary-section {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.summary-section .section-title {
  color: #67c23a;
}

.summary-item {
  padding: 15px;
  background: white;
  border-radius: 4px;
  text-align: center;
  border: 1px solid #ebeef5;
}

.summary-label {
  color: #909399;
  margin-bottom: 8px;
  font-size: 14px;
}

.summary-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.summary-value.warning {
  color: #e6a23c;
}

/* 账龄信息样式 */
.aging-section {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.aging-section .section-title {
  color: #409eff;
}

.aging-statistics {
  margin-top: 20px;
}

.stat-item {
  padding: 15px;
  background: white;
  border-radius: 4px;
  text-align: center;
  border: 1px solid #ebeef5;
}

.stat-label {
  color: #909399;
  margin-bottom: 8px;
  font-size: 14px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.stat-value.warning {
  color: #e6a23c;
}

.stat-value.danger {
  color: #f56c6c;
}

/* 账龄分析样式 */
.analysis-section {
  background-color: #f9f0ff;
  border-color: #722ed1;
}

.analysis-section .section-title {
  color: #722ed1;
}

/* 账龄卡片 */
.aging-card {
  background: white;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.aging-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-green {
  border-top: 4px solid #67c23a;
}
.card-blue {
  border-top: 4px solid #409eff;
}
.card-yellow {
  border-top: 4px solid #e6a23c;
}
.card-orange {
  border-top: 4px solid #fa8c16;
}
.card-red {
  border-top: 4px solid #f56c6c;
}
.card-dark-red {
  border-top: 4px solid #cf1322;
}

.card-header {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1.4;
}

.card-value.danger {
  color: #cf1322;
}

.card-unit {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.card-percentage {
  font-size: 16px;
  color: #67c23a;
  font-weight: 500;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #ebeef5;
}

/* 坏账卡片 */
.bad-debt-row {
  margin-top: 20px;
  margin-bottom: 20px;
}

.bad-debt-card {
  background: linear-gradient(135deg, #fff2f0 0%, #fff 100%);
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  border: 1px solid #ffa39e;
  box-shadow: 0 2px 8px rgba(207, 19, 34, 0.1);
}

.bad-debt-card .card-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 16px;
  color: #cf1322;
  margin-bottom: 15px;
}

.bad-debt-card .card-value {
  font-size: 32px;
  color: #cf1322;
  margin-bottom: 5px;
}

.bad-debt-card .card-badge {
  margin-top: 15px;
}

/* 分布条 */
.distribution-bar {
  display: flex;
  height: 40px;
  width: 100%;
  border-radius: 20px;
  overflow: hidden;
  margin-top: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.distribution-segment {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  position: relative;
}

.distribution-segment:hover {
  opacity: 0.9;
  transform: scaleY(1.1);
}

.segment-label {
  color: white;
  font-size: 12px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  white-space: nowrap;
  padding: 0 4px;
}

.segment-green {
  background: linear-gradient(135deg, #67c23a, #95d475);
}
.segment-blue {
  background: linear-gradient(135deg, #409eff, #79bbff);
}
.segment-yellow {
  background: linear-gradient(135deg, #e6a23c, #f3d19e);
}
.segment-orange {
  background: linear-gradient(135deg, #fa8c16, #ffc069);
}
.segment-red {
  background: linear-gradient(135deg, #f56c6c, #fab6b6);
}
.segment-dark-red {
  background: linear-gradient(135deg, #cf1322, #ff7875);
}

/* 表格样式 */
.el-table {
  margin-top: 10px;
}

.el-table .amount-large {
  color: #f56c6c;
  font-weight: bold;
}

.el-table .amount-medium {
  color: #e6a23c;
  font-weight: bold;
}

/* 账龄样式 */
.aging-notice {
  color: #e6a23c;
  font-weight: 500;
}

.aging-warning {
  color: #f56c6c;
  font-weight: bold;
}

.aging-danger {
  color: #ff4d4f;
  font-weight: bold;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}

/* 日期状态样式 */
.date-with-status {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.date-display {
  height: 32px;
  line-height: 32px;
  padding: 0 11px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
}

.status-tag {
  font-size: 12px;
}

.status-expired {
  color: #f56c6c;
  text-decoration: line-through;
}

.status-approaching {
  color: #e6a23c;
  font-weight: bold;
}

.status-upcoming {
  color: #409eff;
}

.status-valid {
  color: #67c23a;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 18px;
}

.el-form-item__label {
  font-size: 13px;
}

.el-input__inner[readonly] {
  background-color: #f5f7fa;
  color: #606266;
  cursor: pointer;
}

.el-input__inner[readonly]:hover {
  background-color: #ecf5ff;
}
</style>
