<template>
  <!-- 移动端布局 -->
  <el-drawer v-if="isMobile" v-model="dialogVisible" :title="dialogTitle" direction="rtl" size="100%" :close-on-press-escape="true" :destroy-on-close="true" class="mobile-form-drawer">
    <div class="mobile-form" v-loading="formLoading">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top">
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">基本信息</div>
          <el-form-item label="过磅单号" prop="no"><el-input disabled v-model="formData.no" placeholder="保存时自动生成" /></el-form-item>
          <el-form-item label="原料" prop="productId">
            <el-select v-model="formData.productId" placeholder="请选择原料" filterable style="width:100%" @change="handleProductChange" clearable>
              <el-option v-for="item in productOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <template v-if="isTomato">
            <el-form-item label="交售农户" prop="supplierName">
              <el-select v-model="formData.supplierName" filterable remote :remote-method="remoteSupplierFarmerMethod" :loading="supplierLoadingFarmer" placeholder="请选择交售农户" @change="handleSupplierChange" clearable style="width:100%">
                <el-option v-for="item in supplierOptionsFarmer" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="农户身份证号" prop="idCardNumber"><el-input v-model="formData.idCardNumber" placeholder="农户身份证号" disabled /></el-form-item>
            <el-form-item label="手机号码" prop="mobile"><el-input v-model="formData.mobile" placeholder="请输入手机号码" /></el-form-item>
          </template>
          <div class="mobile-form__input-group">
            <el-form-item label="毛重(t)" prop="grossWeight"><el-input-number style="width:100%" v-model="formData.grossWeight" :precision="2" :step="0.1" :min="0" @change="calculateNetWeight" /></el-form-item>
            <el-form-item label="皮重(t)" prop="tareWeight"><el-input-number style="width:100%" v-model="formData.tareWeight" :precision="2" :step="0.1" :min="0" @change="calculateNetWeight" /></el-form-item>
          </div>
          <el-form-item label="承运司机" prop="driver">
            <el-select v-model="formData.driver" filterable remote :remote-method="remoteDriverMethod" :loading="driverLoading" placeholder="请选择承运司机" @change="handleDriverChange" clearable allow-create default-first-option style="width:100%">
              <el-option v-for="item in driverOptions" :key="item.id" :label="item.driverName" :value="item.driverName" />
            </el-select>
          </el-form-item>
          <el-form-item label="车号" prop="vehicleNumber"><el-input v-model="formData.vehicleNumber" placeholder="请输入车号" /></el-form-item>
          <div class="mobile-form__input-group">
            <el-form-item label="净重(t)" prop="netWeight"><el-input-number style="width:100%" v-model="formData.netWeight" :precision="2" :step="0.1" :min="0" disabled /></el-form-item>
            <el-form-item label="扣杂率(%)" prop="impurityRate"><el-input-number style="width:100%" v-model="formData.impurityRate" :precision="2" :step="0.1" :min="0" :max="100" @change="calculatePlannedWeight" /></el-form-item>
          </div>
          <template v-if="isTomato"><el-form-item label="产地凭证号" prop="originCertificateNumber"><el-input v-model="formData.originCertificateNumber" placeholder="请输入产地凭证号" /></el-form-item></template>
          <div class="mobile-form__input-group">
            <el-form-item label="计划重量(t)" prop="plannedWeight"><el-input-number style="width:100%" v-model="formData.plannedWeight" :precision="2" :step="0.1" :min="0" disabled /></el-form-item>
            <el-form-item label="剩余重量(t)" prop="remainingWeight"><el-input-number style="width:100%" v-model="formData.remainingWeight" :precision="2" :step="0.1" :min="0" disabled /></el-form-item>
          </div>
          <template v-if="isStevia">
            <el-form-item label="供应商" prop="supplierName2">
              <el-select v-model="formData.supplierName2" filterable remote :remote-method="remoteSupplierVendorMethod" :loading="supplierLoadingVendor" placeholder="请选择供应商" @change="handleSupplierChange2" clearable style="width:100%">
                <el-option v-for="item in supplierOptionsVendor" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </template>
          <template v-if="isTomato"><el-form-item label="管理员" prop="administrator"><el-input v-model="formData.administrator" placeholder="请输入管理员姓名" /></el-form-item></template>
          <el-form-item label="司磅员" prop="weigher"><el-input v-model="formData.weigher" placeholder="请输入司磅员姓名" /></el-form-item>
          <el-form-item label="备注" prop="remark"><el-input type="textarea" v-model="formData.remark" :rows="2" placeholder="请输入备注" /></el-form-item>
        </div>
        <template v-if="isStevia">
          <div class="mobile-form__section">
            <div class="mobile-form__section-title">检验信息</div>
            <el-form-item label="取样日期" prop="sampleDate"><el-date-picker v-model="formData.sampleDate" type="date" placeholder="请选择取样日期" style="width:100%" /></el-form-item>
            <el-form-item label="取样地点" prop="sampleLocation"><el-input v-model="formData.sampleLocation" placeholder="请输入取样地点" /></el-form-item>
            <div class="mobile-form__input-group">
              <el-form-item label="代表重量(kg)" prop="representativeWeight"><el-input-number style="width:100%" v-model="formData.representativeWeight" :precision="2" :step="0.1" :min="0" /></el-form-item>
              <el-form-item label="样品重量(kg)" prop="sampleWeight"><el-input-number style="width:100%" v-model="formData.sampleWeight" :precision="2" :step="0.1" :min="0" /></el-form-item>
            </div>
            <div class="mobile-form__input-group">
              <el-form-item label="杂质重量(kg)" prop="impurityWeight"><el-input-number style="width:100%" v-model="formData.impurityWeight" :precision="2" :step="0.1" :min="0" /></el-form-item>
              <el-form-item label="沙土重量(kg)" prop="sandWeight"><el-input-number style="width:100%" v-model="formData.sandWeight" :precision="2" :step="0.1" :min="0" /></el-form-item>
            </div>
            <div class="mobile-form__input-group">
              <el-form-item label="感官" prop="sensoryEvaluation"><el-input v-model="formData.sensoryEvaluation" placeholder="请输入感官评价" /></el-form-item>
              <el-form-item label="合格率(%)" prop="qualificationRate"><el-input v-model="formData.qualificationRate" placeholder="请输入合格率" /></el-form-item>
            </div>
            <div class="mobile-form__input-group">
              <el-form-item label="水分(%)" prop="moistureContent"><el-input v-model="formData.moistureContent" placeholder="请输入水分含量" /></el-form-item>
              <el-form-item label="含糖(%)" prop="sugarContent"><el-input v-model="formData.sugarContent" placeholder="请输入含糖量" /></el-form-item>
            </div>
            <div class="mobile-form__input-group">
              <el-form-item label="RA值" prop="raValue"><el-input v-model="formData.raValue" placeholder="请输入RA值" /></el-form-item>
              <el-form-item label="STV值" prop="stvValue"><el-input v-model="formData.stvValue" placeholder="请输入STV值" /></el-form-item>
            </div>
            <el-form-item label="化验员" prop="labTechnician"><el-input v-model="formData.labTechnician" placeholder="请输入化验员姓名" /></el-form-item>
            <el-form-item label="检验备注" prop="inspectionRemark"><el-input type="textarea" v-model="formData.inspectionRemark" :rows="2" placeholder="请输入检验相关备注" /></el-form-item>
            <el-form-item label="附件" prop="fileUrl"><UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" /></el-form-item>
          </div>
        </template>
      </el-form>
      <div class="mobile-form__footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="formLoading">确 定</el-button>
      </div>
    </div>
  </el-drawer>

  <!-- PC端布局 -->
  <el-dialog v-else v-model="dialogVisible" :title="dialogTitle" width="800">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <h3 class="form-section-title">基本信息</h3>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="过磅单号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="原料" prop="productId">
            <el-select
              v-model="formData.productId"
              placeholder="请选择原料"
              filterable
              class="w-1/1"
              @change="handleProductChange"
              clearable
            >
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 番茄：交售农户 -->
      <el-row :gutter="20" v-if="isTomato">
        <el-col :span="12">
          <el-form-item label="交售农户" prop="supplierName">
            <el-select
              v-model="formData.supplierName"
              filterable
              remote
              :remote-method="remoteSupplierFarmerMethod"
              :loading="supplierLoadingFarmer"
              placeholder="请选择交售农户"
              @change="handleSupplierChange"
              clearable
            >
              <el-option
                v-for="item in supplierOptionsFarmer"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="农户身份证号" prop="idCardNumber">
            <el-input v-model="formData.idCardNumber" placeholder="农户身份证号" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 番茄：手机号码 -->
      <el-row :gutter="20" v-if="isTomato">
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
      </el-row>



      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毛重(t)" prop="grossWeight">
            <el-input-number
              style="width: 100%"
              v-model="formData.grossWeight"
              :precision="2"
              :step="0.1"
              :min="0"
              @change="calculateNetWeight"
            />
