<template>
  <a-modal
    :visible="visible"
    :title="getModalTitle()"
    width="1200px"
    :confirm-loading="loading"
    :ok-button-props="{ disabled: !isFormValid || isView }"
    @cancel="handleCancel"
    @ok="handleSubmit"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
      auto-label-width
    >
      <!-- 标签页导航 -->
      <div class="tab-navigation">
        <div
          v-for="tab in tabs"
          :key="tab.key"
          class="tab-item" :class="[{ active: activeTab === tab.key }]"
          @click="activeTab = tab.key"
        >
          {{ tab.label }}
        </div>
      </div>

      <!-- 标签页内容 -->
      <div class="tab-content">
        <!-- 基本信息 -->
        <div v-show="activeTab === 'basic'">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="设备名称" field="equipmentName">
                <a-input
                  v-model="formData.equipmentName"
                  placeholder="请输入设备名称"
                  :disabled="isView"
                  show-word-limit
                  :max-length="200"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="设备类型" field="equipmentType">
                <a-select
                  v-model="formData.equipmentType"
                  :options="equipmentTypeOptions"
                  placeholder="请选择设备类型"
                  :disabled="isView"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="设备型号" field="equipmentModel">
                <a-input
                  v-model="formData.equipmentModel"
                  placeholder="请输入设备型号"
                  :disabled="isView"
                  show-word-limit
                  :max-length="200"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="序列号" field="equipmentSn">
                <a-input
                  v-model="formData.equipmentSn"
                  placeholder="请输入序列号"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="品牌" field="brand">
                <a-input
                  v-model="formData.brand"
                  placeholder="请输入品牌"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="资产编号" field="assetCode">
                <a-input
                  v-model="formData.assetCode"
                  placeholder="请输入资产编号"
                  :disabled="isView"
                  show-word-limit
                  :max-length="50"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="配置规格" field="specification">
            <a-textarea
              v-model="formData.specification"
              placeholder="请输入配置规格参数"
              :disabled="isView"
              :rows="3"
              show-word-limit
              :max-length="500"
            />
          </a-form-item>
        </div>

        <!-- 位置与状态信息 -->
        <div v-show="activeTab === 'location'">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="设备状态" field="equipmentStatus">
                <a-select
                  v-model="formData.equipmentStatus"
                  :options="equipmentStatusOptions"
                  placeholder="请选择设备状态"
                  :disabled="isView"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="使用状态" field="useStatus">
                <a-select
                  v-model="formData.useStatus"
                  :options="useStatusOptions"
                  placeholder="请选择使用状态"
                  :disabled="isView"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="位置状态" field="locationStatus">
                <a-select
                  v-model="formData.locationStatus"
                  :options="locationStatusOptions"
                  placeholder="请选择位置状态"
                  :disabled="isView"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="健康状态" field="healthStatus">
                <a-select
                  v-model="formData.healthStatus"
                  :options="healthStatusOptions"
                  placeholder="请选择健康状态"
                  :disabled="isView"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="物理位置" field="physicalLocation">
                <a-input
                  v-model="formData.physicalLocation"
                  placeholder="请输入物理位置"
                  :disabled="isView"
                  show-word-limit
                  :max-length="200"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="负责人" field="responsiblePerson">
                <a-input
                  v-model="formData.responsiblePerson"
                  placeholder="请输入负责人"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="库存条码" field="inventoryBarcode">
            <a-input
              v-model="formData.inventoryBarcode"
              placeholder="请输入库存条码"
              :disabled="isView"
              show-word-limit
              :max-length="100"
            />
          </a-form-item>
        </div>

        <!-- 时间与金额 -->
        <div v-show="activeTab === 'time'">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="采购时间" field="purchaseTime">
                <a-date-picker
                  v-model="formData.purchaseTime"
                  placeholder="请选择采购时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="入库时间" field="inStockTime">
                <a-date-picker
                  v-model="formData.inStockTime"
                  placeholder="请选择入库时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="启用时间" field="activationTime">
                <a-date-picker
                  v-model="formData.activationTime"
                  placeholder="请选择启用时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="预计报废时间" field="expectedScrapTime">
                <a-date-picker
                  v-model="formData.expectedScrapTime"
                  placeholder="请选择预计报废时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="实际报废时间" field="actualScrapTime">
                <a-date-picker
                  v-model="formData.actualScrapTime"
                  placeholder="请选择实际报废时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="状态变更时间" field="statusChangeTime">
                <a-date-picker
                  v-model="formData.statusChangeTime"
                  placeholder="请选择状态变更时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="次户号" field="accountNumber">
                <a-input
                  v-model="formData.accountNumber"
                  placeholder="请输入次户号"
                  :disabled="isView"
                  show-word-limit
                  :max-length="50"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="数量" field="quantity">
                <a-input-number
                  v-model="formData.quantity"
                  placeholder="请输入数量"
                  :disabled="isView"
                  style="width: 100%"
                  :min="1"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="单价" field="unitPrice">
                <a-input-number
                  v-model="formData.unitPrice"
                  placeholder="请输入单价"
                  :disabled="isView"
                  style="width: 100%"
                  :precision="2"
                  :min="0"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="总价" field="totalPrice">
                <a-input-number
                  v-model="formData.totalPrice"
                  placeholder="请输入总价"
                  :disabled="isView"
                  style="width: 100%"
                  :precision="2"
                  :min="0"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="采购价格" field="purchasePrice">
                <a-input-number
                  v-model="formData.purchasePrice"
                  placeholder="请输入采购价格"
                  :disabled="isView"
                  style="width: 100%"
                  :precision="2"
                  :min="0"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="盘点依据" field="inventoryBasis">
                <a-textarea
                  v-model="formData.inventoryBasis"
                  placeholder="请输入盘点依据"
                  :disabled="isView"
                  :rows="3"
                  show-word-limit
                  :max-length="500"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="动态记录" field="dynamicRecord">
                <a-textarea
                  v-model="formData.dynamicRecord"
                  placeholder="请输入动态记录"
                  :disabled="isView"
                  :rows="3"
                  show-word-limit
                  :max-length="1000"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 采购及相关信息 -->
        <div v-show="activeTab === 'purchase'">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="采购订单" field="purchaseOrder">
                <a-input
                  v-model="formData.purchaseOrder"
                  placeholder="请输入采购订单"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="供应商名称" field="supplierName">
                <a-input
                  v-model="formData.supplierName"
                  placeholder="请输入供应商名称"
                  :disabled="isView"
                  show-word-limit
                  :max-length="200"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="折旧方法" field="depreciationMethod">
            <a-select
              v-model="formData.depreciationMethod"
              :options="depreciationMethodOptions"
              placeholder="请选择折旧方法"
              :disabled="isView"
            />
          </a-form-item>
        </div>

        <!-- 维保与健康信息 -->
        <div v-show="activeTab === 'maintenance'">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="保修截止日期" field="warrantyExpireDate">
                <a-date-picker
                  v-model="formData.warrantyExpireDate"
                  placeholder="请选择保修截止日期"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="维护人员" field="maintenancePerson">
                <a-input
                  v-model="formData.maintenancePerson"
                  placeholder="请输入维护人员"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="上次维护日期" field="lastMaintenanceDate">
                <a-date-picker
                  v-model="formData.lastMaintenanceDate"
                  placeholder="请选择上次维护日期"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="下次维护日期" field="nextMaintenanceDate">
                <a-date-picker
                  v-model="formData.nextMaintenanceDate"
                  placeholder="请选择下次维护日期"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 使用与盘点信息 -->
        <div v-show="activeTab === 'usage'">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="领用时间" field="borrowingTime">
                <a-date-picker
                  v-model="formData.borrowingTime"
                  placeholder="请选择领用时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="归还时间" field="returnTime">
                <a-date-picker
                  v-model="formData.returnTime"
                  placeholder="请选择归还时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="出库时间" field="outStockTime">
                <a-date-picker
                  v-model="formData.outStockTime"
                  placeholder="请选择出库时间"
                  :disabled="isView"
                  style="width: 100%"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="折旧率" field="depreciationRate">
                <a-input-number
                  v-model="formData.depreciationRate"
                  placeholder="请输入折旧率"
                  :disabled="isView"
                  style="width: 100%"
                  :precision="2"
                  :min="0"
                  :max="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="盘库时间/状态1" field="inventoryTimeStatus1">
                <a-input
                  v-model="formData.inventoryTimeStatus1"
                  placeholder="请输入盘库时间/状态1"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="盘库时间/状态2" field="inventoryTimeStatus2">
                <a-input
                  v-model="formData.inventoryTimeStatus2"
                  placeholder="请输入盘库时间/状态2"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="盘库时间/状态3" field="inventoryTimeStatus3">
                <a-input
                  v-model="formData.inventoryTimeStatus3"
                  placeholder="请输入盘库时间/状态3"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="盘点时间/状态1" field="inventoryCheckTimeStatus1">
                <a-input
                  v-model="formData.inventoryCheckTimeStatus1"
                  placeholder="请输入盘点时间/状态1"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="盘点时间/状态2" field="inventoryCheckTimeStatus2">
                <a-input
                  v-model="formData.inventoryCheckTimeStatus2"
                  placeholder="请输入盘点时间/状态2"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="盘点时间/状态3" field="inventoryCheckTimeStatus3">
                <a-input
                  v-model="formData.inventoryCheckTimeStatus3"
                  placeholder="请输入盘点时间/状态3"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 备注信息 -->
        <div v-show="activeTab === 'remark'">
          <a-form-item label="资产备注" field="assetRemark">
            <a-textarea
              v-model="formData.assetRemark"
              placeholder="请输入资产备注"
              :disabled="isView"
              :rows="4"
              show-word-limit
              :max-length="1000"
            />
          </a-form-item>
          
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="使用部门/人" field="usingDepartment">
                <a-input
                  v-model="formData.usingDepartment"
                  placeholder="请输入使用部门/人"
                  :disabled="isView"
                  show-word-limit
                  :max-length="200"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="导入人" field="importer">
                <a-input
                  v-model="formData.importer"
                  placeholder="请输入导入人"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="条码" field="barcode">
                <a-input
                  v-model="formData.barcode"
                  placeholder="请输入条码"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="总使用时间" field="totalUsageTime">
                <a-input
                  v-model="formData.totalUsageTime"
                  placeholder="请输入总使用时间"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="发票" field="invoice">
                <a-input
                  v-model="formData.invoice"
                  placeholder="请输入发票"
                  :disabled="isView"
                  show-word-limit
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="发票状态" field="invoiceStatus">
                <a-input
                  v-model="formData.invoiceStatus"
                  placeholder="请输入发票状态"
                  :disabled="isView"
                  show-word-limit
                  :max-length="50"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="附件" field="attachments">
            <a-input
              v-model="formData.attachments"
              placeholder="请输入附件"
              :disabled="isView"
              show-word-limit
              :max-length="500"
            />
          </a-form-item>

          <a-form-item label="照片" field="photos">
            <a-input
              v-model="formData.photos"
              placeholder="请输入照片"
              :disabled="isView"
              show-word-limit
              :max-length="500"
            />
          </a-form-item>

          <a-form-item label="折旧方法说明" field="depreciationMethodDesc">
            <a-textarea
              v-model="formData.depreciationMethodDesc"
              placeholder="请输入折旧方法说明"
              :disabled="isView"
              :rows="3"
              show-word-limit
              :max-length="500"
            />
          </a-form-item>
        </div>
      </div>
    </a-form>

    <!-- 开发调试工具 -->
    <template v-if="isDev">
      <a-divider />
      <div class="debug-tools">
        <a-space>
          <a-button size="small" @click="testFormData">测试表单数据</a-button>
          <a-button size="small" @click="fillTestData">填充测试数据</a-button>
          <a-button size="small" @click="clearFormData">清空表单</a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { EquipmentAPI } from '@/apis'
