<template>
  <div style="padding: 20px">
    <el-card shadow="always">
      <template #header>
        <p>支付审批明细</p>
      </template>

      <div>
        <el-tabs v-model="activeTab">
          <el-tab-pane
            :label="`待采购${
              pendingBadgeCount ? '（' + pendingBadgeCount + '）' : ''
            }`"
            name="pending"
          >
            <div
              style="
                margin-bottom: 10px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                gap: 10px;
              "
            >
              <el-input
                v-model="pendingQuery.keywords"
                placeholder="关键词"
                size="small"
                clearable
                style="width: 200px"
              />
              <el-select
                v-model="pendingQuery.creator_department_id"
                placeholder="科室"
                size="small"
                clearable
                style="width: 150px"
              >
                <el-option
                  v-for="item in departments"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-select
                v-model="pendingQuery.created_by"
                placeholder="发起人"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>

              <el-select
                v-model="pendingQuery.chengbanren_id"
                placeholder="采购负责人"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in purchasers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-select
                v-model="pendingQuery.caigouneirong"
                placeholder="采购类别"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in purchaseContents"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-search"
                @click="handlePendingQueryChange"
                >查询</el-button
              >
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                @click="handleBatchPay"
                >批量支付</el-button
              >
            </div>
            <el-table
              ref="pendingTable"
              :data="pendingRows"
              border
              style="width: 100%"
              row-key="id"
              @selection-change="handlePendingSelectionChange"
            >
              <el-table-column
                type="selection"
                width="50"
                reserve-selection
              ></el-table-column>
              <el-table-column label="申请人" width="80" align="center">
                <template #default="{ row }">
                  {{ row.applicant }}
                </template>
              </el-table-column>
              <el-table-column label="申请科室" width="100" align="center">
                <template #default="{ row }">
                  {{ row.department }}
                </template>
              </el-table-column>
              <el-table-column label="流程名称" width="160" align="center">
                <template #default="{ row }">
                  <div
                    @click="showModal(row)"
                    style="cursor: pointer; color: #409eff"
                  >
                    {{ row.flowTitle }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="采购类别"
                width="100"
                align="center"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purchaseContent }}
                </template>
              </el-table-column>
              <el-table-column
                label="采购负责人"
                width="100"
                align="center"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purchaser }}
                </template>
              </el-table-column>

              <el-table-column label="本次报销数量" width="120" align="center">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.applyNum"
                    :min="0"
                    :controls="false"
                    size="small"
                    :class="{ 'error-input': isApplyNumInvalid(row) }"
                    style="width: 90px"
                    @change="validateApplyNum(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="付款金额" width="120" align="center">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.money"
                    :min="0"
                    :precision="2"
                    :controls="false"
                    size="small"
                    style="width: 90px"
                  />
                </template>
              </el-table-column>
              <el-table-column label="已报销数量" width="100" align="center">
                <template #default="{ row }">
                  {{ row.paidNum }}
                </template>
              </el-table-column>
              <el-table-column label="数量" width="100" align="center">
                <template #default="{ row }">
                  {{ row.total }}
                </template>
              </el-table-column>
              <el-table-column label="是否合同审批" width="120" align="center">
                <template #default="{ row }">
                  <el-select
                    v-model="row.shifouhetongshenpi"
                    placeholder="是否合同审批"
                    size="small"
                    @change="
                      (val) =>
                        handlePendingFieldUpdate(row, 'shifouhetongshenpi', val)
                    "
                    style="width: 90px"
                  >
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="清单情况" width="120" align="center">
                <template #default="{ row }">
                  <el-select
                    v-model="row.shifouqingdan"
                    placeholder="清单情况"
                    size="small"
                    @change="
                      (val) =>
                        handlePendingFieldUpdate(row, 'shifouqingdan', val)
                    "
                    style="width: 90px"
                  >
                    <el-option label="清单内" value="清单内" />
                    <el-option label="清单外" value="清单外" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="是否比价" width="120" align="center">
                <template #default="{ row }">
                  <el-select
                    v-model="row.shifoubijia"
                    placeholder="是否比价"
                    size="small"
                    @change="
                      (val) => handlePendingFieldUpdate(row, 'shifoubijia', val)
                    "
                    style="width: 90px"
                  >
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="是否收货" width="120" align="center">
                <template #default="{ row }">
                  <el-select
                    v-model="row.shifoufahuo"
                    placeholder="是否收货"
                    size="small"
                    @change="
                      (val) => handlePendingFieldUpdate(row, 'shifoufahuo', val)
                    "
                    style="width: 90px"
                  >
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column
                label="品名或服务需求"
                min-width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.itemName }}
                </template>
              </el-table-column>
              <el-table-column
                label="型号与规格"
                width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.model }}
                </template>
              </el-table-column>
              <el-table-column label="产地" width="100" align="center">
                <template #default="{ row }">
                  {{ row.origin }}
                </template>
              </el-table-column>
              <el-table-column label="单位" width="100" align="center">
                <template #default="{ row }">
                  {{ row.unit }}
                </template>
              </el-table-column>
              <el-table-column
                label="用途"
                min-width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purpose }}
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin-top: 10px"
              @size-change="handlePendingSizeChange"
              @current-change="handlePendingPageChange"
              :current-page="pendingPage"
              :page-sizes="[10, 20, 30, 40, 50, 100]"
              :page-size="pendingPageSize"
              layout="total, ->, prev, pager, next, sizes, jumper"
              :total="pendingTotal"
            />
          </el-tab-pane>

          <el-tab-pane
            :label="`明细拆分前${
              beforeSplitBadgeCount ? '（' + beforeSplitBadgeCount + '）' : ''
            }`"
            name="beforeSplit"
          >
            <div
              style="
                margin-bottom: 10px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                gap: 10px;
              "
            >
              <el-input
                v-model="beforeSplitQuery.keywords"
                placeholder="关键词"
                size="small"
                clearable
                style="width: 200px"
              />
              <el-select
                v-model="beforeSplitQuery.creator_department_id"
                placeholder="科室"
                size="small"
                clearable
                style="width: 150px"
              >
                <el-option
                  v-for="item in departments"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-select
                v-model="beforeSplitQuery.created_by"
                placeholder="发起人"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>

              <el-select
                v-model="beforeSplitQuery.chengbanren_id"
                placeholder="采购负责人"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in purchasers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-select
                v-model="beforeSplitQuery.caigouneirong"
                placeholder="采购类别"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in purchaseContents"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-search"
                @click="handleBeforeSplitQueryChange"
                >查询</el-button
              >
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                @click="handleBatchPayBeforeSplit"
                >批量支付</el-button
              >
            </div>
            <el-table
              ref="beforeSplitTable"
              :data="beforeSplitRows"
              border
              style="width: 100%"
              row-key="id"
              @selection-change="handleBeforeSplitSelectionChange"
            >
              <el-table-column
                type="selection"
                width="50"
                reserve-selection
              ></el-table-column>
              <el-table-column label="申请人" width="80" align="center">
                <template #default="{ row }">
                  {{ row.applicant }}
                </template>
              </el-table-column>
              <el-table-column label="申请科室" width="100" align="center">
                <template #default="{ row }">
                  {{ row.department }}
                </template>
              </el-table-column>
              <el-table-column label="流程名称" width="160" align="center">
                <template #default="{ row }">
                  <div
                    @click="showModal(row)"
                    style="cursor: pointer; color: #409eff"
                  >
                    {{ row.flowTitle }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="采购类别"
                width="100"
                align="center"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purchaseContent }}
                </template>
              </el-table-column>
              <el-table-column
                label="采购负责人"
                width="100"
                align="center"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purchaser }}
                </template>
              </el-table-column>

              <el-table-column label="本次报销数量" width="120" align="center">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.applyNum"
                    :min="0"
                    :controls="false"
                    size="small"
                    :class="{ 'error-input': isApplyNumInvalid(row) }"
                    style="width: 90px"
                    @change="validateApplyNum(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="付款金额" width="120" align="center">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.money"
                    :min="0"
                    :precision="2"
                    :controls="false"
                    size="small"
                    style="width: 90px"
                  />
                </template>
              </el-table-column>
              <el-table-column label="已报销数量" width="100" align="center">
                <template #default="{ row }">
                  {{ row.paidNum }}
                </template>
              </el-table-column>
              <el-table-column label="数量" width="100" align="center">
                <template #default="{ row }">
                  {{ row.total }}
                </template>
              </el-table-column>
              <el-table-column label="是否合同审批" width="120" align="center">
                <template #default="{ row }">
                  <el-select
                    v-model="row.shifouhetongshenpi"
                    placeholder="是否合同审批"
                    size="small"
                    @change="
                      (val) =>
                        handleBeforeSplitFieldUpdate(row, 'shifouhetongshenpi', val)
                    "
                    style="width: 90px"
                  >
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="清单情况" width="120" align="center">
                <template #default="{ row }">
                  <el-select
                    v-model="row.shifouqingdan"
                    placeholder="清单情况"
                    size="small"
                    @change="
                      (val) =>
                        handleBeforeSplitFieldUpdate(row, 'shifouqingdan', val)
                    "
                    style="width: 90px"
                  >
                    <el-option label="清单内" value="清单内" />
                    <el-option label="清单外" value="清单外" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="是否比价" width="120" align="center">
                <template #default="{ row }">
                  <el-select
                    v-model="row.shifoubijia"
                    placeholder="是否比价"
                    size="small"
                    @change="
                      (val) => handleBeforeSplitFieldUpdate(row, 'shifoubijia', val)
                    "
                    style="width: 90px"
                  >
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="是否收货" width="120" align="center">
                <template #default="{ row }">
                  <el-select
                    v-model="row.shifoufahuo"
                    placeholder="是否收货"
                    size="small"
                    @change="
                      (val) => handleBeforeSplitFieldUpdate(row, 'shifoufahuo', val)
                    "
                    style="width: 90px"
                  >
                    <el-option label="是" value="是" />
                    <el-option label="否" value="否" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column
                label="品名或服务需求"
                min-width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.itemName }}
                </template>
              </el-table-column>
              <el-table-column
                label="型号与规格"
                width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.model }}
                </template>
              </el-table-column>
              <el-table-column label="产地" width="100" align="center">
                <template #default="{ row }">
                  {{ row.origin }}
                </template>
              </el-table-column>
              <el-table-column label="单位" width="100" align="center">
                <template #default="{ row }">
                  {{ row.unit }}
                </template>
              </el-table-column>
              <el-table-column
                label="用途"
                min-width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purpose }}
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin-top: 10px"
              @size-change="handleBeforeSplitSizeChange"
              @current-change="handleBeforeSplitPageChange"
              :current-page="beforeSplitPage"
              :page-sizes="[10, 20, 30, 40, 50, 100]"
              :page-size="beforeSplitPageSize"
              layout="total, ->, prev, pager, next, sizes, jumper"
              :total="beforeSplitTotal"
            />
          </el-tab-pane>

          <el-tab-pane label="已支付" name="paid">
            <div
              style="
                margin-bottom: 10px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                gap: 10px;
              "
            >
              <el-input
                v-model="paidQuery.keywords"
                placeholder="关键词"
                size="small"
                clearable
                style="width: 200px"
              />
              <el-select
                v-model="paidQuery.creator_department_id"
                placeholder="科室"
                size="small"
                clearable
                style="width: 150px"
              >
                <el-option
                  v-for="item in departments"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-select
                v-model="paidQuery.created_by"
                placeholder="发起人"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-select
                v-model="paidQuery.chengbanren_id"
                placeholder="采购负责人"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in purchasers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-select
                v-model="paidQuery.caigouneirong"
                placeholder="采购类别"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in purchaseContents"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
              <el-select
                v-model="paidQuery.status"
                placeholder="是否支付完成"
                size="small"
                clearable
                filterable
                style="width: 150px"
              >
                <el-option
                  v-for="item in [{label: '是', value: 1}, {label: '否', value: 0}]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-search"
                @click="handlePaidQueryChange"
                >查询</el-button
              >
            </div>
            <el-table :data="paidRows" border style="width: 100%" row-key="id">
              <el-table-column label="申请人" width="80" align="center">
                <template #default="{ row }">
                  {{ row.applicant }}
                </template>
              </el-table-column>
              <el-table-column label="申请科室" width="100" align="center">
                <template #default="{ row }">
                  {{ row.department }}
                </template>
              </el-table-column>
              <el-table-column label="流程名称" width="160" align="center">
                <template #default="{ row }">
                  <div
                    @click="showModal(row)"
                    style="cursor: pointer; color: #409eff"
                  >
                    {{ row.flowTitle }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="采购类别"
                width="100"
                align="center"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purchaseContent }}
                </template>
              </el-table-column>
              <el-table-column
                label="采购负责人"
                width="100"
                align="center"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purchaser }}
                </template>
              </el-table-column>

              <el-table-column label="已报销数量" width="100" align="center">
                <template #default="{ row }">
                  {{ row.paidNum }}
                </template>
              </el-table-column>
              <el-table-column label="付款金额" width="100" align="center">
                <template #default="{ row }">
                  {{ row.money }}
                </template>
              </el-table-column>
              <el-table-column label="数量" width="100" align="center">
                <template #default="{ row }">
                  {{ row.total }}
                </template>
              </el-table-column>
              <el-table-column label="是否支付完成" width="120" align="center">
                <template #default="{ row }">
                  {{ row.fund_log.status ? '是' : '否' }}
                </template>
              </el-table-column>
              <el-table-column label="是否合同审批" width="120" align="center">
                <template #default="{ row }">
                  {{ row.shifouhetongshenpi || "" }}
                </template>
              </el-table-column>
              <el-table-column label="清单情况" width="120" align="center">
                <template #default="{ row }">
                  {{ row.shifouqingdan || "" }}
                </template>
              </el-table-column>
              <el-table-column label="是否比价" width="100" align="center">
                <template #default="{ row }">
                  {{ row.shifoubijia || "" }}
                </template>
              </el-table-column>
              <el-table-column label="是否收货" width="100" align="center">
                <template #default="{ row }">
                  {{ row.shifoufahuo || "" }}
                </template>
              </el-table-column>

              <el-table-column
                label="品名或服务需求"
                min-width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.itemName }}
                </template>
              </el-table-column>
              <el-table-column
                label="型号与规格"
                width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.model }}
                </template>
              </el-table-column>
              <el-table-column label="产地" width="100" align="center">
                <template #default="{ row }">
                  {{ row.origin }}
                </template>
              </el-table-column>
              <el-table-column label="单位" width="100" align="center">
                <template #default="{ row }">
                  {{ row.unit }}
                </template>
              </el-table-column>
              <el-table-column
                label="用途"
                min-width="140"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.purpose }}
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin-top: 10px"
              @size-change="handlePaidSizeChange"
              @current-change="handlePaidPageChange"
              :current-page="paidPage"
              :page-sizes="[10, 20, 30, 40, 50, 100]"
              :page-size="paidPageSize"
              layout="total, ->, prev, pager, next, sizes, jumper"
              :total="paidTotal"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <payMx ref="payMx" :is-show.sync="isShowPay"></payMx>

    <vxe-modal
      v-model="isShowModal"
      :z-index="zIndex"
      transfer
      show-zoom
      resize
      :fullscreen="true"
      title="查看流程"
      :width="defaultModalSize.width"
      :height="defaultModalSize.height"
      esc-closable
      :padding="false"
    >
      <iframe
        :src="modalUrl"
        style="display: block; width: 100%; height: 100%; border: 0"
        frameborder="0"
      />
    </vxe-modal>

    <el-dialog
      title="已选采购明细"
      :visible.sync="selectedPreviewVisible"
      width="60%"
      @close="closeSelectedPreview"
    >
      <el-table
        ref="previewTable"
        :data="selectedPreviewRows"
        border
        height="400"
        style="width: 100%"
        row-key="id"
        @selection-change="handleSelectedPreviewSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="申请人" width="80" align="center">
          <template #default="{ row }">
            {{ row.applicant }}
          </template>
        </el-table-column>
        <el-table-column label="申请科室" width="100" align="center">
          <template #default="{ row }">
            {{ row.department }}
          </template>
        </el-table-column>
        <el-table-column label="流程名称" width="160" align="center">
          <template #default="{ row }">
            <div
              @click="showModal(row)"
              style="cursor: pointer; color: #409eff"
            >
              {{ row.flowTitle }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="采购类别"
          min-width="120"
          align="center"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.purchaseContent }}
          </template>
        </el-table-column>
        <el-table-column
          label="采购负责人"
          width="100"
          align="center"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.purchaser }}
          </template>
        </el-table-column>
        <el-table-column label="本次报销数量" width="120" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.applyNum"
              :min="0"
              :controls="false"
              size="small"
              :class="{ 'error-input': isApplyNumInvalid(row) }"
              style="width: 90px"
              @change="validateApplyNum(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="付款金额" width="120" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.money"
              :min="0"
              :precision="2"
              :controls="false"
              size="small"
              style="width: 90px"
            />
          </template>
        </el-table-column>
        <el-table-column label="已报销数量" width="100" align="center">
          <template #default="{ row }">
            {{ row.paidNum }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100" align="center">
          <template #default="{ row }">
            {{ row.total }}
          </template>
        </el-table-column>
        <el-table-column label="是否合同审批" width="120" align="center">
          <template #default="{ row }">
            {{ row.shifouhetongshenpi || "" }}
          </template>
        </el-table-column>
        <el-table-column label="清单情况" width="120" align="center">
          <template #default="{ row }">
            {{ row.shifouqingdan || "" }}
          </template>
        </el-table-column>
        <el-table-column label="是否比价" width="100" align="center">
          <template #default="{ row }">
            {{ row.shifoubijia || "" }}
          </template>
        </el-table-column>
        <el-table-column label="是否收货" width="100" align="center">
          <template #default="{ row }">
            {{ row.shifoufahuo || "" }}
          </template>
        </el-table-column>
        <el-table-column
          label="品名或服务需求"
          min-width="140"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.itemName }}
          </template>
        </el-table-column>
        <el-table-column label="型号与规格" width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.model }}
          </template>
        </el-table-column>
        <el-table-column label="产地" width="100" align="center">
          <template #default="{ row }">
            {{ row.origin }}
          </template>
        </el-table-column>
        <el-table-column label="单位" width="100" align="center">
          <template #default="{ row }">
            {{ row.unit }}
          </template>
        </el-table-column>
        <el-table-column label="用途" min-width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.purpose }}
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSelectedPreview">取 消</el-button>
        <el-button type="primary" @click="confirmSelectedPreview"
          >确认支付</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  waitList,
  receiveList,
  getFundLog,
  detailContract,
  updateList,
} from "@/api/flow/pay";
import payMx from "./components/payMx.vue";
import {
  departmentListNoAuth,
  caigoumingxiConfig,
  userListNoAuth,
} from "@/api/common";
import { PopupManager } from "element-ui/lib/utils/popup";
import { defaultModalSize } from "@/settings";
import { getToken } from "@/utils/auth";
export default {
  name: "PayList",
  components: {
    payMx,
  },
  data() {
    return {
      isShowModal: false,
      modalUrl: "",
      zIndex: PopupManager.nextZIndex(),
      defaultModalSize,
      departments: [],
      users: [],
      purchasers: [], // 采购负责人列表
      purchaseContents: [], // 采购类别列表
      waitList: [],
      activeTab: "pending",
      pendingQuery: {
        creator_department_id: "",
        created_by: "",
        keywords: "",
        chengbanren_id: "",
        caigouneirong: "",
      },
      pendingRows: [],
      pendingPage: 1,
      pendingPageSize: 10,
      pendingTotal: 0,
      pendingSelectedIds: [],
      pendingSelectedMap: {},
      beforeSplitQuery: {
        creator_department_id: "",
        created_by: "",
        keywords: "",
        chengbanren_id: "",
        caigouneirong: "",
      },
      beforeSplitRows: [],
      beforeSplitPage: 1,
      beforeSplitPageSize: 10,
      beforeSplitTotal: 0,
      beforeSplitSelectedIds: [],
      beforeSplitSelectedMap: {},
      selectedPreviewVisible: false,
      selectedPreviewRows: [],
      selectedPreviewSelection: [],
      selectedPreviewSource: "pending", // 标记数据来源: "pending" 或 "beforeSplit"
      syncingPreviewSelection: false,
      syncingPendingSelection: false,
      syncingBeforeSplitSelection: false,
      isShowPay: false,
      paidQuery: {
        creator_department_id: "",
        created_by: "",
        keywords: "",
        chengbanren_id: "",
        caigouneirong: "",
        status: "",
      },
      paidRows: [],
      paidPage: 1,
      paidPageSize: 10,
      paidTotal: 0,
    };
  },
  computed: {
    pendingBadgeCount() {
      return this.pendingSelectedIds && this.pendingSelectedIds.length
        ? this.pendingSelectedIds.length
        : 0;
    },
    beforeSplitBadgeCount() {
      return this.beforeSplitSelectedIds && this.beforeSplitSelectedIds.length
        ? this.beforeSplitSelectedIds.length
        : 0;
    },
  },
  methods: {
    async handlePendingFieldUpdate(row, field, value) {
      const oldValue = row[field];
      // v-model 已经写入新值，这里确保使用传入值
      try {
        await updateList({ id: row.id, [field]: value });
        this.$message.success("已保存");
      } catch (e) {
        // 失败回滚
        this.$message.error("保存失败，请重试");
        this.$set(row, field, oldValue);
      }
    },
    async handleBeforeSplitFieldUpdate(row, field, value) {
      const oldValue = row[field];
      // v-model 已经写入新值，这里确保使用传入值
      try {
        await updateList({ id: row.id, [field]: value });
        this.$message.success("已保存");
      } catch (e) {
        // 失败回滚
        this.$message.error("保存失败，请重试");
        this.$set(row, field, oldValue);
      }
    },
    showModal(row) {
      this.modalUrl = `/oa/#/flow/detail?module_id=${
        row.yibancaigou?.flow?.custom_model_id
      }&flow_id=${
        row.yibancaigou?.flow?.id
      }&auth_token=${window.encodeURIComponent(getToken())}&isSinglePage=1`;
      this.isShowModal = true;
    },
    async getDepartmentList() {
      const res = await departmentListNoAuth();
      console.log(res);
      const arr = res;
      this.departments = arr;
      this.departments.unshift({
        id: "",
        name: "全部",
      });
    },
    async getUserList() {
      const res = await caigoumingxiConfig();
      const userRes = await userListNoAuth({
        page: 1,
        rows: 9999,
      });
      console.log(res);
      const arr = userRes.data;
      this.users = arr;
      // 保存采购负责人列表
      this.purchasers = res.users;
      // 保存采购类别列表
      this.purchaseContents = res.customModelFieldStub;
    },
    switchTab(tab) {
      this.activeTab = tab;
    },
    isApplyNumInvalid(row) {
      const applyNum =
        row.applyNum === null || row.applyNum === undefined
          ? null
          : Number(row.applyNum);
      const paidNum = Number(row.paidNum) || 0;
      const total = Number(row.total) || 0;

      // 如果未输入，不显示错误
      if (applyNum === null) {
        return false;
      }

      // 检查本次报销数量是否为0
      if (applyNum === 0) {
        return true;
      }

      // 检查本次报销数量 + 已报销数量是否大于总数量
      if (applyNum + paidNum > total) {
        return true;
      }

      return false;
    },
    validateApplyNum(row) {
      if (this.isApplyNumInvalid(row)) {
        const applyNum =
          row.applyNum === null || row.applyNum === undefined
            ? null
            : Number(row.applyNum);
        const paidNum = Number(row.paidNum) || 0;
        const total = Number(row.total) || 0;

        if (applyNum === 0) {
          this.$message.warning("本次报销数量不能为0");
        } else if (applyNum + paidNum > total) {
          this.$message.warning("本次报销数量大于剩余可报销数量");
        }
      }
    },
    async handleBatchPay() {
      // 检查是否选中数据
      if (this.pendingSelectedIds.length === 0) {
        this.$message.warning("请先选择需要支付的明细");
        return;
      }
      this.openSelectedPreview();
      return;
    },
    async handleBatchPayBeforeSplit() {
      // 检查是否选中数据
      if (this.beforeSplitSelectedIds.length === 0) {
        this.$message.warning("请先选择需要支付的明细");
        return;
      }
      this.openSelectedPreviewBeforeSplit();
      return;
      // 以下老逻辑暂时保留（不执行）
      if (this.pendingSelectedIds.length === 0) {
        this.$message.warning("请先选择需要支付的明细");
        return;
      }

      // 获取当前页选中的行（使用 Element UI 的正确方法）
      const currentPageSelectedRows = this.pendingRows.filter((row) =>
        this.pendingSelectedIds.includes(row.id)
      );

      // 检查是否有跨页选中的数据
      const currentPageIds = this.pendingRows.map((row) => row.id);
      const crossPageSelectedIds = this.pendingSelectedIds.filter(
        (id) => !currentPageIds.includes(id)
      );

      if (crossPageSelectedIds.length > 0) {
        // 需要获取跨页选中数据的完整信息来计算页面
        const params = {
          page: 1,
          page_size: this.pendingTotal || 9999, // 获取所有数据以计算页面
        };
        if (this.pendingQuery.creator_department_id) {
          params.creator_department_id =
            this.pendingQuery.creator_department_id;
        }
        if (this.pendingQuery.created_by) {
          params.created_by = this.pendingQuery.created_by;
        }
        if (this.pendingQuery.keywords) {
          params.keywords = this.pendingQuery.keywords;
        }
        if (this.pendingQuery.chengbanren_id) {
          params.chengbanren_id = this.pendingQuery.chengbanren_id;
        }
        if (this.pendingQuery.caigouneirong) {
          params.caigouneirong = this.pendingQuery.caigouneirong;
        }

        const res = await waitList(params);
        const allData = res.data || [];

        // 找出跨页选中数据所在的页面
        const pagesToComplete = new Set();
        crossPageSelectedIds.forEach((selectedId) => {
          const index = allData.findIndex((item) => item.id === selectedId);
          if (index !== -1) {
            const page = Math.floor(index / this.pendingPageSize) + 1;
            pagesToComplete.add(page);
          }
        });

        if (pagesToComplete.size > 0) {
          const pagesArray = Array.from(pagesToComplete).sort((a, b) => a - b);
          const pagesText = pagesArray.join("、");
          this.$message.warning(`请完善第${pagesText}页的数据`);
          return;
        }
      }

      // 使用当前页选中的行进行验证
      const selectedRows = currentPageSelectedRows;
      if (selectedRows.length === 0) {
        this.$message.warning("请先选择需要支付的明细");
        return;
      }

      // 验证选中的数据
      const invalidRows = [];
      selectedRows.forEach((row) => {
        const applyNum = Number(row.applyNum) || 0;
        const paidNum = Number(row.paidNum) || 0;
        const total = Number(row.total) || 0;

        // 检查本次报销数量是否为0
        if (applyNum === 0) {
          invalidRows.push({
            row,
            reason: "本次报销数量不能为0",
          });
        }
        // 检查本次报销数量 + 已报销数量是否大于总数量
        else if (applyNum + paidNum > total) {
          invalidRows.push({
            row,
            reason: "本次报销数量大于剩余可报销数量",
          });
        }
      });

      // 如果有不符合条件的数据，提示并阻止提交
      if (invalidRows.length > 0) {
        const errorMessages = invalidRows
          .map((item) => {
            const itemName = item.row.itemName || "未知项目";
            return `${itemName}：${item.reason}`;
          })
          .join("；");

        this.$message.warning(`以下数据不符合条件：${errorMessages}`);

        // 确保错误行显示红色边框（通过触发响应式更新）
        this.$nextTick(() => {
          // 强制更新视图，确保红色边框显示
          this.$forceUpdate();
        });

        return;
      }

      // 构造 baseInfo
      const titleParts = selectedRows.map(
        (r) => `${r.itemName || ""}*${Number(r.applyNum) || 0}`
      );
      const zhifutitle = `${titleParts.join(",")}${
        titleParts.length ? "," : ""
      }`;
      const xiangxishuoming = zhifutitle;

      // 合同ID集合（去重）
      const contractIdSet = Array.from(
        new Set(
          selectedRows
            .map((r) => r?.yibancaigou?.flow?.out_contract_id)
            .filter((id) => id)
        )
      );
      const contractIdsStr = contractIdSet.join(",");

      // 合同ID字符串（按要求：相同取一个）
      const contract_id = contractIdsStr;

      // 申请总金额
      const amt = selectedRows.reduce(
        (sum, r) => sum + (Number(r.money) || 0),
        0
      );

      // 已付金额与次数：getFundLog
      let yifujine = 0;
      let cishu = 0;
      const fundRes = await getFundLog({
        contract_id: contractIdsStr,
        show_type: 1,
      });
      const payments = fundRes?.data || [];
      // @payMx.vue (591-592)
      const actNumsTotal = () =>
        payments.reduce(
          (pre, cur) =>
            pre + (Number(cur?.act_money) ? Number(cur.act_money) : 0),
          0
        );
      yifujine = actNumsTotal();
      cishu = Array.isArray(payments) ? payments.length : 0;

      // 相关合同信息（详细）
      let xiangmuzonge = 0;
      let zhifucishu = 0;
      let liezhiqudao = "";
      let contractno = "";
      let guanlianliucheng = "";
      // @payMx.vue (579-586)
      let contracts = [];
      if (contractIdSet.length > 0) {
        contracts = await Promise.all(
          contractIdSet.map((id) => detailContract({ id }))
        );
      }
      // @payMx.vue (601-606)
      const sumMoney = (contracts || []).reduce(
        (sum, c) => sum + (Number(c?.money) || 0),
        0
      );
      const sumPlanLen = (contracts || []).reduce(
        (sum, c) => sum + (c?.sign_plan?.length || 0),
        0
      );
      const plansNames = Array.from(
        new Set(
          (contracts || [])
            .flatMap((c) => (c?.plans || []).map((p) => p?.name))
            .filter(Boolean)
        )
      ).join(",");
      const contractNos = (contracts || [])
        .map((c) => c?.number)
        .filter(Boolean)
        .join(",");
      const relatedFlows = Array.from(
        new Set(
          (contracts || [])
            .flatMap((c) =>
              (c?.contract_flow_links || []).map((l) => l?.flow_id)
            )
            .filter(Boolean)
        )
      ).join(",");

      xiangmuzonge = sumMoney;
      zhifucishu = sumPlanLen;
      liezhiqudao = plansNames;
      contractno = contractNos;
      guanlianliucheng = relatedFlows;

      const baseInfo = {
        zhifutitle,
        contract_id,
        amt,
        xiangxishuoming,
        yifujine,
        cishu,
        xiangmuzonge,
        zhifucishu,
        liezhiqudao,
        contractno,
        guanlianliucheng,
        wuzicaigou_items,
      };

      // 明细项
      const wuzicaigou_items = selectedRows.map((r) => ({
        flow_id: r?.yibancaigou?.flow?.id,
        contract_id: r?.yibancaigou?.flow?.out_contract_id,
        wuzicaigou_id: r?.yibancaigou?.id,
        wuzicaigou_item_id: r?.id,
        name: r?.itemName,
        num: Number(r?.applyNum) || 0,
        total: Number(r?.num) || 0,
        apply_money: Number(r?.money) || 0,
        money: Number(r?.money) || 0,
        is_receive: 0,
      }));

      // 暂存到实例，供后续使用
      baseInfo.wuzicaigou_items = wuzicaigou_items;
      console.log(baseInfo, "baseInfo");
      const url = `/flow/create?&module_name=oa&isSinglePage=1&module_id=75&default_json=${window.encodeURIComponent(
        JSON.stringify(baseInfo)
      )}`;
      this.$router.push(url);
      // this.$message.success('数据已整理完成，可进行后续流程')
    },
    handlePendingSelectionChange(selection) {
      if (this.syncingPendingSelection) return;
      // 获取当前页选中的ID
      const currentPageIds = selection.map((row) => row.id);
      // 获取当前页所有行的ID
      const currentPageAllIds = this.pendingRows.map((row) => row.id);
      // 更新选中映射
      currentPageIds.forEach((id) => {
        const record =
          selection.find((row) => row.id === id) ||
          this.pendingRows.find((row) => row.id === id);
        if (record) {
          this.$set(this.pendingSelectedMap, id, record);
        }
      });
      currentPageAllIds.forEach((id) => {
        if (!currentPageIds.includes(id)) {
          if (this.pendingSelectedIds.includes(id)) {
            const index = this.pendingSelectedIds.indexOf(id);
            if (index > -1) {
              this.pendingSelectedIds.splice(index, 1);
            }
          }
          if (this.pendingSelectedMap[id]) {
            this.$delete(this.pendingSelectedMap, id);
          }
        }
      });
      currentPageIds.forEach((id) => {
        if (!this.pendingSelectedIds.includes(id)) {
          this.pendingSelectedIds.push(id);
        }
        if (!this.pendingSelectedMap[id]) {
          const record = this.pendingRows.find((row) => row.id === id);
          if (record) {
            this.$set(this.pendingSelectedMap, id, record);
          }
        }
      });
    },
    syncPendingTableSelection() {
      this.$nextTick(() => {
        if (this.$refs.pendingTable) {
          this.syncingPendingSelection = true;
          this.$refs.pendingTable.clearSelection();
          this.pendingRows.forEach((row) => {
            if (this.pendingSelectedIds.includes(row.id)) {
              this.$refs.pendingTable.toggleRowSelection(row, true);
            }
          });
          this.$nextTick(() => {
            this.syncingPendingSelection = false;
          });
        }
      });
    },
    handlePendingQueryChange() {
      this.pendingPage = 1;
      this.getWaitList();
    },
    handlePendingSizeChange(val) {
      this.pendingPageSize = val;
      this.pendingPage = 1;
      this.getWaitList();
    },
    handlePendingPageChange(val) {
      this.pendingPage = val;
      this.getWaitList();
    },
    handleBeforeSplitQueryChange() {
      this.beforeSplitPage = 1;
      this.getBeforeSplitList();
    },
    handleBeforeSplitSizeChange(val) {
      this.beforeSplitPageSize = val;
      this.beforeSplitPage = 1;
      this.getBeforeSplitList();
    },
    handleBeforeSplitPageChange(val) {
      this.beforeSplitPage = val;
      this.getBeforeSplitList();
    },
    handleBeforeSplitSelectionChange(selection) {
      if (this.syncingBeforeSplitSelection) return;
      // 获取当前页选中的ID
      const currentPageIds = selection.map((row) => row.id);
      // 获取当前页所有行的ID
      const currentPageAllIds = this.beforeSplitRows.map((row) => row.id);
      // 更新选中映射
      currentPageIds.forEach((id) => {
        const record =
          selection.find((row) => row.id === id) ||
          this.beforeSplitRows.find((row) => row.id === id);
        if (record) {
          this.$set(this.beforeSplitSelectedMap, id, record);
        }
      });
      currentPageAllIds.forEach((id) => {
        if (!currentPageIds.includes(id)) {
          if (this.beforeSplitSelectedIds.includes(id)) {
            const index = this.beforeSplitSelectedIds.indexOf(id);
            if (index > -1) {
              this.beforeSplitSelectedIds.splice(index, 1);
            }
          }
          if (this.beforeSplitSelectedMap[id]) {
            this.$delete(this.beforeSplitSelectedMap, id);
          }
        }
      });
      currentPageIds.forEach((id) => {
        if (!this.beforeSplitSelectedIds.includes(id)) {
          this.beforeSplitSelectedIds.push(id);
        }
        if (!this.beforeSplitSelectedMap[id]) {
          const record = this.beforeSplitRows.find((row) => row.id === id);
          if (record) {
            this.$set(this.beforeSplitSelectedMap, id, record);
          }
        }
      });
    },
    syncBeforeSplitTableSelection() {
      this.$nextTick(() => {
        if (this.$refs.beforeSplitTable) {
          this.syncingBeforeSplitSelection = true;
          this.$refs.beforeSplitTable.clearSelection();
          this.beforeSplitRows.forEach((row) => {
            if (this.beforeSplitSelectedIds.includes(row.id)) {
              this.$refs.beforeSplitTable.toggleRowSelection(row, true);
            }
          });
          this.$nextTick(() => {
            this.syncingBeforeSplitSelection = false;
          });
        }
      });
    },
    handlePaidQueryChange() {
      this.paidPage = 1;
      this.getPaidList();
    },
    handlePaidSizeChange(val) {
      this.paidPageSize = val;
      this.paidPage = 1;
      this.getPaidList();
    },
    handlePaidPageChange(val) {
      this.paidPage = val;
      this.getPaidList();
    },
    openSelectedPreview() {
      // 记录已存在的编辑值，便于重建时保留
      const editedMap = {};
      (this.selectedPreviewRows || []).forEach((r) => {
        editedMap[r.id] = { applyNum: r.applyNum, money: r.money };
      });

      // 按当前已选的待采购集合构建预览（始终以最新选择为准）
      const rows = this.pendingSelectedIds
        .map((id) => {
          if (!this.pendingSelectedMap[id]) {
            const record = this.pendingRows.find((row) => row.id === id);
            if (record) {
              this.$set(this.pendingSelectedMap, id, record);
            }
          }
          const rec = this.pendingSelectedMap[id];
          if (!rec) return null;
          // 合并保留之前在弹窗中编辑过的值
          const edited = editedMap[id];
          if (edited) {
            if (edited.applyNum !== undefined && edited.applyNum !== null)
              rec.applyNum = edited.applyNum;
            if (edited.money !== undefined && edited.money !== null)
              rec.money = edited.money;
          }
          return rec;
        })
        .filter(Boolean);
      this.selectedPreviewRows = rows;
      this.selectedPreviewSelection = rows.map((row) => row.id);
      this.selectedPreviewSource = "pending";
      this.selectedPreviewVisible = true;
      this.$nextTick(() => {
        if (this.$refs.previewTable) {
          this.syncingPreviewSelection = true;
          this.$refs.previewTable.clearSelection();
          this.selectedPreviewRows.forEach((row) => {
            if (this.selectedPreviewSelection.includes(row.id)) {
              this.$refs.previewTable.toggleRowSelection(row, true);
            }
          });
          this.$nextTick(() => {
            this.syncingPreviewSelection = false;
          });
        }
      });
    },
    openSelectedPreviewBeforeSplit() {
      // 记录已存在的编辑值，便于重建时保留
      const editedMap = {};
      (this.selectedPreviewRows || []).forEach((r) => {
        editedMap[r.id] = { applyNum: r.applyNum, money: r.money };
      });

      // 按当前已选的明细拆分前集合构建预览（始终以最新选择为准）
      const rows = this.beforeSplitSelectedIds
        .map((id) => {
          if (!this.beforeSplitSelectedMap[id]) {
            const record = this.beforeSplitRows.find((row) => row.id === id);
            if (record) {
              this.$set(this.beforeSplitSelectedMap, id, record);
            }
          }
          const rec = this.beforeSplitSelectedMap[id];
          if (!rec) return null;
          // 合并保留之前在弹窗中编辑过的值
          const edited = editedMap[id];
          if (edited) {
            if (edited.applyNum !== undefined && edited.applyNum !== null)
              rec.applyNum = edited.applyNum;
            if (edited.money !== undefined && edited.money !== null)
              rec.money = edited.money;
          }
          return rec;
        })
        .filter(Boolean);
      this.selectedPreviewRows = rows;
      this.selectedPreviewSelection = rows.map((row) => row.id);
      this.selectedPreviewSource = "beforeSplit";
      this.selectedPreviewVisible = true;
      this.$nextTick(() => {
        if (this.$refs.previewTable) {
          this.syncingPreviewSelection = true;
          this.$refs.previewTable.clearSelection();
          this.selectedPreviewRows.forEach((row) => {
            if (this.selectedPreviewSelection.includes(row.id)) {
              this.$refs.previewTable.toggleRowSelection(row, true);
            }
          });
          this.$nextTick(() => {
            this.syncingPreviewSelection = false;
          });
        }
      });
    },
    handleSelectedPreviewSelectionChange(selection) {
      if (this.syncingPreviewSelection) return;
      this.selectedPreviewSelection = selection.map((row) => row.id);
    },
    confirmSelectedPreview() {
      const selectedRows = this.selectedPreviewRows.filter((row) =>
        this.selectedPreviewSelection.includes(row.id)
      );
      if (selectedRows.length === 0) {
        this.$message.warning("请至少勾选一条明细");
        return;
      }

      // 校验数量
      const invalidRows = [];
      selectedRows.forEach((row) => {
        const applyNum = Number(row.applyNum) || 0;
        const paidNum = Number(row.paidNum) || 0;
        const total = Number(row.total) || 0;
        if (applyNum === 0) {
          invalidRows.push({ row, reason: "本次报销数量不能为0" });
        } else if (applyNum + paidNum > total) {
          invalidRows.push({ row, reason: "本次报销数量大于剩余可报销数量" });
        }
      });
      if (invalidRows.length > 0) {
        const errorMessages = invalidRows
          .map((item) => `${item.row.itemName || "未知项目"}：${item.reason}`)
          .join("；");
        this.$message.warning(`以下数据不符合条件：${errorMessages}`);
        this.$nextTick(() => {
          this.$forceUpdate();
        });
        return;
      }

      // 同步选择状态（根据数据来源更新对应的选择状态）
      const newIds = [...this.selectedPreviewSelection];
      if (this.selectedPreviewSource === "pending") {
        this.pendingSelectedIds = newIds;
        const newMap = {};
        newIds.forEach((id) => {
          const record =
            this.selectedPreviewRows.find((row) => row.id === id) ||
            this.pendingSelectedMap[id] ||
            this.pendingRows.find((row) => row.id === id);
          if (record) newMap[id] = record;
        });
        this.pendingSelectedMap = { ...newMap };
      } else if (this.selectedPreviewSource === "beforeSplit") {
        this.beforeSplitSelectedIds = newIds;
        const newMap = {};
        newIds.forEach((id) => {
          const record =
            this.selectedPreviewRows.find((row) => row.id === id) ||
            this.beforeSplitSelectedMap[id] ||
            this.beforeSplitRows.find((row) => row.id === id);
          if (record) newMap[id] = record;
        });
        this.beforeSplitSelectedMap = { ...newMap };
      }

      // 组装并跳转
      const titleParts = selectedRows.map(
        (r) => `${r.itemName || ""}*${Number(r.applyNum) || 0}`
      );
      const zhifutitle = `${titleParts.join(",")}${
        titleParts.length ? "," : ""
      }`;
      const xiangxishuoming = zhifutitle;

      const contractIdSet = Array.from(
        new Set(
          selectedRows
            .map((r) => r?.yibancaigou?.flow?.out_contract_id)
            .filter(Boolean)
        )
      );
      const contractIdsStr = contractIdSet.join(",");
      const contract_id = contractIdsStr;
      const amt = selectedRows.reduce(
        (sum, r) => sum + (Number(r.money) || 0),
        0
      );

      const proceed = async () => {
        let yifujine = 0;
        let cishu = 0;
        try {
          const fundRes = await getFundLog({
            contract_id: contractIdsStr,
            show_type: 1,
          });
          const payments = fundRes?.data || [];
          const actNumsTotal = () =>
            payments.reduce(
              (pre, cur) =>
                pre + (Number(cur?.act_money) ? Number(cur.act_money) : 0),
              0
            );
          yifujine = actNumsTotal();
          cishu = Array.isArray(payments) ? payments.length : 0;
        } catch (e) {}

        let xiangmuzonge = 0;
        let zhifucishu = 0;
        let liezhiqudao = "";
        let contractno = "";
        let guanlianliucheng = "";
        try {
          let contracts = [];
          if (contractIdSet.length > 0) {
            contracts = await Promise.all(
              contractIdSet.map((id) => detailContract({ id }))
            );
          }
          const sumMoney = (contracts || []).reduce(
            (sum, c) => sum + (Number(c?.money) || 0),
            0
          );
          const sumPlanLen = (contracts || []).reduce(
            (sum, c) => sum + (c?.sign_plan?.length || 0),
            0
          );
          const plansNames = Array.from(
            new Set(
              (contracts || [])
                .flatMap((c) => (c?.plans || []).map((p) => p?.name))
                .filter(Boolean)
            )
          ).join(",");
          const contractNos = (contracts || [])
            .map((c) => c?.number)
            .filter(Boolean)
            .join(",");
          const relatedFlows = Array.from(
            new Set(
              (contracts || [])
                .flatMap((c) =>
                  (c?.contract_flow_links || []).map((l) => l?.flow_id)
                )
                .filter(Boolean)
            )
          ).join(",");
          xiangmuzonge = sumMoney;
          zhifucishu = sumPlanLen;
          liezhiqudao = plansNames;
          contractno = contractNos;
          guanlianliucheng = relatedFlows;
        } catch (e) {}

        const wuzicaigou_items = selectedRows.map((r) => ({
          flow_id: r?.yibancaigou?.flow?.id,
          contract_id: r?.yibancaigou?.flow?.out_contract_id,
          wuzicaigou_id: r?.yibancaigou?.id,
          wuzicaigou_item_id: r?.id,
          name: r?.itemName,
          num: Number(r?.applyNum) || 0,
          total: Number(r?.num) || 0,
          apply_money: Number(r?.money) || 0,
          money: Number(r?.money) || 0,
          is_receive: 0,
        }));

        const baseInfo = {
          zhifutitle,
          contract_id,
          amt,
          xiangxishuoming,
          yifujine,
          cishu,
          xiangmuzonge,
          zhifucishu,
          liezhiqudao,
          contractno,
          guanlianliucheng,
          wuzicaigou_items,
        };

        this.selectedPreviewVisible = false;
        const url = `/flow/create?&module_name=oa&isSinglePage=1&module_id=75&default_json=${window.encodeURIComponent(
          JSON.stringify(baseInfo)
        )}`;
        this.$router.push(url);
      };

      proceed();
    },
    closeSelectedPreview() {
      // 仅关闭弹窗，不清空勾选与已编辑数据
      this.selectedPreviewVisible = false;
    },
    async getWaitList() {
      const params = {
        page: this.pendingPage,
        page_size: this.pendingPageSize,
        is_before: 0, // 待采购传 0
      };
      if (this.pendingQuery.creator_department_id) {
        params.creator_department_id = this.pendingQuery.creator_department_id;
      }
      if (this.pendingQuery.created_by) {
        params.created_by = this.pendingQuery.created_by;
      }
      if (this.pendingQuery.keywords) {
        params.keywords = this.pendingQuery.keywords;
      }
      if (this.pendingQuery.chengbanren_id) {
        params.chengbanren_id = this.pendingQuery.chengbanren_id;
      }
      if (this.pendingQuery.caigouneirong) {
        params.caigouneirong = this.pendingQuery.caigouneirong;
      }
      const res = await waitList(params);
      this.waitList = res.data || [];
      this.pendingTotal = res.total || 0;
      // 映射数据到表格字段
      this.pendingRows = (res.data || []).map((item) => ({
        ...item, // 保留原始数据，方便后续使用
        checked: false,
        applicant: item.yibancaigou?.flow?.creator?.name || "",
        department: item.yibancaigou?.flow?.creator_department?.name || "",
        flowTitle: item.yibancaigou?.flow?.title || "",
        purchaseContent: item.yibancaigou?.caigouneirong || "",
        purchaser:
          item.yibancaigou?.flow?.logs && item.yibancaigou.flow.logs.length > 0
            ? item.yibancaigou.flow.logs[0]?.user?.name || ""
            : "",
        isContractFlow: item.yibancaigou?.flow?.contract_flow ? "是" : "否",
        paidNum: item.fund_log_wuzicaigou_items_sum_num || 0,
        total: item.num || 0,
        itemName: item.pinminghuofuwuxuqiu || "",
        model: item.xinghao || "",
        origin: item.chandi || "",
        unit: item.danwei || "",
        purpose: item.yongtu || "",
        applyNum: null, // 本次报销数量，由用户输入
        money: null, // 付款金额，由用户输入
        shifouqingdan: item.shifouqingdan || "",
        shifoubijia: item.shifoubijia || "",
        shifoufahuo: item.shifoufahuo || "",
      }));
      this.pendingRows.forEach((row) => {
        if (this.pendingSelectedIds.includes(row.id)) {
          this.$set(this.pendingSelectedMap, row.id, row);
        }
      });
      // 不再移除之前选择的项，保持跨查询选择
      this.syncPendingTableSelection();
    },
    async getBeforeSplitList() {
      const params = {
        page: this.beforeSplitPage,
        page_size: this.beforeSplitPageSize,
        is_before: 1, // 明细拆分前传 1
      };
      if (this.beforeSplitQuery.creator_department_id) {
        params.creator_department_id = this.beforeSplitQuery.creator_department_id;
      }
      if (this.beforeSplitQuery.created_by) {
        params.created_by = this.beforeSplitQuery.created_by;
      }
      if (this.beforeSplitQuery.keywords) {
        params.keywords = this.beforeSplitQuery.keywords;
      }
      if (this.beforeSplitQuery.chengbanren_id) {
        params.chengbanren_id = this.beforeSplitQuery.chengbanren_id;
      }
      if (this.beforeSplitQuery.caigouneirong) {
        params.caigouneirong = this.beforeSplitQuery.caigouneirong;
      }
      const res = await waitList(params);
      this.beforeSplitTotal = res.total || 0;
      // 映射数据到表格字段
      this.beforeSplitRows = (res.data || []).map((item) => ({
        ...item, // 保留原始数据，方便后续使用
        checked: false,
        applicant: item.yibancaigou?.flow?.creator?.name || "",
        department: item.yibancaigou?.flow?.creator_department?.name || "",
        flowTitle: item.yibancaigou?.flow?.title || "",
        purchaseContent: item.yibancaigou?.caigouneirong || "",
        purchaser:
          item.yibancaigou?.flow?.logs && item.yibancaigou.flow.logs.length > 0
            ? item.yibancaigou.flow.logs[0]?.user?.name || ""
            : "",
        isContractFlow: item.yibancaigou?.flow?.contract_flow ? "是" : "否",
        paidNum: item.fund_log_wuzicaigou_items_sum_num || 0,
        total: item.num || 0,
        itemName: item.pinminghuofuwuxuqiu || "",
        model: item.xinghao || "",
        origin: item.chandi || "",
        unit: item.danwei || "",
        purpose: item.yongtu || "",
        applyNum: null, // 本次报销数量，由用户输入
        money: null, // 付款金额，由用户输入
        shifouqingdan: item.shifouqingdan || "",
        shifoubijia: item.shifoubijia || "",
        shifoufahuo: item.shifoufahuo || "",
      }));
      this.beforeSplitRows.forEach((row) => {
        if (this.beforeSplitSelectedIds.includes(row.id)) {
          this.$set(this.beforeSplitSelectedMap, row.id, row);
        }
      });
      // 不再移除之前选择的项，保持跨查询选择
      this.syncBeforeSplitTableSelection();
    },
    async getPaidList() {
      const params = {
        page: this.paidPage,
        page_size: this.paidPageSize,
      };
      if (this.paidQuery.creator_department_id) {
        params.creator_department_id = this.paidQuery.creator_department_id;
      }
      if (this.paidQuery.created_by) {
        params.created_by = this.paidQuery.created_by;
      }
      if (this.paidQuery.keywords) {
        params.keywords = this.paidQuery.keywords;
      }
      if (this.paidQuery.chengbanren_id) {
        params.chengbanren_id = this.paidQuery.chengbanren_id;
      }
      if (this.paidQuery.caigouneirong) {
        params.caigouneirong = this.paidQuery.caigouneirong;
      }
      if (this.paidQuery.status || this.paidQuery.status === 0) {
        params.status = this.paidQuery.status?1:0;
      }
      const res = await receiveList(params);
      this.paidTotal = res.total || 0;
      this.paidRows = (res.data || []).map((item) => ({
        ...item,
        applicant: item.yibancaigou?.flow?.creator?.name || "",
        department: item.yibancaigou?.flow?.creator_department?.name || "",
        flowTitle: item.yibancaigou?.flow?.title || "",
        purchaseContent: item.yibancaigou?.caigouneirong || "",
        purchaser:
          item.yibancaigou?.flow?.logs && item.yibancaigou.flow.logs.length > 0
            ? item.yibancaigou.flow.logs[0]?.user?.name || ""
            : "",
        isContractFlow: item.yibancaigou?.flow?.contract_flow ? "是" : "否",
        paidNum: item.num || 0,
        money: item.money || 0,
        total: item.caigoumingxi?.num || 0,
        itemName: item.caigoumingxi?.pinminghuofuwuxuqiu || "",
        model: item.caigoumingxi?.xinghao || "",
        origin: item.caigoumingxi?.chandi || "",
        unit: item.caigoumingxi?.danwei || "",
        purpose: item.caigoumingxi?.yongtu || "",
        shifouqingdan: item.shifouqingdan || "",
        shifoubijia: item.shifoubijia || "",
        shifoufahuo: item.shifoufahuo || "",
      }));
    },
  },
  watch: {
    isShowModal(newVal) {
      if (newVal) {
      } else {
        this.modalUrl = "";
      }
    },
    activeTab(newTab, oldTab) {
      // 重置分页参数
      if (newTab === "pending") {
        this.pendingPage = 1;
        this.pendingPageSize = 10;
      } else if (newTab === "beforeSplit") {
        this.beforeSplitPage = 1;
        this.beforeSplitPageSize = 10;
      } else if (newTab === "paid") {
        this.paidPage = 1;
        this.paidPageSize = 10;
      }

      // 重置查询条件
      if (newTab === "pending") {
        this.pendingQuery = {
          creator_department_id: "",
          created_by: "",
          keywords: "",
          chengbanren_id: "",
          caigouneirong: "",
        };
        this.pendingSelectedIds = [];
        this.pendingSelectedMap = {};
      } else if (newTab === "beforeSplit") {
        this.beforeSplitQuery = {
          creator_department_id: "",
          created_by: "",
          keywords: "",
          chengbanren_id: "",
          caigouneirong: "",
        };
        this.beforeSplitSelectedIds = [];
        this.beforeSplitSelectedMap = {};
      } else if (newTab === "paid") {
        this.paidQuery = {
          creator_department_id: "",
          created_by: "",
          keywords: "",
          chengbanren_id: "",
          caigouneirong: "",
          status: "",
        };
      }

      // 清空所有表格的选中项（使用双重 nextTick 确保表格已渲染）
      this.$nextTick(() => {
        this.$nextTick(() => {
          if (this.$refs.pendingTable) {
            this.$refs.pendingTable.clearSelection();
          }
          if (this.$refs.beforeSplitTable) {
            this.$refs.beforeSplitTable.clearSelection();
          }
        });
      });

      // 加载对应标签页的数据
      if (newTab === "paid") {
        this.getPaidList();
      } else if (newTab === "pending") {
        // 切换到待采购时也重新加载数据，确保状态正确
        this.getWaitList();
      } else if (newTab === "beforeSplit") {
        // 切换到明细拆分前时重新加载数据
        this.getBeforeSplitList();
      }
    },
    // 关闭弹窗不清空已选择的数据
  },
  mounted() {
    this.getDepartmentList();
    this.getWaitList();
    this.getUserList();
  },
};
</script>

<style scoped>
.icon-space {
  margin-right: 6px;
}

.selected-info {
  margin-left: 12px;
  color: #666;
}

.selected-info.is-clickable {
  cursor: pointer;
  color: #409eff;
}

.selected-info.is-clickable:hover {
  text-decoration: underline;
}

.selected-count {
  color: #409eff;
  margin: 0 2px;
}

::v-deep .error-input .el-input__inner {
  border-color: #f56c6c !important;
}

::v-deep .error-input:hover .el-input__inner {
  border-color: #f56c6c !important;
}

::v-deep .error-input .el-input__inner:focus {
  border-color: #f56c6c !important;
}
</style>