<!--            <span class="ml-2 text-red-500">注：{{ formData.grossWeight ? (formData.grossWeight / 1000).toFixed(3) + ' 吨' : '' }}</span>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="皮重(t)" prop="tareWeight">
            <el-input-number
              style="width: 100%"
              v-model="formData.tareWeight"
              :precision="2"
              :step="0.1"
              :min="0"
              @change="calculateNetWeight"
            />
<!--            <span class="ml-2 text-red-500">注：{{ formData.tareWeight ? (formData.tareWeight / 1000).toFixed(3) + ' 吨' : '' }}</span>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="承运司机" prop="driver">
            <el-select
              v-model="formData.driver"
              filterable
              remote
              :remote-method="remoteDriverMethod"
              :loading="driverLoading"
              placeholder="请选择承运司机"
              @change="handleDriverChange"
              clearable
              allow-create
              default-first-option
            >
              <el-option
                v-for="item in driverOptions"
                :key="item.id"
                :label="item.driverName"
                :value="item.driverName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车号" prop="vehicleNumber">
            <el-input v-model="formData.vehicleNumber" placeholder="请输入车号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="净重(t)" prop="netWeight">
            <el-input-number
              style="width: 100%"
              v-model="formData.netWeight"
              :precision="2"
              :step="0.1"
              :min="0"
              disabled
            />