import type { EquipmentReq, EquipmentResp } from '@/types/equipment.d'

interface Props {
  visible: boolean
  equipmentData?: EquipmentResp | null
  mode: 'add' | 'edit' | 'view'
}

interface FormDataType extends EquipmentReq {
  [key: string]: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  equipmentData: null,
  mode: 'add',
})

const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

const formRef = ref()
const loading = ref(false)
const activeTab = ref('basic')

// 标签页配置
const tabs = [
  { key: 'basic', label: '基本信息' },
  { key: 'location', label: '位置与状态信息' },
  { key: 'time', label: '时间与金额' },
  { key: 'purchase', label: '采购及相关信息' },
  { key: 'maintenance', label: '维保与健康信息' },
  { key: 'usage', label: '使用与盘点信息' },
  { key: 'remark', label: '备注信息' },
]

// 表单数据
const formData = ref<FormDataType>({
  // 基础标识字段
  equipmentName: '',
  equipmentType: '',
  equipmentModel: '',
  equipmentSn: '',
  assetCode: '',
  inventoryBarcode: '',

  // 分类与规格字段
  brand: '',
  specification: '',

  // 状态管理字段
  equipmentStatus: 'normal',
  useStatus: '0',
  locationStatus: 'in_stock',
  healthStatus: 'good',

  // 位置与责任人字段
  physicalLocation: '',
  responsiblePerson: '',
  maintenancePerson: '',

  // 时间管理字段
  purchaseTime: '',
  inStockTime: '',
  activationTime: '',
  expectedScrapTime: '',
  actualScrapTime: '',
  statusChangeTime: '',
  warrantyExpireDate: '',
  lastMaintenanceDate: '',
  nextMaintenanceDate: '',

  // 财务价值字段
  purchasePrice: undefined,
  currentNetValue: undefined,
  salvageValue: undefined,
  depreciationMethod: 'straight_line',
  depreciationYears: 5,

  // 采购信息字段
  purchaseOrder: '',
  supplierName: '',

  // 新增采购相关字段
  accountNumber: '',
  quantity: 1,
  unitPrice: undefined,
  totalPrice: undefined,
  inventoryBasis: '',
  dynamicRecord: '',

  // 备注信息字段
  assetRemark: '',

  // 新增字段
  usingDepartment: '',
  borrowingTime: '',
  returnTime: '',
  outStockTime: '',
  totalUsageTime: '',
  depreciationRate: undefined,
  depreciationMethodDesc: '',
  invoice: '',
  invoiceStatus: '',
  attachments: '',
  photos: '',
  barcode: '',
  importer: '',
  inventoryTimeStatus1: '',
  inventoryTimeStatus2: '',
  inventoryTimeStatus3: '',
  inventoryCheckTimeStatus1: '',
  inventoryCheckTimeStatus2: '',
  inventoryCheckTimeStatus3: '',
})

