<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft, Plus, Delete, Download, View } from "@element-plus/icons-vue";
import {
  getArchiveDetail,
  createArchive,
  updateArchive,
  getEnumOptions,
  uploadToOss,
  deleteOssFile
} from "@/api/shopArchive";
import { getEnabledShops } from "@/api/shop";
import type {
  ShopArchiveForm,
  FixedAsset,
  ContractAttachment,
  EnumOption
} from "./utils/types";
import type { UploadRequestOptions, UploadUserFile } from "element-plus";

defineOptions({
  name: "ShopArchiveDetail"
});

const route = useRoute();
const router = useRouter();

const formRef = ref();
const activeTab = ref("basic");
const loading = ref(false);
const saving = ref(false);

// 门店下拉选项
const shopOptions = ref<Array<{ id: string; name: string; address: string }>>([]);

// 加载门店列表（用于下拉选择）
async function loadShopOptions() {
  try {
    const res = await getEnabledShops();
    if (res && res.data) {
      shopOptions.value = res.data.map((s: any) => ({
        id: String(s.id),
        name: s.name,
        address: s.address || ""
      }));
    }
  } catch (error) {
    console.error("加载门店列表失败:", error);
  }
}

// 选择门店后自动带出地址
function handleShopChange(shopId: string) {
  const shop = shopOptions.value.find(s => s.id === shopId);
  if (shop) {
    form.shopName = shop.name;
    form.shopAddress = shop.address;
  } else {
    form.shopName = "";
    form.shopAddress = "";
  }
}

// 页面模式
const isCreate = computed(() => route.query.mode === "create");
const isView = computed(() => route.query.mode === "view");
const isEdit = computed(() => route.query.mode === "edit");
const pageTitle = computed(() => {
  if (isCreate.value) return "新增门店档案";
  if (isView.value) return "查看门店档案";
  return "编辑门店档案";
});

// 表单数据
const form = reactive<ShopArchiveForm>({
  shopName: "",
  shopAddress: "",
  venueType: "",
  cooperationMode: "",
  partyBSalesman: "",
  partyBSalesmanPhone: "",
  partyACompany: "",
  partyAManager: "",
  partyAManagerPhone: "",
  businessStatus: "",
  remark: "",
  contractNo: "",
  contractSignDate: "",
  contractStartDate: "",
  contractEndDate: "",
  contractStatus: "",
  rentStartDate: "",
  monthlyRent: undefined,
  rentFreeDays: undefined,
  rentPayDeadlineDay: undefined,
  depositAmount: undefined,
  depositStatus: "",
  depositPaidAmount: undefined,
  depositRefundCondition: "",
  billingMode: "",
  electricityPrice: undefined,
  electricityShareRule: "",
  commissionBaseType: "",
  commissionBase: undefined,
  commissionRate: undefined,
  commissionMinGuarantee: undefined,
  commissionPeriodMonths: undefined,
  paymentCycle: "",
  terminationDate: "",
  terminationRemark: "",
  paymentMethod: "",
  payeeAccountName: "",
  payeeBankName: "",
  payeeBankAccount: "",
  taxpayerId: "",
  invoiceType: "",
  invoiceTaxRate: undefined,
  fixedAssets: [],
  attachments: []
});

// 枚举选项
const contractStatusOptions = ref<EnumOption[]>([]);
const businessStatusOptions = ref<EnumOption[]>([]);
const billingModeOptions = ref<EnumOption[]>([]);
const venueTypeOptions = ref<EnumOption[]>([]);
const depositStatusOptions = ref<EnumOption[]>([]);
const commissionBaseTypeOptions = ref<EnumOption[]>([]);

// 静态选项
const cooperationModeOptions = [
  { label: "水饮副食", value: "DRINKS_SNACKS" },
  { label: "盒饭", value: "BOXED_MEAL" }
];

const paymentMethodOptions = [
  { label: "对公", value: "CORPORATE" },
  { label: "对私", value: "PERSONAL" }
];

const invoiceTypeOptions = [
  { label: "增值税专票", value: "SPECIAL_VAT" },
  { label: "增值税普票", value: "GENERAL_VAT" }
];