<!--            <span class="ml-2 text-red-500">注：{{ formData.netWeight ? (formData.netWeight / 1000).toFixed(3) + ' 吨' : '' }}</span>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="扣杂率(%)" prop="impurityRate">
            <el-input-number
              style="width: 100%"
              v-model="formData.impurityRate"
              :precision="2"
              :step="0.1"
              :min="0"
              :max="100"
              @change="calculatePlannedWeight"
            />
            <span v-if="isStevia" class="ml-2 text-gray-400">（甜叶菊不参与扣杂率计算）</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!-- 番茄：产地凭证号 -->
        <el-col :span="12" v-if="isTomato">
          <el-form-item label="产地凭证号" prop="originCertificateNumber">
            <el-input v-model="formData.originCertificateNumber" placeholder="请输入产地凭证号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划重量(t)" prop="plannedWeight">
            <el-input-number
              style="width: 100%"
              v-model="formData.plannedWeight"
              :precision="2"
              :step="0.1"
              :min="0"
              disabled
            />
<!--            <span class="ml-2 text-red-500">注：{{ formData.plannedWeight ? (formData.plannedWeight / 1000).toFixed(3) + ' 吨' : '' }}</span>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="剩余重量(t)" prop="remainingWeight">
            <el-input-number
              style="width: 100%"
              v-model="formData.remainingWeight"
              :precision="2"
              :step="0.1"
              :min="0"
              disabled
            />