// 表单验证规则
const rules = {
  // 基础标识字段验证
  equipmentName: [
    { required: true, message: '请输入设备名称' },
    { maxLength: 200, message: '设备名称长度不能超过200个字' },
  ],
  equipmentType: [
    { required: true, message: '请选择设备类型' },
  ],
  equipmentModel: [
    { required: true, message: '请输入设备型号' },
    { maxLength: 200, message: '设备型号长度不能超过200个字' },
  ],
  equipmentSn: [
    { required: true, message: '请输入序列号' },
    { maxLength: 100, message: '序列号长度不能超过100个字' },
  ],
  assetCode: [
    { maxLength: 50, message: '资产编号长度不能超过50个字' },
  ],
  inventoryBarcode: [
    { maxLength: 100, message: '库存条码长度不能超过100个字' },
  ],

  // 分类与规格字段验证
  brand: [
    { maxLength: 100, message: '品牌长度不能超过100个字' },
  ],
  specification: [
    { maxLength: 500, message: '配置规格长度不能超过500个字' },
  ],

  // 位置与责任人字段验证
  physicalLocation: [
    { maxLength: 200, message: '物理位置长度不能超过200个字' },
  ],
  responsiblePerson: [
    { maxLength: 100, message: '负责人长度不能超过100个字' },
  ],
  maintenancePerson: [
    { maxLength: 100, message: '维护人员长度不能超过100个字' },
  ],

  // 采购信息字段验证
  purchaseOrder: [
    { maxLength: 100, message: '采购订单长度不能超过100个字' },
  ],
  supplierName: [
    { maxLength: 200, message: '供应商名称长度不能超过200个字' },
  ],

  // 新增采购相关字段验证
  accountNumber: [
    { maxLength: 50, message: '次户号长度不能超过50个字' },
  ],
  quantity: [
    { type: 'number', min: 1, message: '数量必须大于等于1' },
  ],
  unitPrice: [
    { type: 'number', min: 0, message: '单价必须大于等于0' },
  ],
  totalPrice: [
    { type: 'number', min: 0, message: '总价必须大于等于0' },
  ],
  inventoryBasis: [
    { maxLength: 500, message: '盘点依据长度不能超过500个字' },
  ],
  dynamicRecord: [
    { maxLength: 1000, message: '动态记录长度不能超过1000个字' },
  ],

  // 财务价值字段验证
  purchasePrice: [
    { type: 'number', min: 0, message: '采购价格必须大于等于0' },
  ],
  currentNetValue: [
    { type: 'number', min: 0, message: '当前净值必须大于等于0' },
  ],
  salvageValue: [
    { type: 'number', min: 0, message: '残值必须大于等于0' },
  ],
  depreciationYears: [
    { type: 'number', min: 1, max: 100, message: '折旧年限必须在1-100年之间' },
  ],

  // 备注信息字段验证
  assetRemark: [
    { maxLength: 1000, message: '资产备注长度不能超过1000个字' },
  ],
}