const paymentCycleOptions = [
  { label: "月付", value: "MONTHLY" },
  { label: "季度付", value: "QUARTERLY" },
  { label: "半年付", value: "SEMI_ANNUAL" },
  { label: "年付", value: "ANNUAL" }
];

const assetTypeOptions = [
  { label: "自助售卖机", value: "VENDING_MACHINE" },
  { label: "微波炉", value: "MICROWAVE" }
];

const assetStatusOptions = [
  { label: "正常运行", value: "NORMAL" },
  { label: "故障维修", value: "REPAIR" },
  { label: "闲置撤机", value: "IDLE" }
];

// 条件显示
const showElectricityFields = computed(
  () => form.billingMode === "ELECTRICITY"
);
const showCommissionFields = computed(
  () => form.billingMode === "COMMISSION"
);
const showBankName = computed(
  () => form.paymentMethod === "CORPORATE"
);
const showTerminationFields = computed(
  () => form.contractStatus === "TERMINATED"
);

// 固定资产表格列
const assetColumns = [
  { label: "资产类型", prop: "assetType", minWidth: 150 },
  { label: "资产名称", prop: "assetName", minWidth: 150 },
  { label: "资产编号", prop: "assetCode", minWidth: 150 },
  { label: "设备状态", prop: "assetStatus", minWidth: 150 },
  { label: "备注", prop: "remark", minWidth: 200 },
  { label: "操作", prop: "action", width: 80, fixed: "right" }
];

// 附件分组
const attachmentGroups = [
  { type: "CONTRACT", title: "合同附件" },
  { type: "LEASE_AGREEMENT", title: "场地租赁协议" },
  { type: "ELECTRICITY_AGREEMENT", title: "电费补充协议" },
  { type: "DEPOSIT_RECEIPT", title: "保证金收据" },
  { type: "TERMINATION_AGREEMENT", title: "解约/补充变更协议" }
];

// 各分组文件列表
const fileLists = reactive<Record<string, UploadUserFile[]>>({
  CONTRACT: [],
  LEASE_AGREEMENT: [],
  ELECTRICITY_AGREEMENT: [],
  DEPOSIT_RECEIPT: [],
  TERMINATION_AGREEMENT: []
});

// 文件大小格式化
function formatFileSize(size: number): string {
  if (!size) return "0 B";
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
  return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}

// OSS 自定义上传
async function customUpload(options: UploadRequestOptions) {
  const file = options.file;
  const attachmentType = options.data?.attachmentType as string;

  try {
    options.onProgress({ percent: 0 });
    const result = await uploadToOss(
      file,
      `shop-archive/${attachmentType.toLowerCase()}`,
      (percent: number) => {
        options.onProgress({ percent });
      }
    );

    const newFile: UploadUserFile = {
      name: result.fileName,
      url: result.url,
      uid: Date.now(),
      status: "success",
      size: result.fileSize
    };
    (newFile as any).objectKey = result.objectKey;
    (newFile as any).attachmentType = attachmentType;
    (newFile as any).fileExtension = result.fileExtension;

    fileLists[attachmentType].push(newFile);
    options.onSuccess(newFile);
  } catch (error) {
    options.onError(error as Error);
    ElMessage.error(`文件 ${file.name} 上传失败`);
  }
}

// 删除附件
function handleRemove(file: UploadUserFile, attachmentType: string) {
  const list = fileLists[attachmentType];
  const index = list.findIndex(f => f.uid === file.uid);
  if (index > -1) {
    list.splice(index, 1);
  }
  if ((file as any).objectKey) {
    deleteOssFile((file as any).objectKey).catch(() => {
      ElMessage.warning("OSS 文件删除失败，但已从列表移除");
    });
  }
}

// 预览附件
function handlePreview(file: UploadUserFile) {
  if (file.url) {
    window.open(file.url, "_blank");
  }
}

