<template>
  <div class="p-2 h-full flex flex-col">
    <!-- 主体布局：左右分栏 -->
    <el-card shadow="never" class="flex-1 overflow-hidden">
      <div class="flex h-full" style="min-height: 600px">
        <!-- 左侧：回款信息（可展开/收缩） -->
        <div
          :class="[
            'transition-all duration-300 relative border-r border-gray-200 flex flex-col min-w-0 shrink-0',
            leftCollapsed ? 'w-12' : 'flex-[3]'
          ]"
        >
          <!-- 左侧头部 -->
          <div class="panel-head">
            <el-button link @click="leftCollapsed = !leftCollapsed">
              <el-icon :class="leftCollapsed ? 'rotate-180' : ''">
                <DArrowLeft />
              </el-icon>
            </el-button>
            <span v-show="!leftCollapsed" class="panel-head__title">回款信息</span>
          </div>

          <!-- 左侧内容区 -->
          <div v-show="!leftCollapsed" class="flex-1 flex flex-col overflow-hidden">
            <!-- 搜索区域 -->
            <div class="p-3 border-b border-gray-100">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px" class="mb-0">
                <el-form-item label="客户名称" prop="customerName" class="mb-2">
                  <el-select
                    v-model="queryParams.customerName"
                    placeholder="请选择客户名称"
                    filterable
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                  >
                    <el-option
                      v-for="item in customerInfoList"
                      :key="item.customerId"
                      :label="item.customerName"
                      :value="item.customerName"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="分款进度" prop="installmentStatus" class="mb-2">
                  <el-select v-model="queryParams.installmentStatus" placeholder="请选择分款进度" clearable >
                    <el-option v-for="dict in installment_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item class="mb-2">
                  <el-button type="primary" @click="handleQuery">搜索</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 回款列表 -->
            <div class="flex-1 flex flex-col overflow-hidden px-2 pb-2">
              <div class="installment-toolbar">
                <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handleAddInstallment"
                  v-hasPermi="['oa/erp:finAccountInstallment:add']"
                >
                  新增
                </el-button>
                <el-button
                  type="warning"
                  plain
                  icon="Upload"
                  @click="upload.open = true"
                  v-hasPermi="['oa/erp:finAccountInstallment:import']"
                >
                  导入
                </el-button>
                <el-button
                  type="success"
                  plain
                  icon="Promotion"
                  :disabled="!canDispatchSelection"
                  @click="openDispatchDialog()"
                  v-hasPermi="['oa/erp:finAccountInstallment:dispatch']"
                >
                  派发客户经理
                </el-button>
                <span v-if="selectedInstallmentRows.length" class="installment-toolbar__hint">
                  已选 {{ selectedInstallmentRows.length }} 条
                </span>
              </div>
              <div class="flex-1 overflow-auto min-h-0">
              <el-table
                v-loading="loading"
                :data="finAccountInstallmentList"
                highlight-current-row
                @row-click="handleRowClick"
                @selection-change="handleInstallmentSelectionChange"
                :row-class-name="getRowClassName"
                border
                size="small"
              >
                <el-table-column type="selection" width="42" align="center" :selectable="isRowSelectable" />
                <el-table-column label="回款编号" align="center" prop="installmentCode" min-width="120"/>
                <el-table-column label="客户名称" align="center" prop="customerName" min-width="150"  />
                <el-table-column label="回款金额" align="center" prop="paymentAmount" min-width="100">
                  <template #default="{ row }">
                    <span class="font-medium">¥{{ formatMoney(row.paymentAmount) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="回款日期" align="center" prop="paymentDate" min-width="110">
                  <template #default="{ row }">
                    {{ parseTime(row.paymentDate, '{y}-{m}-{d}') }}
                  </template>
                </el-table-column>
                <el-table-column label="分款进度" align="center" prop="installmentStatus" min-width="96">
                  <template #default="scope">
                    <dict-tag :options="installment_status" :value="scope.row.installmentStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="客户经理" align="center" prop="managerNickNames" min-width="120" show-overflow-tooltip />
                <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="120">
                  <template #default="{ row }">
                    <template v-if="row.installmentStatus === INSTALLMENT_STATUS_NOT_ALLOCATED">
                      <el-tooltip content="修改" placement="top">
                        <el-button
                          link
                          type="primary"
                          icon="Edit"
                          @click.stop="handleUpdate(row)"
                          v-hasPermi="['oa/erp:finAccountInstallment:edit']"
                        />
                      </el-tooltip>
                      <el-tooltip content="删除" placement="top">
                        <el-button
                          link
                          type="danger"
                          icon="Delete"
                          @click.stop="handleDelete(row)"
                          v-hasPermi="['oa/erp:finAccountInstallment:remove']"
                        />
                      </el-tooltip>
                      <el-tooltip content="派发客户经理" placement="top">
                        <el-button
                          link
                          type="warning"
                          icon="Promotion"
                          @click.stop="openDispatchDialog([row])"
                          v-hasPermi="['oa/erp:finAccountInstallment:dispatch']"
                        />
                      </el-tooltip>
                    </template>
                    <el-tooltip
                      v-else
                      content="查看详情"
                      placement="top"
                    >
                      <el-button link type="info" icon="DocumentChecked" @click.stop="handleView(row)" />
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
              </div>

              <!-- 分页 -->
              <div class="flex justify-end mt-2 shrink-0">
                <pagination
                  v-show="total > 0"
                  :total="total"
                  v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize"
                  @pagination="getList"
                  small
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：分款明细 -->
        <div class="detail-panel flex-[2] min-w-0 flex flex-col overflow-hidden">
          <div class="detail-panel__header">
            <div class="detail-panel__header-main">
              <div>
                <div class="detail-panel__title">分款明细</div>
                <div v-if="selectedInstallment" class="detail-panel__meta">
                  <span class="detail-panel__code">{{ selectedInstallment.installmentCode }}</span>
                  <span class="detail-panel__divider">·</span>
                  <span class="detail-panel__customer">{{ selectedInstallment.customerName }}</span>
                </div>
                <div v-else class="detail-panel__placeholder">请从左侧选择一条回款记录</div>
              </div>
            </div>
          </div>

          <div class="detail-panel__body">
            <template v-if="selectedInstallment">
              <div class="detail-summary">
                <div class="detail-summary__card detail-summary__card--primary">
                  <div class="detail-summary__label">回款金额</div>
                  <div class="detail-summary__value">¥{{ formatMoney(selectedInstallment.paymentAmount) }}</div>
                </div>
                <div class="detail-summary__card detail-summary__card--allocated">
                  <div class="detail-summary__label">已分款</div>
                  <div class="detail-summary__value">¥{{ formatMoney(allocatedAmount) }}</div>
                </div>
                <div
                  class="detail-summary__card"
                  :class="remainingAmount < 0 ? 'detail-summary__card--danger' : 'detail-summary__card--remain'"
                >
                  <div class="detail-summary__label">剩余可分</div>
                  <div class="detail-summary__value">¥{{ formatMoney(remainingAmount) }}</div>
                </div>
              </div>

              <div v-if="allocatePercent >= 0" class="detail-progress">
                <div class="detail-progress__text">
                  <span>分款进度</span>
                  <span>{{ allocatePercent }}%</span>
                </div>
                <el-progress
                  :percentage="allocatePercent"
                  :status="allocateProgressStatus"
                  :stroke-width="8"
                  :show-text="false"
                />
              </div>

              <el-alert
                v-if="isAmountExceeded"
                title="分款金额超出回款金额"
                type="error"
                :closable="false"
                class="detail-alert"
                show-icon
              >
                <template #default>
                  已超出 ¥{{ formatMoney(Math.abs(remainingAmount)) }}，请调整分款明细
                </template>
              </el-alert>
              <el-alert
                v-else-if="isAmountInsufficient"
                type="warning"
                :closable="false"
                class="detail-alert detail-alert--compact"
                show-icon
              >
                <template #title>
                  <span class="detail-alert-compact__text">还差 ¥{{ formatMoney(remainingAmount) }} 未分配</span>
                </template>
              </el-alert>

              <div class="detail-table-section">
                <div class="detail-table-section__head">
                  <span class="detail-table-section__title">明细列表</span>
                  <span class="detail-table-section__count">共 {{ detailCount }} 条</span>
                </div>
                <el-table
                  v-if="detailLoading || detailCount > 0"
                  v-loading="detailLoading"
                  :data="finAccountInstallmentDetailList"
                  border
                  stripe
                  size="small"
                  class="detail-table"
                >
                  <el-table-column label="项目" align="center" min-width="140" show-overflow-tooltip>
                    <template #default="{ row }">
                      <div class="detail-cell-project">
                        <span class="detail-cell-project__code">{{ row.projectCode || '—' }}</span>
                        <span class="detail-cell-project__name">{{ row.projectName || '—' }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="合同" align="center" min-width="140" show-overflow-tooltip>
                    <template #default="{ row }">
                      <div class="detail-cell-project">
                        <span class="detail-cell-project__code">{{ row.contractCode || '—' }}</span>
                        <span class="detail-cell-project__name">{{ row.contractName || '—' }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="阶段" align="center" prop="stageName" width="88" show-overflow-tooltip />
                  <el-table-column label="分款金额" align="center" width="108">
                    <template #default="{ row }">
                      <span class="detail-amount">¥{{ formatMoney(row.detailAmount) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" align="center" prop="remark" min-width="80" show-overflow-tooltip />
                </el-table>
                <el-empty
                  v-if="!detailLoading && detailCount === 0"
                  :image-size="72"
                  description="暂无分款明细"
                  class="detail-empty"
                >
                  <template #description>
                    <p class="detail-empty__desc">暂无分款明细</p>
                  </template>
                </el-empty>
              </div>
            </template>

            <el-empty v-else :image-size="88" description="请选择左侧回款记录" class="detail-panel__empty" />
          </div>
        </div>
      </div>
    </el-card>

    <!-- Excel导入对话框 -->
    <el-dialog title="导入Excel" v-model="upload.open" width="600px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="upload.open = false">取 消</el-button>
          <el-button :loading="upload.isUploading" type="primary" @click="submitImport">确定导入</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/修改回款 -->
    <el-dialog
      :title="installmentDialog.title"
      v-model="installmentDialog.visible"
      width="480px"
      append-to-body
      @closed="resetInstallmentForm"
    >
      <el-form
        :key="installmentFormKey"
        ref="installmentFormRef"
        :model="installmentForm"
        :rules="installmentRules"
        label-width="100px"
      >
        <el-form-item label="客户名称" prop="customerName">
          <el-select v-model="installmentForm.customerName" placeholder="请选择客户名称" filterable clearable style="width: 100%">
            <el-option
              v-for="item in customerInfoList"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="回款金额" prop="paymentAmount">
          <el-input-number v-model="installmentForm.paymentAmount" :precision="2" :min="0.01" style="width: 100%" controls-position="right" />
        </el-form-item>
        <el-form-item label="回款日期" prop="paymentDate">
          <el-date-picker v-model="installmentForm.paymentDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择回款日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="installmentForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="installmentDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="installmentDialog.loading" @click="submitInstallmentForm">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 派发客户经理 -->
    <el-dialog title="派发客户经理" v-model="dispatchDialog.visible" width="720px" append-to-body>
      <p class="text-sm text-gray-600 mb-2">已选 {{ selectedInstallmentRows.length }} 条未分款回款：</p>
      <el-table :data="selectedInstallmentRows" border size="small" max-height="220" class="mb-4">
        <el-table-column label="回款编号" align="center" prop="installmentCode" width="120" show-overflow-tooltip />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="120" show-overflow-tooltip />
        <el-table-column label="回款金额" align="center" width="110">
          <template #default="{ row }">
            <span class="font-medium">¥{{ formatMoney(row.paymentAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回款日期" align="center" width="100">
          <template #default="{ row }">
            {{ parseTime(row.paymentDate, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
      </el-table>
      <el-form label-width="88px">
        <el-form-item label="客户经理" required>
          <el-select
            v-model="dispatchManagerUserIds"
            multiple
            filterable
            clearable
            placeholder="请选择客户经理（可多选）"
            style="width: 100%"
          >
            <el-option v-for="u in managerUserOptions" :key="u.userId" :label="u.nickName" :value="u.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dispatchDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="dispatchDialog.loading" @click="submitDispatch">确认派发</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="FinAccountInstallment" lang="ts">
import {
  listFinAccountInstallment,
  addFinAccountInstallment,
  updateFinAccountInstallment,
  delFinAccountInstallment,
  dispatchFinAccountInstallment
} from '@/api/oa/erp/finAccountInstallment';
import { getErpFinAccountInstallmentDetailList } from '@/api/oa/erp/finAccountInstallmentDetail';
import {
  FinAccountInstallmentForm,
  FinAccountInstallmentQuery,
  FinAccountInstallmentVO,
  FinAccountInstallmentDispatchForm
} from '@/api/oa/erp/finAccountInstallment/types';
import { FinAccountInstallmentDetailVO } from '@/api/oa/erp/finAccountInstallmentDetail/types';
import { DArrowLeft } from '@element-plus/icons-vue';
import { getUserList } from '@/api/system/user';
import type { UserVO } from '@/api/system/user/types';
import { globalHeaders } from '@/utils/request';
import { parseTime } from '@/utils/ruoyi';
import { getCrmCustomerInfoList } from '@/api/oa/crm/customerInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const { installment_status } = toRefs<any>(proxy?.useDict('installment_status'));

// 左侧回款列表
const finAccountInstallmentList = ref<FinAccountInstallmentVO[]>([]);
const loading = ref(true);
const total = ref(0);
const leftCollapsed = ref(false);
const selectedInstallment = ref<FinAccountInstallmentVO | null>(null);
const selectedInstallmentRows = ref<FinAccountInstallmentVO[]>([]);

const queryParams = reactive<FinAccountInstallmentQuery>({
  pageNum: 1,
  pageSize: 10,
  customerName: undefined,
  installmentStatus: undefined
});
const queryFormRef = ref<ElFormInstance>();

// 右侧分款明细
const finAccountInstallmentDetailList = ref<FinAccountInstallmentDetailVO[]>([]);
const detailLoading = ref(false);

const allocatedAmount = computed(() =>
  Number((finAccountInstallmentDetailList.value || []).reduce((sum, item) => sum + Number(item.detailAmount || 0), 0))
);

const remainingAmount = computed(() => {
  if (!selectedInstallment.value) return 0;
  return Number(selectedInstallment.value.paymentAmount || 0) - allocatedAmount.value;
});

const detailCount = computed(() => finAccountInstallmentDetailList.value?.length ?? 0);

const isAmountExceeded = computed(() => remainingAmount.value < 0);

const isAmountInsufficient = computed(() => remainingAmount.value > 0);

const allocatePercent = computed(() => {
  const total = Number(selectedInstallment.value?.paymentAmount || 0);
  if (total <= 0) return 0;
  const pct = Math.round((allocatedAmount.value / total) * 100);
  return Math.min(pct, 100);
});

const allocateProgressStatus = computed(() => {
  if (isAmountExceeded.value) return 'exception';
  if (allocatePercent.value >= 100) return 'success';
  return undefined;
});

const uploadRef = ref();

const formatMoney = (money: number | undefined | null) => {
  if (money === undefined || money === null) return '0.00';
  return money.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const INSTALLMENT_STATUS_NOT_ALLOCATED = '0';

/** 是否未分款（installment_status = 0） */
const isNotAllocated = (row: FinAccountInstallmentVO) => row.installmentStatus === INSTALLMENT_STATUS_NOT_ALLOCATED;

const canDispatchSelection = computed(
  () => selectedInstallmentRows.value.length > 0 && selectedInstallmentRows.value.every(isNotAllocated)
);

const installmentDialog = reactive({ visible: false, loading: false, title: '新增回款' });
const installmentFormRef = ref<ElFormInstance>();
const installmentFormKey = ref(0);
const getDefaultInstallmentForm = (): FinAccountInstallmentForm => ({
  accountInstallmentId: undefined,
  customerName: undefined,
  paymentAmount: undefined,
  paymentDate: undefined,
  remark: undefined,
  currency: 'CNY'
});
const installmentForm = reactive<FinAccountInstallmentForm>(getDefaultInstallmentForm());
/** 客户下拉（选项值存客户名称） */
const customerInfoList = ref<any[]>([]);
const getCustomerInfoListSelect = async () => {
  const res = await getCrmCustomerInfoList(null as any);
  customerInfoList.value = res.data || [];
};

const installmentRules = {
  customerName: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
  paymentAmount: [{ required: true, message: '请输入回款金额', trigger: 'blur' }],
  paymentDate: [{ required: true, message: '请选择回款日期', trigger: 'change' }]
};

const dispatchDialog = reactive({ visible: false, loading: false });
const dispatchManagerUserIds = ref<Array<string | number>>([]);
const managerUserOptions = ref<UserVO[]>([]);
const managerUserOptionsLoaded = ref(false);

const loadManagerUserOptions = async () => {
  if (managerUserOptionsLoaded.value) return;
  const res = await getUserList({} as any);
  managerUserOptions.value = res.data || [];
  managerUserOptionsLoaded.value = true;
};

const isRowSelectable = (row: FinAccountInstallmentVO) => isNotAllocated(row);

const handleInstallmentSelectionChange = (rows: FinAccountInstallmentVO[]) => {
  selectedInstallmentRows.value = rows;
};

const resetInstallmentForm = () => {
  Object.assign(installmentForm, getDefaultInstallmentForm());
};

const handleAddInstallment = async () => {
  resetInstallmentForm();
  installmentFormKey.value++;
  installmentDialog.title = '新增回款';
  installmentDialog.visible = true;
  await nextTick();
  installmentFormRef.value?.clearValidate();
};

/** 修改未分款回款 */
const handleUpdate = async (row: FinAccountInstallmentVO) => {
  if (!isNotAllocated(row)) {
    proxy?.$modal.msgWarning('仅未分款状态的回款可修改');
    return;
  }
  resetInstallmentForm();
  Object.assign(installmentForm, {
    accountInstallmentId: row.accountInstallmentId,
    customerName: row.customerName,
    paymentAmount: row.paymentAmount,
    paymentDate: row.paymentDate,
    remark: row.remark,
    currency: row.currency || 'CNY'
  });
  installmentDialog.title = '修改回款';
  installmentDialog.visible = true;
  await nextTick();
  installmentFormRef.value?.clearValidate();
};

const submitInstallmentForm = async () => {
  const valid = await installmentFormRef.value?.validate();
  if (!valid) return;
  installmentDialog.loading = true;
  const isEdit = !!installmentForm.accountInstallmentId;
  try {
    if (isEdit) {
      await updateFinAccountInstallment(installmentForm);
      proxy?.$modal.msgSuccess('修改成功');
    } else {
      await addFinAccountInstallment(installmentForm);
      proxy?.$modal.msgSuccess('新增成功');
    }
    installmentDialog.visible = false;
    const selectedId = selectedInstallment.value?.accountInstallmentId;
    await getList();
    if (isEdit && selectedId === installmentForm.accountInstallmentId) {
      const updated = finAccountInstallmentList.value.find((item) => item.accountInstallmentId === selectedId);
      if (updated) {
        selectedInstallment.value = updated;
        await getDetailList();
      }
    }
  } finally {
    installmentDialog.loading = false;
  }
};

/** 删除单条未分款回款 */
const handleDelete = async (row: FinAccountInstallmentVO) => {
  if (!isNotAllocated(row)) {
    proxy?.$modal.msgWarning('仅未分款状态的回款可删除');
    return;
  }
  await proxy?.$modal.confirm(`是否确认删除回款编号为「${row.installmentCode}」的数据？`);
  await delFinAccountInstallment(row.accountInstallmentId);
  proxy?.$modal.msgSuccess('删除成功');
  if (selectedInstallment.value?.accountInstallmentId === row.accountInstallmentId) {
    selectedInstallment.value = null;
    finAccountInstallmentDetailList.value = [];
  }
  selectedInstallmentRows.value = selectedInstallmentRows.value.filter(
    (item) => item.accountInstallmentId !== row.accountInstallmentId
  );
  await getList();
};

/** 打开派发弹窗（批量勾选或操作列单条） */
const openDispatchDialog = async (rows?: FinAccountInstallmentVO[]) => {
  const targetRows = rows ?? selectedInstallmentRows.value;
  if (!targetRows.length || !targetRows.every(isNotAllocated)) {
    proxy?.$modal.msgWarning(
      rows?.length ? '仅未分款状态的回款可派发' : '请勾选分款进度为「未分款」的回款'
    );
    return;
  }
  selectedInstallmentRows.value = targetRows;
  dispatchManagerUserIds.value = [];
  await loadManagerUserOptions();
  dispatchDialog.visible = true;
};

const buildDispatchPayload = (): FinAccountInstallmentDispatchForm => ({
  accountInstallmentIds: selectedInstallmentRows.value.map((r) => r.accountInstallmentId),
  managerUserIds: dispatchManagerUserIds.value
});

const submitDispatch = async () => {
  if (!dispatchManagerUserIds.value.length) {
    proxy?.$modal.msgWarning('请选择客户经理');
    return;
  }
  dispatchDialog.loading = true;
  try {
    await dispatchFinAccountInstallment(buildDispatchPayload());
    proxy?.$modal.msgSuccess('派发成功');
    dispatchDialog.visible = false;
    await getList();
  } finally {
    dispatchDialog.loading = false;
  }
};

const upload = reactive({
  open: false,
  isUploading: false,
  updateSupport: 0,
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/oa/erp/finAccountInstallment/importData'
});

const importTemplate = () => {
  proxy?.download('oa/erp/finAccountInstallment/exportAccountInstallTemplate', {}, `回款模板_${new Date().getTime()}.xlsx`);
};

const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>',
    '导入结果',
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

const getRowClassName = ({ row }: { row: FinAccountInstallmentVO }) => {
  return selectedInstallment.value?.accountInstallmentId === row.accountInstallmentId ? 'selected-row' : '';
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listFinAccountInstallment(queryParams);
    finAccountInstallmentList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 查看详情 */
const handleView = (row: FinAccountInstallmentVO) => {
  router.push({
    path: '/fin/finAccountInstallment/edit',
    query: {
      id: String(row.accountInstallmentId),
      type: 'view'
    }
  });
};

const handleRowClick = async (row: FinAccountInstallmentVO) => {
  selectedInstallment.value = row;
  await getDetailList();
};

const getDetailList = async () => {
  if (!selectedInstallment.value) return;
  detailLoading.value = true;
  try {
    const res = await getErpFinAccountInstallmentDetailList({
      accountInstallmentId: selectedInstallment.value.accountInstallmentId
    });
    finAccountInstallmentDetailList.value = res.data;
  } finally {
    detailLoading.value = false;
  }
};

const submitImport = async () => {
  uploadRef.value?.submit();
};

onMounted(() => {
  getCustomerInfoListSelect();
  getList();
});
</script>

<style scoped>
.selected-row {
  background-color: #ecf5ff !important;
}

:deep(.el-table .selected-row td) {
  background-color: #ecf5ff !important;
}

:deep(.el-table__row) {
  cursor: pointer;
}

.el-icon {
  transition: transform 0.3s;
}

.rotate-180 {
  transform: rotate(180deg);
}

.panel-head {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 12px 14px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background: var(--el-fill-color-light);
}

.panel-head__title {
  font-size: 15px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.installment-toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  padding: 10px 0 8px;
  flex-shrink: 0;
}

.installment-toolbar__hint {
  margin-left: 4px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

/* 右侧分款明细 */
.detail-panel {
  background: var(--el-bg-color);
}

.detail-panel__header {
  padding: 14px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background: linear-gradient(180deg, var(--el-fill-color-light) 0%, var(--el-bg-color) 100%);
}

.detail-panel__header-main {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.detail-panel__title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  line-height: 1.4;
}

.detail-panel__meta {
  margin-top: 4px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
  line-height: 1.5;
}

.detail-panel__code {
  font-family: ui-monospace, monospace;
  color: var(--el-color-primary);
}

.detail-panel__divider {
  margin: 0 4px;
  color: var(--el-text-color-placeholder);
}

.detail-panel__customer {
  color: var(--el-text-color-regular);
}

.detail-panel__placeholder {
  margin-top: 4px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.detail-panel__tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.detail-panel__body {
  flex: 1;
  overflow: auto;
  padding: 14px 16px;
}

.detail-panel__empty {
  padding-top: 80px;
}

.detail-summary {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.detail-summary__card {
  padding: 10px 12px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  background: var(--el-fill-color-blank);
}

.detail-summary__card--primary {
  border-color: var(--el-color-primary-light-7);
  background: var(--el-color-primary-light-9);
}

.detail-summary__card--primary .detail-summary__value {
  color: var(--el-color-primary);
}

.detail-summary__card--allocated {
  border-color: var(--el-color-warning-light-7);
  background: var(--el-color-warning-light-9);
}

.detail-summary__card--allocated .detail-summary__value {
  color: var(--el-color-warning-dark-2);
}

.detail-summary__card--remain {
  border-color: var(--el-color-success-light-7);
  background: var(--el-color-success-light-9);
}

.detail-summary__card--remain .detail-summary__value {
  color: var(--el-color-success-dark-2);
}

.detail-summary__card--danger {
  border-color: var(--el-color-danger-light-7);
  background: var(--el-color-danger-light-9);
}

.detail-summary__card--danger .detail-summary__value {
  color: var(--el-color-danger);
}

.detail-summary__label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.detail-summary__value {
  font-size: 15px;
  font-weight: 600;
  line-height: 1.3;
  word-break: break-all;
}

.detail-progress {
  margin-top: 12px;
  padding: 10px 12px;
  border-radius: 8px;
  background: var(--el-fill-color-lighter);
}

.detail-progress__text {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 6px;
}

.detail-alert {
  margin-top: 12px;
}

.detail-alert--compact {
  margin-top: 8px;
}

.detail-alert--compact :deep(.el-alert) {
  padding: 4px 10px;
  align-items: center;
}

.detail-alert--compact :deep(.el-alert__content) {
  padding: 0;
  margin: 0;
}

.detail-alert--compact :deep(.el-alert__title) {
  margin: 0;
  line-height: 1.4;
}

.detail-alert-compact__text {
  font-size: 12px;
  font-weight: normal;
  color: var(--el-color-warning-dark-2);
}

.detail-alert--compact :deep(.el-alert__icon) {
  font-size: 14px;
  width: 14px;
  margin-right: 6px;
}

.detail-alert--compact :deep(.el-alert__description) {
  display: none;
}

.detail-table-section {
  margin-top: 14px;
}

.detail-table-section__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-table-section__title {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.detail-table-section__count {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.detail-table {
  width: 100%;
}

.detail-table :deep(.el-table__header th) {
  background: var(--el-fill-color-light);
}

.detail-cell-project {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  line-height: 1.35;
  text-align: center;
}

.detail-cell-project__code {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.detail-cell-project__name {
  font-size: 13px;
  color: var(--el-text-color-primary);
}

.detail-amount {
  font-weight: 600;
  color: var(--el-color-warning-dark-2);
}

.detail-empty {
  padding: 16px 0 8px;
}

.detail-empty__desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.detail-empty__hint {
  margin: 6px 0 0;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}
</style>