// 选项数据
const equipmentTypeOptions = [
  { label: '检测设备', value: 'detection' },
  { label: '维修设备', value: 'maintain' },
  { label: '安全设备', value: 'security' },
  { label: '办公设备', value: 'office' },
  { label: '车辆', value: 'car' },
]

const equipmentStatusOptions = [
  { label: '正常', value: 'normal' },
  { label: '维修中', value: 'repair' },
  { label: '保养中', value: 'maintain' },
  { label: '报废', value: 'scrap' },
]

const useStatusOptions = [
  { label: '空闲', value: '0' },
  { label: '使用中', value: '1' },
]

const locationStatusOptions = [
  { label: '库存中', value: 'in_stock' },
  { label: '已分配', value: 'allocated' },
  { label: '维修中', value: 'repair' },
  { label: '待报废', value: 'scrap' },
  { label: '已报废', value: 'scrapped' },
  { label: '外借中', value: 'borrowed' },
  { label: '丢失', value: 'lost' },
]

const healthStatusOptions = [
  { label: '优秀', value: 'excellent' },
  { label: '良好', value: 'good' },
  { label: '一般', value: 'normal' },
  { label: '较差', value: 'poor' },
  { label: '差', value: 'bad' },
]

const depreciationMethodOptions = [
  { label: '直线法', value: 'straight_line' },
  { label: '双倍余额递减法', value: 'double_declining' },
  { label: '年数总和法', value: 'sum_of_years' },
  { label: '工作量法', value: 'workload' },
]