<!--            <span class="ml-2 text-red-500">注：{{ formData.remainingWeight ? (formData.remainingWeight / 1000).toFixed(3) + ' 吨' : '' }}</span>-->
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 甜叶菊：供应商 -->
      <el-row :gutter="20" v-if="isStevia">
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierName2">
            <el-select
              v-model="formData.supplierName2"
              filterable
              remote
              :remote-method="remoteSupplierVendorMethod"
              :loading="supplierLoadingVendor"
              placeholder="请选择供应商"
              @change="handleSupplierChange2"
              clearable
            >
              <el-option
                v-for="item in supplierOptionsVendor"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!-- 番茄：管理员 -->
        <el-col :span="12" v-if="isTomato">
          <el-form-item label="管理员" prop="administrator">
            <el-input v-model="formData.administrator" placeholder="请输入管理员姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="司磅员" prop="weigher">
            <el-input v-model="formData.weigher" placeholder="请输入司磅员姓名" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              :rows="2"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 新增字段部分 - 仅甜叶菊显示 -->
      <template v-if="isStevia">
        <h3 class="form-section-title">检验信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="取样日期" prop="sampleDate">
              <el-date-picker
                v-model="formData.sampleDate"
                type="date"
                placeholder="请选择取样日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="取样地点" prop="sampleLocation">
              <el-input v-model="formData.sampleLocation" placeholder="请输入取样地点" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="代表重量(kg)" prop="representativeWeight">
              <el-input-number
                style="width: 100%"
                v-model="formData.representativeWeight"
                :precision="2"
                :step="0.1"
                :min="0"
              />
              <span class="ml-2 text-red-500">注：{{ formData.representativeWeight ? (formData.representativeWeight / 1000).toFixed(3) + ' 吨' : '' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="样品重量(kg)" prop="sampleWeight">
              <el-input-number
                style="width: 100%"
                v-model="formData.sampleWeight"
                :precision="2"
                :step="0.1"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="杂质重量(kg)" prop="impurityWeight">
              <el-input-number
                style="width: 100%"
                v-model="formData.impurityWeight"
                :precision="2"
                :step="0.1"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="沙土重量(kg)" prop="sandWeight">
              <el-input-number
                style="width: 100%"
                v-model="formData.sandWeight"
                :precision="2"
                :step="0.1"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="感官" prop="sensoryEvaluation">
              <el-input v-model="formData.sensoryEvaluation" placeholder="请输入感官评价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格率(%)" prop="qualificationRate">
              <el-input v-model="formData.qualificationRate" placeholder="请输入合格率" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="水分(%)" prop="moistureContent">
              <el-input v-model="formData.moistureContent" placeholder="请输入水分含量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含糖(%)" prop="sugarContent">
              <el-input v-model="formData.sugarContent" placeholder="请输入含糖量" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="RA值" prop="raValue">
              <el-input v-model="formData.raValue" placeholder="请输入RA值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="STV值" prop="stvValue">
              <el-input v-model="formData.stvValue" placeholder="请输入STV值" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="化验员" prop="labTechnician">
              <el-input v-model="formData.labTechnician" placeholder="请输入化验员姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="检验备注" prop="inspectionRemark">
              <el-input
                type="textarea"
                v-model="formData.inspectionRemark"
                :rows="2"
                placeholder="请输入检验相关备注"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="附件" prop="fileUrl">
              <UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="formLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage } from 'element-plus'
import { SupplierApi } from '@/api/erp/purchase/supplier'
import { FarmerApi } from '@/api/erp/purchase/farmer'
import { WeighApi } from '@/api/erp/purchase/weigh'
import { getCarPage } from '@/api/erp/purchase/car'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

// 定义供应商数据类型
interface SupplierItem {
  id: number
  name: string
  idCardNumber?: string
  mobile?: string
  [key: string]: any
}

// 定义司机车辆数据类型
interface DriverCarItem {
  id: number
  driverName: string
  vehicleNumber: string
  [key: string]: any
}

const emit = defineEmits(['success'])
const { t } = useI18n()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formRef = ref()

// 判断是否为番茄
const isTomato = computed(() => {
  return formData.productName && formData.productName.includes('番茄')
})

// 判断是否为甜叶菊
const isStevia = computed(() => {
  return formData.productName && formData.productName.includes('甜叶菊')
})

// 供应商（农户）下拉
const supplierOptionsFarmer = ref<SupplierItem[]>([])
const supplierLoadingFarmer = ref(false)
// 供应商（供应商）下拉
const supplierOptionsVendor = ref<SupplierItem[]>([])
const supplierLoadingVendor = ref(false)

const driverOptions = ref<DriverCarItem[]>([])
const driverLoading = ref(false)
const productOptions = ref<ProductVO[]>([])

// 在formData对象中添加新字段
const formData = reactive({
  id: undefined,
  no: undefined, // 过磅单号，后端返回
  supplierName: '',
  supplierName2: '',
  idCardNumber: '',
  mobile: '', // 新增手机号码字段
  // 新增产品字段
  productId: undefined as undefined | number,
  productName: '' as string,
  grossWeight: 0,
  tareWeight: 0,
  vehicleNumber: '',
  driver: '',
  netWeight: 0,
  administrator: '',
  impurityRate: 0,
  originCertificateNumber: '',
  plannedWeight: 0,
  remainingWeight: 0,
  weigher: '',
  remark: '',
  fileUrl: '',
  // 新增字段
  sampleDate: undefined as string | undefined,
  sampleLocation: '',
  representativeWeight: 0,
  sampleWeight: 0,
  impurityWeight: 0,
  sandWeight: 0,
  sensoryEvaluation: '',
  qualificationRate: '',
  moistureContent: '',
  sugarContent: '',
  raValue: '',
  stvValue: '',
  labTechnician: '',
  inspectionRemark: '',
})

const formRules = reactive({
  // supplierName: [{ required: true, message: '请选择交售农户', trigger: 'change' }],
  // 新增产品校验
  // productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  mobile: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }],
  grossWeight: [{ required: true, message: '请输入毛重', trigger: 'blur' }],
  tareWeight: [{ required: true, message: '请输入皮重', trigger: 'blur' }],
  vehicleNumber: [{ required: true, message: '请输入车号', trigger: 'blur' }],
  driver: [{ required: true, message: '请输入承运司机', trigger: 'blur' }],
  administrator: [{ required: true, message: '请输入管理员姓名', trigger: 'blur' }],
  weigher: [{ required: true, message: '请输入司磅员姓名', trigger: 'blur' }]
})

const calculateNetWeight = () => {
  if (formData.grossWeight && formData.tareWeight) {
    formData.netWeight = Math.max(0, formData.grossWeight - formData.tareWeight)
    calculatePlannedWeight()
  }
}

const calculatePlannedWeight = () => {
  if (formData.netWeight) {
    // 如果是甜叶菊，计划重量等于净重，不参与扣杂率计算
    if (isStevia.value) {
      formData.plannedWeight = formData.netWeight
    } else {
      // 番茄等其他原料，需要扣除杂质
      if (formData.impurityRate >= 0) {
        const deduction = formData.netWeight * (formData.impurityRate / 100)
        formData.plannedWeight = Math.max(0, formData.netWeight - deduction)
      }
    }
    // 新增时，剩余重量等于计划重量
    if (!formData.id) {
      formData.remainingWeight = formData.plannedWeight
    }
  }
}

// 农户远程搜索（使用分页接口）
const remoteSupplierFarmerMethod = async (query: string) => {
  supplierLoadingFarmer.value = true
  try {
    const res = await FarmerApi.getFarmerPage({
      pageNo: 1,
      pageSize: 100,
      name: query || undefined
    })
    console.log('Farmer page response:', res) // 添加日志以便调试
    supplierOptionsFarmer.value = res.list || []
  } catch (error) {
    console.error('Failed to fetch farmer suppliers:', error)
  } finally {
    supplierLoadingFarmer.value = false
  }
}

// 供应商远程搜索（type=1）
const remoteSupplierVendorMethod = async (query: string) => {
  supplierLoadingVendor.value = true
  try {
    const res = await SupplierApi.getSupplierPage({
      pageNo: 1,
      pageSize: 100,
      name: query || undefined,
      type: 1
    })
    supplierOptionsVendor.value = res.list || []
  } catch (error) {
    console.error('Failed to fetch vendors:', error)
  } finally {
    supplierLoadingVendor.value = false
  }
}

// 加载供应商数据
const loadSupplierOptions = () => {
  remoteSupplierFarmerMethod('')
  remoteSupplierVendorMethod('')
}

const handleSupplierChange = (value: string) => {
  console.log('handleSupplierChange called with value:', value) // 添加日志以便调试
  const selectedSupplier = supplierOptionsFarmer.value.find(item => item.name === value)
  if (selectedSupplier) {
    formData.idCardNumber = selectedSupplier.idCardNumber || ''
    formData.mobile = selectedSupplier.mobile || ''
    formData.administrator = selectedSupplier.adminName || ''
    console.log('Selected supplier:', selectedSupplier) // 添加日志以便调试
  } else {
    formData.idCardNumber = ''
    formData.mobile = ''
    formData.administrator = ''
  }
}

const handleSupplierChange2 = (value: string) => {
  console.log('handleSupplierChange called with value:', value) // 添加日志以便调试
  const selectedSupplier = supplierOptionsVendor.value.find(item => item.name === value)
  if (selectedSupplier) {
    formData.mobile = selectedSupplier.mobile || ''
    console.log('Selected supplier:', selectedSupplier) // 添加日志以便调试
  } else {
    formData.mobile = ''
  }
}


// 远程搜索司机数据
const remoteDriverMethod = async (query: string) => {
  driverLoading.value = true
  try {
    const res = await getCarPage({
      pageNo: 1,
      pageSize: 100,
      driverName: query || undefined
    })
    driverOptions.value = res.list || []
  } catch (error) {
    console.error('Failed to fetch drivers:', error)
  } finally {
    driverLoading.value = false
  }
}

// 处理司机选择变更，联动车牌号
const handleDriverChange = (value: string) => {
  const selectedDriver = driverOptions.value.find(item => item.driverName === value)
  if (selectedDriver) {
    formData.vehicleNumber = selectedDriver.licensePlate || ''
  } else {
    formData.vehicleNumber = ''
  }
}

// 加载司机数据
const loadDriverOptions = () => {
  remoteDriverMethod('')
}

// 新增：加载产品列表
const loadProductOptions = async () => {
  try {
    const list = await ProductApi.getProductSimpleList()
    productOptions.value = Array.isArray(list) ? list : []
  } catch (error) {
    console.error('Failed to fetch products:', error)
  }
}

// 新增：处理产品选择，写入产品名称
const handleProductChange = (value: number | undefined) => {
  const selected = productOptions.value.find((p) => p.id === value)
  formData.productName = selected ? selected.name : ''
  // 切换原料后重新计算计划重量
  calculatePlannedWeight()
}

const open = (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增过磅单' : '编辑过磅单'
  resetForm()

  // 加载供应商数据
  loadSupplierOptions()

  // 加载司机数据
  loadDriverOptions()

  // 新增：加载产品数据
  loadProductOptions()

  // 如果是编辑模式，需要获取数据
  if (id) {
    formLoading.value = true
    // 获取过磅单详情
    WeighApi.getWeigh(id).then(response => {
      Object.assign(formData, response)
      // 编辑时也需要重新计算一次，确保计划重量正确
      calculatePlannedWeight()
      formLoading.value = false
    }).catch(error => {
      console.error('Failed to fetch weigh record:', error)
      formLoading.value = false
    })
  }
}

const submitForm = async () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    formLoading.value = true
    try {
      // 创建或更新过磅单
      if (formData.id) {
        await WeighApi.updateWeigh(formData)
      } else {
        await WeighApi.createWeigh(formData)
      }
      ElMessage.success(t('新增成功'))
      dialogVisible.value = false
      // 触发列表刷新事件
      emit('success')
    } catch (error) {
      console.error(error)
      ElMessage.error(t('common.saveFailText'))
    } finally {
      formLoading.value = false
    }
  })
}