// 下载附件
function handleDownload(file: UploadUserFile) {
  if (file.url) {
    const link = document.createElement("a");
    link.href = file.url;
    link.download = file.name || "下载文件";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

// 添加固定资产行
function addAsset() {
  form.fixedAssets.push({
    id: `temp_${Date.now()}`,
    shopArchiveId: "",
    shopId: "",
    assetType: "",
    assetName: "",
    assetCode: "",
    assetStatus: "",
    remark: ""
  });
}

// 删除固定资产行
function removeAsset(index: number) {
  form.fixedAssets.splice(index, 1);
}

// 加载枚举选项
async function loadEnumOptions() {
  try {
    const [contractRes, businessRes, billingRes, venueRes, depositRes, commBaseRes] =
      await Promise.all([
        getEnumOptions("contractStatus"),
        getEnumOptions("businessStatus"),
        getEnumOptions("billingMode"),
        getEnumOptions("venueType"),
        getEnumOptions("depositStatus"),
        getEnumOptions("commissionBaseType")
      ]);
    contractStatusOptions.value = contractRes.data || [];
    businessStatusOptions.value = businessRes.data || [];
    billingModeOptions.value = billingRes.data || [];
    venueTypeOptions.value = venueRes.data || [];
    depositStatusOptions.value = depositRes.data || [];
    commissionBaseTypeOptions.value = commBaseRes.data || [];
  } catch (error) {
    console.error("加载枚举选项失败:", error);
  }
}

// 将附件列表转换为提交数据
function buildAttachments(): ContractAttachment[] {
  const result: ContractAttachment[] = [];
  for (const group of attachmentGroups) {
    const files = fileLists[group.type] || [];
    files.forEach((file, index) => {
      result.push({
        id: (file as any).id || `temp_${file.uid}`,
        shopArchiveId: "",
        shopId: "",
        attachmentType: group.type,
        fileName: file.name,
        fileUrl: file.url,
        fileSize: file.size || 0,
        fileExtension: (file as any).fileExtension || "",
        sortOrder: index
      });
    });
  }
  return result;
}

// 构建提交数据
function buildSubmitData() {
  return {
    ...form,
    fixedAssets: form.fixedAssets.filter(a => a.assetType || a.assetName),
    attachments: buildAttachments()
  };
}

// 加载档案详情
async function loadArchiveDetail() {
  const id = route.params.id as string;
  if (!id) return;

  loading.value = true;
  try {
    const res = await getArchiveDetail(id);
    if (res && res.data) {
      const data = res.data;
      Object.keys(form).forEach(key => {
        if (data[key] !== undefined) {
          (form as any)[key] = data[key];
        }
      });

      // 回填固定资产
      if (data.fixedAssets) {
        form.fixedAssets = data.fixedAssets;
      }

      // 回填附件
      if (data.attachments) {
        for (const group of attachmentGroups) {
          const groupFiles = (data.attachments as ContractAttachment[]).filter(
            (a: ContractAttachment) => a.attachmentType === group.type
          );
          fileLists[group.type] = groupFiles.map((a: ContractAttachment) => ({
            name: a.fileName || "",
            url: a.fileUrl || "",
            uid: Number(a.id) || Date.now(),
            status: "success" as const,
            size: a.fileSize || 0,
            objectKey: (a as any).objectKey || "",
            attachmentType: a.attachmentType,
            fileExtension: a.fileExtension || "",
            id: a.id
          }));
        }
      }
    }
  } catch (error) {
    console.error("加载档案详情失败:", error);
    ElMessage.error("加载档案详情失败");
  } finally {
    loading.value = false;
  }
}

// 保存
async function handleSave() {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
  } catch {
    ElMessage.warning("请检查表单必填项");
    return;
  }

  if (!form.shopId) {
    ElMessage.warning("请选择门店");
    return;
  }

  saving.value = true;
  try {
    const submitData = buildSubmitData();
    if (isCreate.value) {
      const res = await createArchive(submitData);
      if (res.code === 200 || res.code === 0) {
        ElMessage.success("创建成功");
        router.push("/operation/shop-archive");
      } else {
        ElMessage.error(res.message || "创建失败");
      }
    } else {
      const res = await updateArchive(route.params.id as string, submitData);
      if (res.code === 200 || res.code === 0) {
        ElMessage.success("保存成功");
        router.push("/operation/shop-archive");
      } else {
        ElMessage.error(res.message || "保存失败");
      }
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
}

// 返回
function goBack() {
  router.push("/operation/shop-archive");
}

onMounted(() => {
  loadEnumOptions();
  loadShopOptions();
  if (route.params.id && !isCreate.value) {
    loadArchiveDetail();
  }
});
</script>

<template>
  <div class="shop-archive-detail" v-loading="loading">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button :icon="ArrowLeft" @click="goBack">返回列表</el-button>
      <span class="page-title">{{ pageTitle }}</span>
    </div>

    <!-- 表单主体 -->
    <el-form
      ref="formRef"
      :model="form"
      label-width="160px"
      :disabled="isView"
      class="detail-form"
    >
      <el-tabs v-model="activeTab" type="border-card">
        <!-- ========== Tab 1: 门店基础信息 ========== -->
        <el-tab-pane label="门店基础信息" name="basic">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="选择门店" required>
                <el-select
                  v-model="form.shopId"
                  placeholder="请选择门店"
                  clearable
                  filterable
                  class="w-full"
                  @change="handleShopChange"
                >
                  <el-option
                    v-for="shop in shopOptions"
                    :key="shop.id"
                    :label="shop.name"
                    :value="shop.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门店地址">
                <el-input
                  v-model="form.shopAddress"
                  placeholder="请输入门店地址"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合作场地类型">
                <el-select
                  v-model="form.venueType"
                  placeholder="请选择合作场地类型"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="item in venueTypeOptions"
                    :key="item.code"
                    :label="item.description"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合作模式">
                <el-select
                  v-model="form.cooperationMode"
                  placeholder="请选择合作模式"
                  clearable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  class="w-full"
                >
                  <el-option
                    v-for="item in cooperationModeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="乙方业务员姓名">
                <el-input
                  v-model="form.partyBSalesman"
                  placeholder="请输入乙方业务员姓名"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="乙方业务员手机号">
                <el-input
                  v-model="form.partyBSalesmanPhone"
                  placeholder="请输入手机号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="甲方公司名称">
                <el-input
                  v-model="form.partyACompany"
                  placeholder="请输入甲方公司名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="甲方场地管理人员姓名">
                <el-input
                  v-model="form.partyAManager"
                  placeholder="请输入甲方场地管理人员姓名"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="甲方场地管理人员电话">
                <el-input
                  v-model="form.partyAManagerPhone"
                  placeholder="请输入甲方场地管理人员电话"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门店经营状态">
                <el-select
                  v-model="form.businessStatus"
                  placeholder="请选择门店经营状态"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="item in businessStatusOptions"
                    :key="item.code"
                    :label="item.description"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="门店备注">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入门店备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- ========== Tab 2: 固定资产设备 ========== -->
        <el-tab-pane label="固定资产设备" name="assets">
          <el-table :data="form.fixedAssets" border style="width: 100%">
            <el-table-column label="资产类型" min-width="150">
              <template #default="{ row }">
                <el-select
                  v-model="row.assetType"
                  placeholder="请选择"
                  clearable
                  :disabled="isView"
                >
                  <el-option
                    v-for="item in assetTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="资产名称" min-width="150">
              <template #default="{ row }">
                <el-input
                  v-model="row.assetName"
                  placeholder="请输入"
                  :disabled="isView"
                />
              </template>
            </el-table-column>
            <el-table-column label="资产编号" min-width="150">
              <template #default="{ row }">
                <el-input
                  v-model="row.assetCode"
                  placeholder="请输入"
                  :disabled="isView"
                />
              </template>
            </el-table-column>
            <el-table-column label="设备状态" min-width="150">
              <template #default="{ row }">
                <el-select
                  v-model="row.assetStatus"
                  placeholder="请选择"
                  clearable
                  :disabled="isView"
                >
                  <el-option
                    v-for="item in assetStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="200">
              <template #default="{ row }">
                <el-input
                  v-model="row.remark"
                  placeholder="请输入"
                  :disabled="isView"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="{ $index }">
                <el-button
                  type="danger"
                  link
                  :icon="Delete"
                  :disabled="isView"
                  @click="removeAsset($index)"
                />
              </template>
            </el-table-column>
          </el-table>
          <el-button
            type="primary"
            plain
            :icon="Plus"
            class="mt-4"
            :disabled="isView"
            @click="addAsset"
          >
            添加设备
          </el-button>
        </el-tab-pane>

        <!-- ========== Tab 3: 合同核心信息 ========== -->
        <el-tab-pane label="合同核心信息" name="contract">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="合同编号">
                <el-input
                  v-model="form.contractNo"
                  placeholder="请输入合同编号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同签订日期">
                <el-date-picker
                  v-model="form.contractSignDate"
                  type="date"
                  placeholder="请选择签订日期"
                  value-format="YYYY-MM-DD"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同起始日">
                <el-date-picker
                  v-model="form.contractStartDate"
                  type="date"
                  placeholder="请选择起始日"
                  value-format="YYYY-MM-DD"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同到期日">
                <el-date-picker
                  v-model="form.contractEndDate"
                  type="date"
                  placeholder="请选择到期日"
                  value-format="YYYY-MM-DD"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同状态">
                <el-select
                  v-model="form.contractStatus"
                  placeholder="请选择合同状态"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="item in contractStatusOptions"
                    :key="item.code"
                    :label="item.description"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租金起始日">
                <el-date-picker
                  v-model="form.rentStartDate"
                  type="date"
                  placeholder="请选择租金起始日"
                  value-format="YYYY-MM-DD"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="每月固定租金金额">
                <el-input-number
                  v-model="form.monthlyRent"
                  :min="0"
                  :precision="2"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="免租期天数">
                <el-input-number
                  v-model="form.rentFreeDays"
                  :min="0"
                  :precision="0"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租金缴纳截止日">
                <el-input-number
                  v-model="form.rentPayDeadlineDay"
                  :min="1"
                  :max="31"
                  :precision="0"
                  :controls="false"
                  placeholder="每月几号"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="保证金总额">
                <el-input-number
                  v-model="form.depositAmount"
                  :min="0"
                  :precision="2"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="保证金缴纳状态">
                <el-select
                  v-model="form.depositStatus"
                  placeholder="请选择"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="item in depositStatusOptions"
                    :key="item.code"
                    :label="item.description"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="保证金实缴金额">
                <el-input-number
                  v-model="form.depositPaidAmount"
                  :min="0"
                  :precision="2"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="保证金退还条件">
                <el-input
                  v-model="form.depositRefundCondition"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入保证金退还条件"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="合作计费模式">
                <el-select
                  v-model="form.billingMode"
                  placeholder="请选择合作计费模式"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="item in billingModeOptions"
                    :key="item.code"
                    :label="item.description"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 电费相关字段 -->
            <template v-if="showElectricityFields">
              <el-col :span="8">
                <el-form-item label="电费结算单价">
                  <el-input-number
                    v-model="form.electricityPrice"
                    :min="0"
                    :precision="2"
                    :controls="false"
                    placeholder="请输入"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="电费公摊规则">
                  <el-input
                    v-model="form.electricityShareRule"
                    placeholder="请输入电费公摊规则"
                  />
                </el-form-item>
              </el-col>
            </template>

            <!-- 提成相关字段 -->
            <template v-if="showCommissionFields">
              <el-col :span="8">
                <el-form-item label="提成基数计算口径">
                  <el-select
                    v-model="form.commissionBaseType"
                    placeholder="请选择"
                    clearable
                    class="w-full"
                  >
                    <el-option
                      v-for="item in commissionBaseTypeOptions"
                      :key="item.code"
                      :label="item.description"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="提成基数">
                  <el-input-number
                    v-model="form.commissionBase"
                    :min="0"
                    :precision="2"
                    :controls="false"
                    placeholder="请输入"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="提成比例(%)">
                  <el-input-number
                    v-model="form.commissionRate"
                    :min="0"
                    :max="100"
                    :precision="2"
                    :controls="false"
                    placeholder="请输入"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最低保底提成金额">
                  <el-input-number
                    v-model="form.commissionMinGuarantee"
                    :min="0"
                    :precision="2"
                    :controls="false"
                    placeholder="请输入"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="提成账期(月)">
                  <el-input-number
                    v-model="form.commissionPeriodMonths"
                    :min="1"
                    :precision="0"
                    :controls="false"
                    placeholder="请输入"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
            </template>

            <el-col :span="8">
              <el-form-item label="计费方式">
                <el-select
                  v-model="form.paymentCycle"
                  placeholder="请选择计费方式"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="item in paymentCycleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 解约相关字段 -->
            <template v-if="showTerminationFields">
              <el-col :span="8">
                <el-form-item label="解约日期">
                  <el-date-picker
                    v-model="form.terminationDate"
                    type="date"
                    placeholder="请选择解约日期"
                    value-format="YYYY-MM-DD"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="解约备注">
                  <el-input
                    v-model="form.terminationRemark"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入解约备注"
                  />
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-tab-pane>

        <!-- ========== Tab 4: 收款结算 & 开票信息 ========== -->
        <el-tab-pane label="收款结算 & 开票信息" name="settlement">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="打款方式">
                <el-select
                  v-model="form.paymentMethod"
                  placeholder="请选择打款方式"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="item in paymentMethodOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="甲方收款账户名称">
                <el-input
                  v-model="form.payeeAccountName"
                  placeholder="请输入甲方收款账户名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="showBankName">
              <el-form-item label="收款开户行">
                <el-input
                  v-model="form.payeeBankName"
                  placeholder="请输入收款开户行"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="银行账号">
                <el-input
                  v-model="form.payeeBankAccount"
                  placeholder="请输入银行账号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="纳税人识别号">
                <el-input
                  v-model="form.taxpayerId"
                  placeholder="请输入纳税人识别号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票类型">
                <el-select
                  v-model="form.invoiceType"
                  placeholder="请选择发票类型"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="item in invoiceTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开票税率(%)">
                <el-input-number
                  v-model="form.invoiceTaxRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- ========== Tab 5: 合同附件 ========== -->
        <el-tab-pane label="合同附件" name="attachments">
          <div
            v-for="group in attachmentGroups"
            :key="group.type"
            class="attachment-group"
          >
            <div class="attachment-group-title">{{ group.title }}</div>
            <el-upload
              :file-list="fileLists[group.type]"
              :http-request="customUpload"
              :on-remove="file => handleRemove(file, group.type)"
              :on-preview="handlePreview"
              :before-upload="file => { if (file.size > 50 * 1024 * 1024) { ElMessage.error('文件大小不能超过50MB'); return false; } return true; }"
              :data="{ attachmentType: group.type }"
              :disabled="isView"
              multiple
              :auto-upload="true"
            >
              <el-button
                type="primary"
                plain
                :icon="Plus"
                :disabled="isView"
              >
                上传文件
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传任意格式文件，单个文件不超过 50MB
                </div>
              </template>
            </el-upload>
            <!-- 已上传文件列表（查看模式） -->
            <div
              v-if="fileLists[group.type]?.length && isView"
              class="file-list-view"
            >
              <div
                v-for="file in fileLists[group.type]"
                :key="file.uid"
                class="file-item"
              >
                <span class="file-name">{{ file.name }}</span>
                <span class="file-size">
                  {{ formatFileSize(file.size || 0) }}
                </span>
                <span class="file-actions">
                  <el-button
                    type="primary"
                    link
                    :icon="View"
                    @click="handlePreview(file)"
                  >
                    预览
                  </el-button>
                  <el-button
                    type="primary"
                    link
                    :icon="Download"
                    @click="handleDownload(file)"
                  >
                    下载
                  </el-button>
                </span>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 底部操作按钮 -->
    <div class="page-footer" v-if="!isView">
      <el-button @click="goBack">取消</el-button>
      <el-button type="primary" :loading="saving" @click="handleSave">
        保存
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.shop-archive-detail {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .page-title {
    margin-left: 12px;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.detail-form {
  :deep(.el-tabs__content) {
    padding: 24px 16px;
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;
  }

  :deep(.el-input-number) {
    width: 100%;
  }
}

.attachment-group {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);

  &:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
  }

  .attachment-group-title {
    font-size: 15px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 12px;
  }
}

.file-list-view {
  margin-top: 12px;

  .file-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 4px;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .file-name {
      flex: 1;
      font-size: 14px;
      color: var(--el-text-color-primary);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .file-size {
      margin: 0 16px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
      white-space: nowrap;
    }

    .file-actions {
      display: flex;
      gap: 8px;
      white-space: nowrap;
    }
  }
}

.page-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 24px 0;
  margin-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}
</style>