// 计算属性
const isView = computed(() => props.mode === 'view')
const isDev = computed(() => import.meta.env.DEV)

const getModalTitle = () => {
  switch (props.mode) {
    case 'add':
      return '新增设备'
    case 'edit':
      return '编辑设备'
    case 'view':
      return '查看设备'
    default:
      return '设备信息'
  }
}

const isFormValid = computed(() => {
  return formData.value.equipmentName
    && formData.value.equipmentType
    && formData.value.equipmentModel
    && formData.value.equipmentSn
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // eslint-disable-next-line ts/no-use-before-define
    initFormData()
  }
})

// 监听equipmentData变化
watch(() => props.equipmentData, () => {
  if (props.visible) {
    // eslint-disable-next-line ts/no-use-before-define
    initFormData()
  }
}, { deep: true })

// 初始化表单数据
const initFormData = () => {
  if (props.mode === 'add') {
    // eslint-disable-next-line ts/no-use-before-define
    resetFormData()
  } else if (props.equipmentData) {
    // 编辑或查看模式，填充数据
    Object.keys(formData.value).forEach((key) => {
      if (key in props.equipmentData!) {
        formData.value[key] = props.equipmentData![key as keyof EquipmentResp]
      }
    })
  }
}

// 重置表单数据
const resetFormData = () => {
  formData.value = {
    // 基础标识字段
    equipmentName: '',
    equipmentType: '',
    equipmentModel: '',
    equipmentSn: '',
    assetCode: '',
    inventoryBarcode: '',

    // 分类与规格字段
    brand: '',
    specification: '',

    // 状态管理字段
    equipmentStatus: 'normal',
    useStatus: '0',
    locationStatus: 'in_stock',
    healthStatus: 'good',

    // 位置与责任人字段
    physicalLocation: '',
    responsiblePerson: '',
    maintenancePerson: '',

    // 时间管理字段
    purchaseTime: '',
    inStockTime: '',
    activationTime: '',
    expectedScrapTime: '',
    actualScrapTime: '',
    statusChangeTime: '',
    warrantyExpireDate: '',
    lastMaintenanceDate: '',
    nextMaintenanceDate: '',

    // 财务价值字段
    purchasePrice: undefined,
    currentNetValue: undefined,
    salvageValue: undefined,
    depreciationMethod: 'straight_line',
    depreciationYears: 5,

    // 采购信息字段
    purchaseOrder: '',
    supplierName: '',

    // 新增采购相关字段
    accountNumber: '',
    quantity: 1,
    unitPrice: undefined,
    totalPrice: undefined,
    inventoryBasis: '',
    dynamicRecord: '',

    // 备注信息字段
    assetRemark: '',

    // 新增字段
    usingDepartment: '',
    borrowingTime: '',
    returnTime: '',
    outStockTime: '',
    totalUsageTime: '',
    depreciationRate: undefined,
    depreciationMethodDesc: '',
    invoice: '',
    invoiceStatus: '',
    attachments: '',
    photos: '',
    barcode: '',
    importer: '',
    inventoryTimeStatus1: '',
    inventoryTimeStatus2: '',
    inventoryTimeStatus3: '',
    inventoryCheckTimeStatus1: '',
    inventoryCheckTimeStatus2: '',
    inventoryCheckTimeStatus3: '',
  }
}