// 在resetForm函数中添加新字段的重置
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: undefined,
    no: undefined,
    supplierName: '',
    supplierName2: '',
    idCardNumber: '',
    mobile: '', // 重置手机号码字段
    // 重置产品字段
    productId: undefined,
    productName: '',
    grossWeight: 0,
    tareWeight: 0,
    vehicleNumber: '',
    driver: '',
    netWeight: 0,
    administrator: '',
    impurityRate: 0,
    originCertificateNumber: '',
    plannedWeight: 0,
    remainingWeight: 0,
    weigher: '',
    remark: '',
    fileUrl: '',
    // 重置新增字段
    sampleDate: undefined,
    sampleLocation: '',
    representativeWeight: 0,
    sampleWeight: 0,
    impurityWeight: 0,
    sandWeight: 0,
    sensoryEvaluation: '',
    qualificationRate: '',
    moistureContent: '',
    sugarContent: '',
    raValue: '',
    stvValue: '',
    labTechnician: '',
    inspectionRemark: '',
  })
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.form-section-title {
  margin: 15px 0;
  padding-left: 10px;
  border-left: 3px solid #409eff;
  font-size: 16px;
  color: #606266;
}

.mobile-form {
  padding: 12px;
}
.mobile-form__section {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}
.mobile-form__section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}
.mobile-form__input-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}
.mobile-form__footer {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 12px 16px;
  padding-bottom: calc(12px + constant(safe-area-inset-bottom));
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  z-index: 10;
  margin: 0 -12px -12px;
  .el-button {
    flex: 1;
    height: 40px;
    font-size: 15px;
  }
}
</style>
