<template>
  <div class="order-ledger-container">
    <el-card shadow="never" class="main-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">销售合同订单台账</span>
          <el-button size="default" type="primary" icon="ArrowLeft" @click="handleBack">返回</el-button>
        </div>
      </template>
      <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="custom-tabs">
        <!-- 合同信息 Tab -->
        <el-tab-pane label="合同信息" name="contract">
          <div v-loading="loadingContract" class="tab-content">
            <div v-if="contractInfo" class="contract-info-pane">
              <div class="contract-desc-section">
                <div class="contract-desc-section__title">基础信息</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="合同编号">
                    <span class="value-text value-highlight">{{ contractInfo.contractCode || '-' }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="合同名称" :span="2">
                    <span class="value-text value-highlight">{{ contractInfo.contractName || '-' }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="合同负责人">{{ contractInfo.contractManagerName || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="合同签订日期">
                    {{ contractInfo.contractDate ? parseTime(contractInfo.contractDate, '{y}-{m}-{d}') : '-' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="签订地点">{{ contractInfo.signingPlace || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="甲方办公地">{{ contractInfo.detailedAddress || '-' }}</el-descriptions-item>
                </el-descriptions>
              </div>

              <div class="contract-desc-section">
                <div class="contract-desc-section__title">编号与外部系统</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="海威SAP订单号">{{ contractInfo.internalContractCode || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="海威合同归档编号">{{ contractInfo.externalContractCode || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="软控SAP订单号">{{ contractInfo.orderContractCode || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="软控SAP项目号">{{ contractInfo.projectContractCode || '-' }}</el-descriptions-item>
                </el-descriptions>
              </div>

              <div class="contract-desc-section">
                <div class="contract-desc-section__title">分类与合同状态</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="业务方向">
                    <dict-tag :options="business_direction" :value="contractInfo.businessDirection" />
                  </el-descriptions-item>
                  <el-descriptions-item label="合同大类">
                    <dict-tag :options="contract_category" :value="contractInfo.contractCategory" />
                  </el-descriptions-item>
                  <el-descriptions-item label="合同模板标识">
                    <dict-tag :options="contract_template_flag" :value="contractInfo.contractTemplateFlag" />
                  </el-descriptions-item>
                  <el-descriptions-item label="合同状态">
                    <dict-tag :options="contract_status" :value="contractInfo.contractStatus" />
                  </el-descriptions-item>
                  <el-descriptions-item label="已生效客户订单">
                    <span>{{
                      contractInfo.effectiveCustomerOrderFlag === '1' ? '是' : contractInfo.effectiveCustomerOrderFlag === '0' ? '否' : '-'
                    }}</span>
                  </el-descriptions-item>
                </el-descriptions>
              </div>

              <div class="contract-desc-section">
                <div class="contract-desc-section__title">本订单执行状态</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="采购状态">
                    <dict-tag :options="order_purchase_status" :value="orderInfo?.orderPurchaseStatus" />
                  </el-descriptions-item>
                  <el-descriptions-item label="发货状态">
                    <dict-tag :options="order_delivery_status" :value="orderInfo?.orderDeliveryStatus" />
                  </el-descriptions-item>
                  <el-descriptions-item label="开票状态">
                    <dict-tag :options="order_invoice_status" :value="orderInfo?.orderInvoiceStatus" />
                  </el-descriptions-item>
                  <el-descriptions-item label="回款百分比">
                    <span>{{ orderInfo?.orderPaymentRate ?? 0 }}%</span>
                  </el-descriptions-item>
                </el-descriptions>
              </div>

              <div class="contract-desc-section">
                <div class="contract-desc-section__title">属地与结算</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="合同属地标识">
                    <dict-tag :options="contract_territorial_flag" :value="contractInfo.contractTerritorialFlag" />
                  </el-descriptions-item>
                  <el-descriptions-item label="合同属地国家/地区">
                    <dict-tag :options="country_region" :value="contractInfo.contractTerritorialCountry" />
                  </el-descriptions-item>
                  <el-descriptions-item label="结算币种">
                    <dict-tag :options="currency_type" :value="contractInfo.settlementCurrency" />
                  </el-descriptions-item>
                  <el-descriptions-item label="对人民币汇率">{{ formatExchangeRate(contractInfo.rmbExchangeRate) }}</el-descriptions-item>
                </el-descriptions>
              </div>

              <div class="contract-desc-section">
                <div class="contract-desc-section__title">签约主体</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="最终客户">{{ contractInfo.finalCustomerName || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="甲方公司">{{ contractInfo.oneCustomerName || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="甲方授权代表">{{ contractInfo.oneRepresent || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="甲方签字日期">
                    {{ contractInfo.oneDate ? parseTime(contractInfo.oneDate, '{y}-{m}-{d}') : '-' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="乙方公司">{{ contractInfo.twoCustomerName || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="乙方授权代表">{{ contractInfo.twoRepresent || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="乙方签字日期">
                    {{ contractInfo.twoDate ? parseTime(contractInfo.twoDate, '{y}-{m}-{d}') : '-' }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>

              <div class="contract-desc-section">
                <div class="contract-desc-section__title">商务与交付</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="付款方式" :span="3">{{ contractInfo.paymentMethod || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="付款账户信息" :span="3">{{ contractInfo.paymentAccountInfo || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="交货地点">{{ contractInfo.deliveryLocation || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="运输方式">{{ contractInfo.shipMethod || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="发货/交货期">{{ contractInfo.deliveryStart || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="质保期描述" :span="3">{{ contractInfo.warrantyPeriodDescription || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="合同大写金额" :span="3">{{ contractInfo.capitalizedAmount || '-' }}</el-descriptions-item>
                </el-descriptions>
              </div>

              <div v-if="contractInfo.isFrameworkContract === '1'" class="contract-desc-section">
                <div class="contract-desc-section__title">框架合同</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="关联框架合同编号">{{ contractInfo.frameworkContractCode || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="关联框架合同名称" :span="2">{{ contractInfo.frameworkContractName || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="框架合同有效期" :span="3">
                    {{ contractInfo.frameworkValidPeriod ? parseTime(contractInfo.frameworkValidPeriod, '{y}-{m}-{d}') : '-' }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>

              <div class="contract-desc-section">
                <div class="contract-desc-section__title">其他</div>
                <el-descriptions :column="3" border class="order-descriptions">
                  <el-descriptions-item label="备注" :span="3">{{ contractInfo.remark || '-' }}</el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
            <el-empty v-else description="暂无合同信息" class="empty-state" />
          </div>
        </el-tab-pane>

        <!-- 采购信息 Tab -->
        <el-tab-pane label="采购信息" name="purchase">
          <div v-loading="loadingPurchase" class="tab-content">
            <div class="section-header">
              <div class="header-left">
                <i class="el-icon-shopping-cart-full section-icon"></i>
                <span class="section-title">项目采购信息</span>
                <el-tag v-if="purchaseTotal > 0" type="info" size="small" class="count-tag"> {{ purchaseTotal }} 条 </el-tag>
              </div>
              <div class="header-actions">
                <el-button size="default" type="primary" icon="Plus" @click="addPurchaseFromLedger">新增采购</el-button>
                <el-button size="default" type="primary" plain icon="Link" @click="openPurchasePage">前往采购页面</el-button>
                <el-button size="default" icon="Refresh" @click="loadPurchaseList">刷新</el-button>
              </div>
            </div>

            <el-table :data="purchaseList" size="default" border stripe v-loading="loadingPurchase" class="data-table">
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column label="采购编号" prop="purchaseCode" width="160" show-overflow-tooltip />
              <el-table-column label="项目号" prop="projectCode" width="150" show-overflow-tooltip />
              <el-table-column label="项目名称" prop="projectName" min-width="180" show-overflow-tooltip />
              <el-table-column label="项目经理" prop="managerName" width="120" />
              <el-table-column label="收货人" prop="consigneeUser" width="120" />
              <el-table-column label="收货地址" prop="consigneeAddress" min-width="180" show-overflow-tooltip />
              <el-table-column label="收货人联系方式" prop="consigneeContact" width="150" />
              <el-table-column label="项目采购状态" prop="projectPurchaseStatus" width="130" align="center">
                <template #default="scope">
                  <dict-tag :options="project_purchase_status" :value="scope.row.projectPurchaseStatus" />
                </template>
              </el-table-column>
              <el-table-column label="流程状态" prop="flowStatus" width="120" align="center">
                <template #default="scope">
                  <dict-tag :options="wf_business_status" :value="scope.row.flowStatus" />
                </template>
              </el-table-column>
              <el-table-column label="是否备件类" prop="spareFlag" width="110" align="center">
                <template #default="scope">
                  <dict-tag :options="spare_flag" :value="scope.row.spareFlag" />
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
              <el-table-column label="操作" width="100" align="center" fixed="right">
                <template #default="scope">
                  <el-button size="default" type="primary" text @click="viewPurchase(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-empty v-if="!loadingPurchase && purchaseList.length === 0" description="暂无采购信息" class="empty-state" />

            <pagination
              v-show="purchaseTotal > 0"
              :total="purchaseTotal"
              v-model:page="purchaseQuery.pageNum"
              v-model:limit="purchaseQuery.pageSize"
              @pagination="loadPurchaseList"
              class="pagination-wrapper"
            />

            <div class="purchase-material-section">
              <div class="section-header">
                <div class="header-left">
                  <i class="el-icon-tickets section-icon"></i>
                  <span class="section-title">采购物料清单</span>
                  <el-tag v-if="purchaseMaterialList.length > 0" type="info" size="small" class="count-tag">
                    {{ purchaseMaterialList.length }} 条
                  </el-tag>
                </div>
              </div>

              <el-table
                :data="purchaseMaterialList"
                size="default"
                border
                stripe
                v-loading="loadingPurchase"
                class="data-table purchase-material-table"
                :row-class-name="getPurchaseMaterialRowClass"
              >
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column label="物料编号" prop="materialCode" width="160" show-overflow-tooltip />
                <el-table-column label="物料名称" prop="materialName" min-width="180" show-overflow-tooltip />
                <el-table-column label="销售物料名称" prop="saleMaterialName" min-width="160" show-overflow-tooltip />
                <el-table-column label="规格描述" prop="specificationDescription" min-width="180" show-overflow-tooltip />
                <el-table-column label="单位" prop="unitName" width="100" align="center" />
                <el-table-column label="合同数量" prop="contractAmount" width="120" align="right">
                  <template #default="scope">
                    {{ formatAmount(scope.row.contractAmount) }}
                  </template>
                </el-table-column>
                <el-table-column label="已采购数量" prop="purchasedAmount" width="120" align="right">
                  <template #default="scope">
                    {{ formatAmount(scope.row.purchasedAmount) }}
                  </template>
                </el-table-column>
                <el-table-column label="未采购数量" prop="unpurchasedAmount" width="120" align="right">
                  <template #default="scope">
                    {{ formatAmount(scope.row.unpurchasedAmount) }}
                  </template>
                </el-table-column>
              </el-table>

              <el-empty v-if="!loadingPurchase && purchaseMaterialList.length === 0" description="暂无合同物料信息" class="empty-state" />
            </div>
          </div>
        </el-tab-pane>

        <!-- 发货信息 Tab -->
        <el-tab-pane label="发货信息" name="shipping">
          <div v-loading="loadingShipping" class="tab-content">
            <div class="section-header">
              <div class="header-left">
                <i class="el-icon-truck section-icon"></i>
                <span class="section-title">发货信息</span>
                <el-tag v-if="shippingTotal > 0" type="info" size="small" class="count-tag"> {{ shippingTotal }} 条 </el-tag>
              </div>
              <div class="header-actions">
                <el-button size="default" type="primary" icon="Plus" @click="addShippingFromLedger">新增发货</el-button>
                <el-button size="default" type="primary" plain icon="Link" @click="openShippingPage">前往发货页面</el-button>
                <el-button size="default" icon="Refresh" @click="loadShippingList">刷新</el-button>
              </div>
            </div>
            <el-table :data="shippingList" border stripe size="default" class="data-table">
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column label="发货单号" prop="shippingCode" width="150" align="center" />
              <el-table-column label="发货方式" prop="shippingMode" width="120" align="center">
                <template #default="scope">
                  <dict-tag :options="shipping_mode" :value="scope.row.shippingMode" />
                </template>
              </el-table-column>
              <el-table-column label="客户名称" prop="customerName" width="180" align="center" show-overflow-tooltip />
              <el-table-column label="收货地址" prop="shippingAddress" width="200" align="center" show-overflow-tooltip />
              <el-table-column label="收货联系人" prop="receiverName" width="100" align="center" />
              <el-table-column label="收货电话" prop="receiverPhone" width="130" align="center" />
              <!--              <el-table-column label="物流公司" prop="logisticsCompany" width="130" align="center" />-->
              <!--              <el-table-column label="运单号" prop="trackingNo" width="150" align="center" />-->
              <el-table-column label="计划到货时间" prop="planArrivalTime" width="120" align="center">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.planArrivalTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="实际发货时间" prop="shippingTime" width="120" align="center">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.shippingTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="发货说明" prop="directions" min-width="200" align="center" show-overflow-tooltip />
              <el-table-column label="操作" align="center" fixed="right" width="100">
                <template #default="scope">
                  <el-tooltip content="查看发货单明细" placement="top">
                    <el-button link type="primary" icon="View" @click="handleViewShipping(scope.row)">明细</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-if="!loadingShipping && shippingList.length === 0" description="暂无发货信息" class="empty-state" />
            <pagination
              v-show="shippingTotal > 0"
              :total="shippingTotal"
              v-model:page="shippingQuery.pageNum"
              v-model:limit="shippingQuery.pageSize"
              @pagination="loadShippingList"
              class="pagination-wrapper"
            />
          </div>
        </el-tab-pane>

        <!-- 回款信息 Tab：创建人、合同负责人、角色 CVP、超级管理员可见 -->
        <el-tab-pane v-if="canViewPaymentLedger" label="回款信息" name="payment">
          <div v-loading="loadingPayment" class="tab-content">
            <div class="section-header">
              <div class="header-left">
                <i class="el-icon-coin section-icon"></i>
                <span class="section-title">回款信息</span>
                <el-tag v-if="planStageList.length > 0" type="info" size="small" class="count-tag"> {{ planStageList.length }} 条 </el-tag>
              </div>
              <div class="header-actions payment-header-actions">
                <div v-if="contractInfo" class="payment-contract-total-inline">
                  <span class="payment-contract-total-inline__label">合同总价</span>
                  <span class="value-text value-amount">
                    {{ contractInfo.totalPrice != null ? formatNumber(contractInfo.totalPrice) + ' 元' : '-' }}
                  </span>
                </div>
                <el-button size="default" icon="Refresh" @click="loadPlanStageList">刷新</el-button>
              </div>
            </div>
            <el-table
              :data="planStageList"
              border
              stripe
              size="default"
              class="data-table"
              :header-cell-style="{ textAlign: 'center' }"
              :cell-style="{ textAlign: 'center' }"
            >
              <el-table-column label="序号" type="index" width="60" align="center" />
              <el-table-column label="回款阶段" min-width="160" align="center" show-overflow-tooltip>
                <template #default="scope">
                  {{ scope.row.paymentStageName || getPaymentStageName(scope.row.paymentStageId) }}
                </template>
              </el-table-column>
              <el-table-column label="合同阶段比例(%)" width="140" align="center">
                <template #default="scope">
                  {{ formatStagePercent(scope.row.repaymentRate) }}
                </template>
              </el-table-column>
              <el-table-column label="合同阶段金额(元)" width="150" align="center">
                <template #default="scope">
                  {{ scope.row.repaymentAmount != null ? formatNumber(scope.row.repaymentAmount) : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="实际回款金额(元)" width="150" align="center">
                <template #default="scope">
                  {{ scope.row.actualRepaymentAmount != null ? formatNumber(scope.row.actualRepaymentAmount) : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="实际回款比例(%)" width="140" align="center">
                <template #default="scope">
                  {{ displayPlanStageActualRepaymentRate(scope.row) }}
                </template>
              </el-table-column>
              <el-table-column label="确认状态" width="120" align="center">
                <template #default="scope">
                  <dict-tag :options="collection_confirm_status" :value="scope.row.collectionConfirmStatus || '0'" />
                </template>
              </el-table-column>
              <el-table-column label="确认日期" width="120" align="center">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.collectionConfirmTime, '{y}-{m}-{d}') || '-' }}</span>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-if="!loadingPayment && planStageList.length === 0" description="暂无回款信息" class="empty-state" />
          </div>
        </el-tab-pane>

        <!-- 开票信息 Tab -->
        <el-tab-pane label="开票信息" name="invoice">
          <div class="tab-content">
            <div v-loading="loadingInvoice" class="tab-content">
              <div class="section-header">
                <div class="header-left">
                  <i class="el-icon-document section-icon"></i>
                  <span class="section-title">开票信息</span>
                  <el-tag v-if="invoiceTotal > 0" type="info" size="small" class="count-tag"> {{ invoiceTotal }} 条 </el-tag>
                </div>
                <div class="header-actions">
                  <el-button size="default" type="primary" icon="Plus" @click="addInvoiceFromLedger">新增开票</el-button>
                  <el-button size="default" icon="Refresh" @click="loadInvoiceList">刷新</el-button>
                </div>
              </div>

              <el-table :data="invoiceList" size="default" border stripe v-loading="loadingInvoice" class="data-table">
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column label="开票申请编号" prop="invoiceCode" width="200" show-overflow-tooltip />
                <el-table-column label="项目号" prop="projectCode" width="150" show-overflow-tooltip />
                <el-table-column label="项目名称" prop="projectName" min-width="180" show-overflow-tooltip />
                <el-table-column label="项目类型" prop="invoiceCategory" width="120" align="center">
                  <template #default="scope">
                    <dict-tag :options="invoice_category" :value="scope.row.invoiceCategory" />
                  </template>
                </el-table-column>
                <el-table-column label="提前开票标识" prop="earlyFlag" width="140" align="center">
                  <template #default="scope">
                    <dict-tag :options="early_flag" :value="scope.row.earlyFlag" />
                  </template>
                </el-table-column>
                <el-table-column label="发票类型" prop="invoiceType" width="120" align="center" />
                <el-table-column label="本次开具金额" prop="issueAmount" width="140" align="right">
                  <template #default="scope">
                    {{ scope.row.issueAmount != null ? formatNumber(scope.row.issueAmount) + ' 元' : '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="验收日期" prop="acceptanceDate" width="150" align="center">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.acceptanceDate, '{y}-{m}-{d}') || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="开票状态" prop="invoiceStatus" width="130" align="center">
                  <template #default="scope">
                    <dict-tag :options="invoice_status" :value="scope.row.invoiceStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="流程状态" prop="flowStatus" width="130" align="center">
                  <template #default="scope">
                    <dict-tag :options="wf_business_status" :value="scope.row.flowStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark" min-width="160" show-overflow-tooltip />
                <el-table-column label="操作" width="100" align="center" fixed="right">
                  <template #default="scope">
                    <el-button size="default" type="primary" text @click="viewInvoice(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <el-empty v-if="!loadingInvoice && invoiceList.length === 0" description="暂无开票信息" class="empty-state" />

              <pagination
                v-show="invoiceTotal > 0"
                :total="invoiceTotal"
                v-model:page="invoiceQuery.pageNum"
                v-model:limit="invoiceQuery.pageSize"
                @pagination="loadInvoiceList"
                class="pagination-wrapper"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="OrderLedger">
import { computed, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getContractOrder, getContractOrderPurchaseMaterialList } from '@/api/oa/erp/contractOrder';
import { ContractOrderPurchaseMaterialVO } from '@/api/oa/erp/contractOrder/types';
import { getContractInfo } from '@/api/oa/erp/contractInfo';
import { ContractInfoVO } from '@/api/oa/erp/contractInfo/types';
import { ProjectInfoVO } from '@/api/oa/erp/projectInfo/types';
import { listProjectInfoByContractId } from '@/api/oa/erp/projectInfo';
import { listProjectPurchase } from '@/api/oa/erp/projectPurchase';
import { ProjectPurchaseVO } from '@/api/oa/erp/projectPurchase/types';
import { listFinInvoiceInfo } from '@/api/oa/erp/finInvoiceInfo';
import { FinInvoiceInfoVO } from '@/api/oa/erp/finInvoiceInfo/types';
import { listWmsShippingBill } from '@/api/wms/wmsShippingBill';
import { WmsShippingBillVO } from '@/api/wms/wmsShippingBill/types';
import { getErpProjectPlanStageList } from '@/api/oa/erp/erpProjectPlanStage';
import { ErpProjectPlanStageForm } from '@/api/oa/erp/erpProjectPlanStage/types';
import { getBasePaymentStageList } from '@/api/oa/base/paymentStage';
import { PaymentStageVO } from '@/api/oa/base/paymentStage/types';
import { useUserStore } from '@/store/modules/user';

/** 回款台账可见角色标识 */
const PAYMENT_LEDGER_ROLE_KEY = 'CVP';

/** 项目类别：9 = 合同订单（非实施项目），采购数据挂在实施项目的 project_id 上 */
const PROJECT_CATEGORY_CONTRACT_ORDER = '9';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();

const {
  business_direction,
  contract_category,
  contract_status,
  contract_territorial_flag,
  country_region,
  currency_type,
  contract_template_flag,
  shipping_mode,
  order_purchase_status,
  order_delivery_status,
  order_invoice_status,
  project_purchase_status,
  spare_flag,
  wf_business_status,
  invoice_status,
  invoice_category,
  early_flag,
  collection_confirm_status
} = toRefs<any>(
  proxy?.useDict(
    'business_direction',
    'contract_category',
    'contract_status',
    'contract_territorial_flag',
    'country_region',
    'currency_type',
    'contract_template_flag',
    'shipping_mode',
    'order_purchase_status',
    'order_delivery_status',
    'order_invoice_status',
    'project_purchase_status',
    'spare_flag',
    'wf_business_status',
    'invoice_status',
    'invoice_category',
    'early_flag',
    'collection_confirm_status'
  )
);

const projectId = computed(() => route.params.projectId as string | number | undefined);
const orderInfo = ref<ProjectInfoVO | null>(null);
const contractInfo = ref<ContractInfoVO | null>(null);

const sameUserId = (a: unknown, b: unknown): boolean => {
  if (a === undefined || a === null || a === '') return false;
  if (b === undefined || b === null || b === '') return false;
  return String(a) === String(b);
};

/** 回款信息：超级管理员、本合同订单创建人、合同负责人、或角色权限字符含 CVP */
const canViewPaymentLedger = computed(() => {
  const roles = userStore.roles ?? [];
  if (roles.includes('superadmin')) {
    return true;
  }
  if (roles.some((r) => r === PAYMENT_LEDGER_ROLE_KEY)) {
    return true;
  }
  const uid = userStore.userId;
  if (sameUserId(uid, orderInfo.value?.createBy)) {
    return true;
  }
  if (sameUserId(uid, contractInfo.value?.contractManagerId)) {
    return true;
  }
  return false;
});
const shippingList = ref<WmsShippingBillVO[]>([]);
const planStageList = ref<ErpProjectPlanStageForm[]>([]);
const paymentStageList = ref<PaymentStageVO[]>([]);
const purchaseList = ref<ProjectPurchaseVO[]>([]);
const invoiceList = ref<FinInvoiceInfoVO[]>([]);
const purchaseMaterialList = ref<ContractOrderPurchaseMaterialVO[]>([]);

const activeTab = ref('contract');
const loadedTabs = ref<Set<string>>(new Set(['contract']));

const loadingContract = ref(false);
const loadingShipping = ref(false);
const loadingPayment = ref(false);
const loadingPurchase = ref(false);
const loadingInvoice = ref(false);

const shippingTotal = ref(0);
const shippingQuery = reactive({ pageNum: 1, pageSize: 10 });
const purchaseTotal = ref(0);
const purchaseQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined as string | number | undefined,
  relationId: undefined as string | number | undefined,
  spareFlag: undefined as string | undefined
});
const invoiceTotal = ref(0);
const invoiceQuery = reactive({ pageNum: 1, pageSize: 10, contractId: undefined as string | number | undefined });

/** 格式化数字 */
const formatNumber = (num: number) => {
  return num?.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const formatAmount = (num?: number | string | null) => {
  if (num === null || num === undefined || num === '') {
    return '0.00';
  }
  const value = Number(num);
  if (Number.isNaN(value)) {
    return '0.00';
  }
  return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

/** 对人民币汇率展示（与合同维护一致，最多 4 位小数） */
const formatExchangeRate = (val?: number | string | null) => {
  if (val === null || val === undefined || val === '') {
    return '-';
  }
  const n = Number(val);
  if (!Number.isFinite(n)) {
    return '-';
  }
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 4 });
};

/** 合同阶段比例等百分比展示 */
const formatStagePercent = (val: number | string | null | undefined) => {
  if (val === null || val === undefined || val === '') {
    return '-';
  }
  const n = Number(val);
  if (!Number.isFinite(n)) {
    return '-';
  }
  return n;
};

/**
 * 优先展示后端 actualRepaymentRate；若无则用实际回款金额 / 合同总价推算（与合同回款确认逻辑一致）
 */
const displayPlanStageActualRepaymentRate = (row: ErpProjectPlanStageForm) => {
  const stored = row.actualRepaymentRate;
  if (stored != null && Number.isFinite(Number(stored))) {
    return Number(stored);
  }
  const actual = Number(row.actualRepaymentAmount ?? 0);
  const total = Number(contractInfo.value?.totalPrice ?? 0);
  if (!Number.isFinite(total) || total <= 0) {
    return '-';
  }
  return Math.round((actual / total) * 10000) / 100;
};

/** 返回 */
const handleBack = () => {
  proxy?.$tab.closePage(route);
  router.back();
};

/** 查看发货单明细 */
const handleViewShipping = (row: WmsShippingBillVO) => {
  router.push({ path: '/shipping/wmsShippingBill/edit', query: { type: 'view', id: row.shippingBillId as string } });
};

/** 前往采购页面 */
const openPurchasePage = () => {
  proxy?.$tab.openPage('/purchase/projectPurchase', '采购管理');
};

/** 前往发货页面 */
const openShippingPage = () => {
  proxy?.$tab.openPage('/shipping/wmsShippingBill', '发货管理');
};

/** 查看采购信息 */
const viewPurchase = (row: ProjectPurchaseVO) => {
  if (!row?.projectPurchaseId) return;
  proxy?.$tab.openPage('/purchase/projectPurchase/edit', '采购信息', {
    id: row.projectPurchaseId,
    type: 'view'
  });
};

/** 从台账新增采购，并携带项目信息 */
const addPurchaseFromLedger = () => {
  const contractId = orderInfo.value?.contractId ?? contractInfo.value?.contractId;
  if (!contractId) {
    proxy?.$modal.msgWarning('合同信息未加载完成，请稍后重试');
    return;
  }
  proxy?.$tab.openPage('/purchase/projectPurchase/edit', '采购信息', {
    type: 'add',
    source: 'orderLedger',
    contractId
  });
};

/** 从台账新增发货，并携带合同信息 */
const addShippingFromLedger = () => {
  const contractId = orderInfo.value?.contractId ?? contractInfo.value?.contractId;
  if (!contractId) {
    proxy?.$modal.msgWarning('合同信息未加载完成，请稍后重试');
    return;
  }
  proxy?.$tab.openPage('/shipping/wmsShippingBill/edit', '发货信息', {
    type: 'add',
    source: 'orderLedger',
    bindType: '2',
    contractId,
    projectId: projectId.value
  });
};

/** 查看开票信息 */
const viewInvoice = (row: FinInvoiceInfoVO) => {
  if (!row?.invoiceId) return;
  proxy?.$tab.openPage('/fin/finInvoiceInfo/edit', '开票信息', {
    id: row.invoiceId,
    type: 'view'
  });
};

/** 从台账新增开票，并携带合同信息 */
const addInvoiceFromLedger = () => {
  const contractId = orderInfo.value?.contractId ?? contractInfo.value?.contractId;
  if (!contractId) {
    proxy?.$modal.msgWarning('合同信息未加载完成，请稍后重试');
    return;
  }
  proxy?.$tab.openPage('/fin/finInvoiceInfo/edit', '开票信息', {
    type: 'add',
    source: 'orderLedger',
    contractId
  });
};

/** 加载订单基本信息和合同信息 */
const loadOrderAndContract = async () => {
  if (!projectId.value) return;
  loadingContract.value = true;
  try {
    // 先获取订单信息
    const orderRes = await getContractOrder(projectId.value);
    orderInfo.value = orderRes.data;
    // 再通过 contractId 获取合同详情
    if (orderRes.data?.contractId) {
      const contractRes = await getContractInfo(orderRes.data.contractId);
      contractInfo.value = contractRes.data;
    } else {
      contractInfo.value = null;
    }
  } finally {
    loadingContract.value = false;
    // 无回款查看权限时：避免仍停留在已隐藏的 payment Tab 上
    if (!canViewPaymentLedger.value) {
      if (activeTab.value === 'payment') {
        activeTab.value = 'contract';
      }
      loadedTabs.value.delete('payment');
      planStageList.value = [];
    }
  }
};

/**
 * 解析台账当前关联的合同ID（订单信息优先，合同详情兜底）。
 */
const resolveContractId = (): string | number | undefined => {
  return orderInfo.value?.contractId ?? contractInfo.value?.contractId;
};

/**
 * 采购单按 erp_project_purchase.project_id（实施项目）查询。
 * 台账路由参数为合同订单行时，需解析到关联的实施项目 ID，不能直接用路由上的合同订单 project_id。
 */
const resolvePurchaseBizProjectId = async (): Promise<string | number | undefined> => {
  const o = orderInfo.value;
  if (!o?.projectId) return undefined;
  if (o.projectCategory !== PROJECT_CATEGORY_CONTRACT_ORDER) {
    return o.projectId;
  }
  if (o.parentProjectId != null && String(o.parentProjectId) !== '') {
    return o.parentProjectId;
  }
  const cid = o.contractId;
  if (!cid) return undefined;
  try {
    const res = await listProjectInfoByContractId(cid);
    const list = res.data ?? [];
    const impl = list.find((p) => p.projectCategory !== PROJECT_CATEGORY_CONTRACT_ORDER);
    if (impl?.projectId != null && String(impl.projectId) !== '') {
      return impl.projectId;
    }
  } catch {
    // 忽略：无实施项目时采购为空
  }
  return undefined;
};

/** 加载采购信息 */
const loadPurchaseList = async () => {
  if (!orderInfo.value) {
    purchaseList.value = [];
    purchaseTotal.value = 0;
    purchaseMaterialList.value = [];
    return;
  }

  const contractId = resolveContractId();
  loadingPurchase.value = true;
  try {
    const bizProjectId = await resolvePurchaseBizProjectId();
    if (bizProjectId != null && bizProjectId !== '') {
      purchaseQuery.projectId = bizProjectId;
      purchaseQuery.relationId = undefined;
      const purchaseRes = await listProjectPurchase({
        ...purchaseQuery
      });
      purchaseList.value = purchaseRes.rows || [];
      purchaseTotal.value = purchaseRes.total || 0;
    } else {
      purchaseList.value = [];
      purchaseTotal.value = 0;
    }

    if (contractId != null && contractId !== '') {
      const materialRes = await getContractOrderPurchaseMaterialList(contractId);
      purchaseMaterialList.value = materialRes.data || [];
    } else {
      purchaseMaterialList.value = [];
    }
  } finally {
    loadingPurchase.value = false;
  }
};

const getPurchaseMaterialRowClass = ({ row }: { row: { unpurchasedAmount?: number | string | null } }) => {
  const unpurchasedAmount = Number(row.unpurchasedAmount ?? 0);
  if (unpurchasedAmount === 0) {
    return 'purchase-row-success';
  }
  if (unpurchasedAmount > 0) {
    return 'purchase-row-warning';
  }
  return '';
};

/** 加载开票信息 */
const loadInvoiceList = async () => {
  const contractId = orderInfo.value?.contractId ?? contractInfo.value?.contractId;
  if (!contractId) {
    invoiceList.value = [];
    invoiceTotal.value = 0;
    return;
  }

  invoiceQuery.contractId = contractId;

  loadingInvoice.value = true;
  try {
    const res: any = await listFinInvoiceInfo(invoiceQuery);
    invoiceList.value = res.rows || [];
    invoiceTotal.value = res.total || 0;
  } finally {
    loadingInvoice.value = false;
  }
};

/** 加载发货信息 */
const loadShippingList = async () => {
  if (!orderInfo.value?.contractId) {
    shippingList.value = [];
    shippingTotal.value = 0;
    return;
  }
  loadingShipping.value = true;
  try {
    const res: any = await listWmsShippingBill({
      ...shippingQuery,
      contractId: orderInfo.value.contractId
    });
    shippingList.value = res.rows || [];
    shippingTotal.value = res.total || 0;
  } finally {
    loadingShipping.value = false;
  }
};

/** 加载回款阶段基础数据 */
const loadPaymentStageBaseList = async () => {
  try {
    const res = await getBasePaymentStageList({ pageNum: 1, pageSize: 9999 });
    paymentStageList.value = (res.data || []).map((item: any) => ({
      ...item,
      paymentStageId: item.paymentStageId != null ? String(item.paymentStageId) : item.paymentStageId
    }));
  } catch (error) {
    console.error('查询回款阶段列表失败:', error);
    paymentStageList.value = [];
  }
};

/** 加载回款信息（项目阶段计划） */
const loadPlanStageList = async () => {
  if (!canViewPaymentLedger.value) {
    planStageList.value = [];
    return;
  }
  if (!projectId.value) {
    planStageList.value = [];
    return;
  }
  loadingPayment.value = true;
  try {
    const res = await getErpProjectPlanStageList({ projectId: projectId.value });
    planStageList.value = (res.data || []).map((item: any) => ({
      ...item,
      paymentStageId: item.paymentStageId,
      paymentStageName: item.paymentStageName,
      repaymentRate: item.repaymentRate || undefined,
      repaymentTime: item.repaymentTime || undefined,
      remark: item.remark || ''
    }));
  } catch (error) {
    console.error('查询回款信息失败:', error);
    planStageList.value = [];
  } finally {
    loadingPayment.value = false;
  }
};

/** 获取回款阶段名称 */
const getPaymentStageName = (stageId: string | number | undefined) => {
  if (stageId === undefined || stageId === null || stageId === '') return '-';
  const stage = paymentStageList.value.find((s) => String(s.paymentStageId) === String(stageId));
  return stage?.stageName || '-';
};

/** Tab 切换 */
const handleTabChange = (tabName: string) => {
  if (!loadedTabs.value.has(tabName)) {
    loadedTabs.value.add(tabName);
    switch (tabName) {
      case 'invoice':
        invoiceQuery.pageNum = 1;
        loadInvoiceList();
        break;
      case 'purchase':
        purchaseQuery.pageNum = 1;
        loadPurchaseList();
        break;
      case 'shipping':
        shippingQuery.pageNum = 1;
        loadShippingList();
        break;
      case 'payment':
        if (canViewPaymentLedger.value) {
          loadPlanStageList();
        }
        break;
    }
  }
};

watch(
  () => projectId.value,
  () => {
    if (projectId.value) {
      activeTab.value = 'contract';
      loadedTabs.value.clear();
      loadedTabs.value.add('contract');
      loadPaymentStageBaseList();
      loadOrderAndContract();
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.order-ledger-container {
  padding: 16px;

  .main-card {
    :deep(.el-card__header) {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .header-title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
    }

    :deep(.el-card__body) {
      padding: 0;
    }
  }

  .custom-tabs {
    :deep(.el-tabs__content) {
      padding: 20px;
    }
  }

  .tab-content {
    padding: 0;
  }

  .contract-info-pane {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .contract-desc-section {
    &__title {
      margin: 0 0 10px;
      font-size: 15px;
      font-weight: 600;
      color: #303133;
      padding-left: 8px;
      border-left: 3px solid #409eff;
    }
  }

  .order-descriptions {
    .value-text {
      &.value-highlight {
        font-weight: 600;
        color: #409eff;
      }

      &.value-amount {
        font-weight: 600;
        color: #e6a23c;
      }
    }
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;

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

      .section-icon {
        font-size: 16px;
        color: #409eff;
      }

      .section-title {
        font-size: 15px;
        font-weight: 600;
        color: #303133;
      }
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .payment-header-actions {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .payment-contract-total-inline {
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;

    &__label {
      font-size: 14px;
      color: #606266;
      font-weight: 500;
    }

    .value-text.value-amount {
      font-weight: 600;
      color: #e6a23c;
    }
  }

  .data-table {
    :deep(.el-table__header) {
      th {
        font-weight: 600;
      }
    }
  }

  .purchase-material-section {
    margin-top: 24px;
  }

  .purchase-material-table {
    :deep(.el-table__body tr.purchase-row-success > td.el-table__cell) {
      background-color: #f0f9eb !important;
    }

    :deep(.el-table__body tr.purchase-row-warning > td.el-table__cell) {
      background-color: #fdf6ec !important;
    }
  }

  .empty-state {
    padding: 40px 0;
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