// 取消操作
const handleCancel = () => {
  resetFormData()
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()

    loading.value = true

    // 数据验证
    if (!formData.value.equipmentName?.trim()) {
      Message.error('设备名称不能为空')
      return
    }

    if (!formData.value.equipmentType) {
      Message.error('请选择设备类型')
      return
    }

    if (!formData.value.equipmentModel?.trim()) {
      Message.error('设备型号不能为空')
      return
    }

    if (!formData.value.equipmentSn?.trim()) {
      Message.error('序列号不能为空')
      return
    }

    // 准备提交数据
    const submitData: EquipmentReq = {
      equipmentName: formData.value.equipmentName.trim(),
      equipmentModel: formData.value.equipmentModel.trim(),
      equipmentType: formData.value.equipmentType,
      equipmentStatus: formData.value.equipmentStatus || 'normal',
      useStatus: formData.value.useStatus || '0',
      equipmentSn: formData.value.equipmentSn.trim(),
      assetCode: formData.value.assetCode?.trim(),
      brand: formData.value.brand?.trim(),
      specification: formData.value.specification?.trim(),
      locationStatus: formData.value.locationStatus,
      physicalLocation: formData.value.physicalLocation?.trim(),
      responsiblePerson: formData.value.responsiblePerson?.trim(),
      healthStatus: formData.value.healthStatus,
      purchaseTime: formData.value.purchaseTime,
      inStockTime: formData.value.inStockTime,
      activationTime: formData.value.activationTime,
      expectedScrapTime: formData.value.expectedScrapTime,
      actualScrapTime: formData.value.actualScrapTime,
      statusChangeTime: formData.value.statusChangeTime,
      purchaseOrder: formData.value.purchaseOrder?.trim(),
      supplierName: formData.value.supplierName?.trim(),
      purchasePrice: formData.value.purchasePrice,
      currentNetValue: formData.value.currentNetValue,
      depreciationMethod: formData.value.depreciationMethod?.trim(),
      depreciationYears: formData.value.depreciationYears,
      salvageValue: formData.value.salvageValue,
      warrantyExpireDate: formData.value.warrantyExpireDate,
      lastMaintenanceDate: formData.value.lastMaintenanceDate,
      nextMaintenanceDate: formData.value.nextMaintenanceDate,
      maintenancePerson: formData.value.maintenancePerson?.trim(),
      inventoryBarcode: formData.value.inventoryBarcode?.trim(),
      assetRemark: formData.value.assetRemark?.trim(),
      
      // 新增字段
      usingDepartment: formData.value.usingDepartment?.trim(),
      borrowingTime: formData.value.borrowingTime,
      returnTime: formData.value.returnTime,
      outStockTime: formData.value.outStockTime,
      totalUsageTime: formData.value.totalUsageTime?.trim(),
      depreciationRate: formData.value.depreciationRate,
      depreciationMethodDesc: formData.value.depreciationMethodDesc?.trim(),
      invoice: formData.value.invoice?.trim(),
      invoiceStatus: formData.value.invoiceStatus?.trim(),
      attachments: formData.value.attachments?.trim(),
      photos: formData.value.photos?.trim(),
      barcode: formData.value.barcode?.trim(),
      importer: formData.value.importer?.trim(),
      inventoryTimeStatus1: formData.value.inventoryTimeStatus1?.trim(),
      inventoryTimeStatus2: formData.value.inventoryTimeStatus2?.trim(),
      inventoryTimeStatus3: formData.value.inventoryTimeStatus3?.trim(),
      inventoryCheckTimeStatus1: formData.value.inventoryCheckTimeStatus1?.trim(),
      inventoryCheckTimeStatus2: formData.value.inventoryCheckTimeStatus2?.trim(),
      inventoryCheckTimeStatus3: formData.value.inventoryCheckTimeStatus3?.trim(),
    }

    // 调用API
    if (props.mode === 'add') {
              await EquipmentAPI.createEquipment(submitData)
      Message.success('设备添加成功')
    } else {
              await EquipmentAPI.updateEquipment(props.equipmentData!.equipmentId, submitData)
      Message.success('设备更新成功')
    }

    emit('success')
    handleCancel()
  } catch (error: any) {
    console.error('提交失败:', error)
    Message.error(error?.message || '操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 开发调试工具
const testFormData = () => {
  console.log('当前表单数据:', formData.value)
  console.log('表单验证状态:', formRef.value?.validate())
}

const fillTestData = () => {
  formData.value = {
    // 基础标识字段
    equipmentName: '测试设备001',
    equipmentType: 'detection',
    equipmentModel: 'TEST-MODEL-001',
    equipmentSn: 'SN20250101001',
    assetCode: 'ZC20250101001',
    inventoryBarcode: 'BC20250101001',

    // 分类与规格字段
    brand: '测试品牌',
    specification: '测试规格参数，包含详细的技术规格信息',

    // 状态管理字段
    equipmentStatus: 'normal',
    useStatus: '0',
    locationStatus: 'in_stock',
    healthStatus: 'good',

    // 位置与责任人字段
    physicalLocation: '测试仓库A区-01-01',
    responsiblePerson: '张三',
    maintenancePerson: '李四',

    // 时间管理字段
    purchaseTime: '2025-01-01 10:00:00',
    inStockTime: '2025-01-02 10:00:00',
    activationTime: '2025-01-03 10:00:00',
    expectedScrapTime: '2030-01-01 10:00:00',
    actualScrapTime: '',
    statusChangeTime: '2025-01-01 10:00:00',
    warrantyExpireDate: '2027-01-01 10:00:00',
    lastMaintenanceDate: '2024-12-01 10:00:00',
    nextMaintenanceDate: '2025-06-01 10:00:00',

    // 财务价值字段
    purchasePrice: 10000.00,
    currentNetValue: 8000.00,
    salvageValue: 1000.00,
    depreciationMethod: 'straight_line',
    depreciationYears: 5,

    // 采购信息字段
    purchaseOrder: 'PO20250101001',
    supplierName: '测试供应商有限公司',

    // 新增采购相关字段
    accountNumber: '001',
    quantity: 10,
    unitPrice: 1000.00,
    totalPrice: 10000.00,
    inventoryBasis: '盘点',
    dynamicRecord: '设备正常使用，无异常',

    // 备注信息字段
    assetRemark: '这是一台测试设备，用于系统功能验证和演示。设备性能良好，维护记录完整。',

    // 新增字段
    usingDepartment: '技术部-张三',
    borrowingTime: '2025-01-15 09:00:00',
    returnTime: '',
    outStockTime: '2025-01-15 09:00:00',
    totalUsageTime: '120小时',
    depreciationRate: 20.00,
    depreciationMethodDesc: '直线折旧法，年折旧率20%',
    invoice: 'INV20250101001',
    invoiceStatus: '已开具',
    attachments: '设备说明书.pdf,保修卡.pdf',
    photos: '设备正面.jpg,设备侧面.jpg',
    barcode: 'BAR20250101001',
    importer: '系统管理员',
    inventoryTimeStatus1: '2025-01-01 已完成',
    inventoryTimeStatus2: '2025-04-01 待盘点',
    inventoryTimeStatus3: '2025-07-01 待盘点',
    inventoryCheckTimeStatus1: '2025-01-01 已核对',
    inventoryCheckTimeStatus2: '2025-04-01 待核对',
    inventoryCheckTimeStatus3: '2025-07-01 待核对',
  }
  Message.success('已填充完整测试数据')
}

const clearFormData = () => {
  resetFormData()
  Message.success('已清空表单数据')
}
</script>

<style scoped>
.debug-tools {
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

/* 自定义标签页样式 */
.tab-navigation {
  display: flex;
  border-bottom: 1px solid #e5e6eb;
  margin-bottom: 16px;
  background-color: #f7f8fa;
  border-radius: 6px 6px 0 0;
}

.tab-item {
  padding: 12px 24px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #4e5969;
  background-color: transparent;
  border-radius: 6px 6px 0 0;
}

.tab-item:hover {
  color: #165dff;
  background-color: #f2f3f5;
}

.tab-item.active {
  color: #165dff;
  background-color: #fff;
  border-bottom-color: #165dff;
  font-weight: 500;
}

.tab-content {
  padding: 16px 0;
  min-height: 300px;
}

/* 确保表单内容正确显示 */
:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-form-item-label) {
  font-weight: 500;
  color: #1d2129;
}

:deep(.arco-input),
:deep(.arco-select),
:deep(.arco-textarea),
:deep(.arco-date-picker),
:deep(.arco-input-number) {
  width: 100%;
}
</style>
