<template>
  <div class="app-container">
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>销售管理</el-breadcrumb-item>
      <el-breadcrumb-item>销售记录</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="销售日期" prop="saleDate" style="width: 100%">
            <el-date-picker
              v-model="queryParams.saleDate"
              type="date"
              placeholder="选择销售日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="耳号" prop="bsManageTagsList" style="width: 100%">
            <el-select
              v-model="queryParams.bsManageTagsList"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="输入耳号搜索，支持多选"
              :remote-method="searchEarNumberMethod"
              :loading="earNumberLoading"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in earNumberQueryOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
           <el-form-item label="性别" prop="gender" style="width: 100%">
            <el-select v-model="queryParams.gender" placeholder="请选择" clearable style="width: 100%">
              <el-option label="公" value="公" />
              <el-option label="母" value="母" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
           <el-form-item label="羊只类型" prop="sheepName" style="width: 100%">
             <el-select v-model="queryParams.sheepName" placeholder="请选择" clearable style="width: 100%">
                <el-option label="羔羊" value="羔羊" />
                <el-option label="成年羊" value="成年羊" />
                <el-option label="后备羊" value="后备羊" />
                <el-option label="种羊" value="种羊" />
             </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="繁育状态" prop="breed" style="width: 100%">
            <el-select v-model="queryParams.breed" placeholder="请选择" clearable style="width: 100%">
              <el-option label="空怀" value="空怀" />
              <el-option label="妊娠" value="妊娠" />
              <el-option label="哺乳" value="哺乳" />
              <el-option label="备配" value="备配" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
           <el-form-item label="销售类别" prop="saleType" style="width: 100%">
            <el-select v-model="queryParams.saleType" placeholder="请选择" clearable style="width: 100%">
              <el-option v-for="item in staticSaleTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
           <el-form-item label="计价方式" prop="pricingMethod" style="width: 100%">
            <el-select v-model="queryParams.pricingMethod" placeholder="请选择" clearable style="width: 100%">
              <el-option label="按个体" value="按个体" />
              <el-option label="按体重" value="按体重" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
           <el-form-item label="客户名称" prop="customerName" style="width: 100%">
            <el-select 
              v-model="queryParams.customerName" 
              filterable 
              clearable 
              placeholder="请选择或输入搜索" 
              style="width: 100%">
              <el-option 
                v-for="item in customerOptions" 
                :key="item.id" 
                :label="item.name" 
                :value="item.name" 
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="6">
           <el-form-item label="所在地区" prop="customerArea" style="width: 100%">
            <el-cascader
              v-model="selectedQueryArea"
              :options="regionData"
              :props="{ checkStrictly: true, label: 'label', value: 'label' }"
              placeholder="请选择省/市/区"
              clearable
              style="width: 100%"
              @change="handleQueryAreaChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
           <el-form-item label="销售人员" prop="salesPersonId" style="width: 100%">
            <el-select v-model="queryParams.salesPersonId" filterable placeholder="请选择" clearable style="width: 100%">
              <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName" :value="user.userId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
           <el-form-item label="审批编号" prop="approvalNo" style="width: 100%">
            <el-input v-model="queryParams.approvalNo" placeholder="支持模糊查询" clearable style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
           <el-form-item label="班组" prop="groupCode" style="width: 100%">
            <el-select v-model="queryParams.groupCode" placeholder="请选择" clearable style="width: 100%">
              <el-option v-for="item in staticGroupOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="24" style="text-align: center; margin-bottom: 10px;">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <div v-if="queryParams.bsManageTagsList && queryParams.bsManageTagsList.length > 0" class="selected-ear-numbers" style="margin-bottom: 10px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
      <span style="margin-right: 10px; color: #606266;">已选择耳号：</span>
      <el-tag
          v-for="tag in queryParams.bsManageTagsList"
          :key="tag"
          closable
          @close="removeQueryEarTag(tag)"
          style="margin-right: 8px;"
      >
        {{ tag }}
      </el-tag>
      <el-button type="text" size="small" @click="clearQueryEarTags">清空</el-button>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['saleRecord:saleRecord:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['saleRecord:saleRecord:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['saleRecord:saleRecord:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['saleRecord:saleRecord:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="saleRecordList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" fixed="left"/>
      <el-table-column label="耳号" align="center" prop="bsManageTags" width="120" fixed="left" show-overflow-tooltip />
      <el-table-column label="品种" align="center" prop="variety" width="100" show-overflow-tooltip />
      <el-table-column label="事件类型" align="center" prop="eventType" width="80" />
      <el-table-column label="销售日期" align="center" prop="saleDate" width="100">
        <template #default="scope"><span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span></template>
      </el-table-column>
      <el-table-column label="羊只类型" align="center" prop="sheepName" width="100" show-overflow-tooltip />
      <el-table-column label="性别" align="center" prop="gender" width="60" />
      <el-table-column label="月龄" align="center" prop="monthAge" width="60" />
      <el-table-column label="胎次" align="center" prop="parity" width="60" />
      
      <el-table-column label="当前重量(kg)" align="center" prop="currentWeight" width="110" />
      
      <el-table-column label="计价方式" align="center" prop="pricingMethod" width="100" />
      <el-table-column label="单价" align="center" prop="unitPrice" width="100">
         <template #default="scope">
           {{ scope.row.unitPrice }} 
           <span v-if="scope.row.pricingMethod=='按体重'">元/kg</span>
           <span v-else-if="scope.row.unitPrice">元</span>
         </template>
      </el-table-column>
      <el-table-column label="重量(kg)" align="center" prop="avgWeight" width="100" />
      <el-table-column label="单只羊价格(元)" align="center" prop="avgPricePerSheep" width="120" />
      
      <el-table-column label="销售类别" align="center" prop="saleType" width="100" show-overflow-tooltip />
      <el-table-column label="客户名称" align="center" prop="customerName" width="120" show-overflow-tooltip />
      <el-table-column label="客户电话" align="center" prop="customerPhone" width="120" show-overflow-tooltip />
      <el-table-column label="所在地区" align="center" prop="customerArea" width="150" show-overflow-tooltip />
      <el-table-column label="详细地址" align="center" prop="customerAddress" width="180" show-overflow-tooltip />
      <el-table-column label="销售人员" align="center" prop="salesPersonName" width="100" />
      <el-table-column label="检疫证号" align="center" prop="quarantineNo" width="120" show-overflow-tooltip />
      <el-table-column label="审批编号" align="center" prop="approvalNo" width="120" show-overflow-tooltip />
      <el-table-column label="疾病类型" align="center" prop="diseaseType" :formatter="diseaseTypeFormat" width="100" show-overflow-tooltip />
      <el-table-column label="次要原因" align="center" prop="secondaryReason" width="120" show-overflow-tooltip />
      <el-table-column label="羊舍" align="center" prop="sheepfoldName" width="120" show-overflow-tooltip />
      <el-table-column label="班组" align="center" prop="groupCode" width="100" />
      <el-table-column label="繁育状态" align="center" prop="breed" width="80" />
      <el-table-column label="产后天数" align="center" prop="postLambingDay" width="80" />
      <el-table-column label="泌乳天数" align="center" prop="lactationDay" width="80" />
      <el-table-column label="怀孕天数" align="center" prop="lambingDay" width="80" />
      <el-table-column label="技术员" align="center" prop="technicianName" width="100" />
      <el-table-column label="处理人" align="center" prop="handlerName" width="100" />
      <el-table-column label="创建人" align="center" prop="createdByName" width="100" />
      <el-table-column label="创建日期" align="center" prop="createdAt" width="100">
         <template #default="scope"><span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span></template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="150" show-overflow-tooltip />
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['saleRecord:saleRecord:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['saleRecord:saleRecord:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="羊舍" prop="sheepfoldId">
               <el-select v-model="form.sheepfoldId" placeholder="请选择羊舍" filterable clearable @change="handleSheepfoldChange" style="width: 100%">
                 <el-option v-for="item in sheepfoldOptions" :key="item.id" :label="item.sheepfoldName || item.name" :value="item.id" />
               </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
             <el-form-item label="耳号" prop="bsManageTagsList">
               <el-select 
                  v-model="form.bsManageTagsList" 
                  multiple 
                  filterable 
                  allow-create 
                  default-first-option 
                  placeholder="手动输入或选择" 
                  style="width: 100%" 
                  @change="handleTagChange">
                  <el-option v-for="tag in earTagOptions" :key="tag" :label="tag" :value="tag" />
               </el-select>
             </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事件类型">
               <el-input v-model="form.eventType" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售日期" prop="saleDate">
              <el-date-picker v-model="form.saleDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="当前体重(kg)">
                <el-input v-model="form.currentWeight" disabled placeholder="根据档案自动生成" />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="计价方式" prop="pricingMethod">
                <el-select v-model="form.pricingMethod" placeholder="请选择" style="width: 100%" @change="handlePricingMethodChange">
                  <el-option label="按个体" value="按个体" />
                  <el-option label="按体重" value="按体重" />
                </el-select>
             </el-form-item>
           </el-col>
        </el-row>

        <el-divider content-position="left">价格计算信息</el-divider>
        <el-row :gutter="20" v-if="form.pricingMethod === '按个体'">
           <el-col :span="8">
             <el-form-item label="单价(元/只)" prop="unitPrice">
               <el-input-number v-model="form.unitPrice" :precision="2" :step="100" style="width:100%" @input="calculatePrice" />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="总价(元)">
               <el-input v-model="form.totalPrice" disabled />
             </el-form-item>
           </el-col>
             <el-col :span="8">
             <el-form-item label="羊只数量">
                <span>{{ sheepCount }} 只</span>
             </el-form-item>
           </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.pricingMethod === '按体重'">
           <el-col :span="6">
             <el-form-item label="单价(元/kg)" prop="unitPrice">
               <el-input-number v-model="form.unitPrice" :precision="2" :step="1" style="width:100%" @input="calculatePrice" />
             </el-form-item>
           </el-col>
           <el-col :span="6">
             <el-form-item label="总体重(kg)" prop="totalWeight">
               <el-input-number v-model="form.totalWeight" :precision="2" :step="10" style="width:100%" @input="calculatePrice" />
             </el-form-item>
           </el-col>
           <el-col :span="6">
             <el-form-item label="总价(元)">
               <el-input v-model="form.totalPrice" disabled />
             </el-form-item>
           </el-col>
           <el-col :span="6">
             <el-form-item label="平均体重/均价">
               <span style="font-size:12px; color:#909399">
                 均重: {{ form.avgWeight }}kg <br/> 均价: {{ form.avgPricePerSheep }}元
               </span>
             </el-form-item>
           </el-col>
        </el-row>

        <el-divider />

        <el-row :gutter="20">
           <el-col :span="8">
              <el-form-item label="销售类别" prop="saleType">
                 <el-select v-model="form.saleType" style="width:100%" @change="handleSaleTypeChange">
                    <el-option v-for="item in staticSaleTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
                 </el-select>
              </el-form-item>
           </el-col>
           <el-col :span="8" v-if="isElimination">
              <el-form-item label="疾病类型" prop="diseaseType">
                 <el-select v-model="form.diseaseType" style="width:100%" @change="handleDiseaseChange">
                   <el-option 
                     v-for="item in staticDiseaseTypeOptions" 
                     :key="item.value" 
                     :label="item.label" 
                     :value="item.value"
                   />
                 </el-select>
              </el-form-item>
           </el-col>
           <el-col :span="8" v-if="isSick">
              <el-form-item label="次要原因" prop="secondaryReason">
                 <el-input v-model="form.secondaryReason" />
              </el-form-item>
           </el-col>
        </el-row>

        <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="客户名称" prop="customerId">
               <el-select 
                  v-model="form.customerId" 
                  filterable 
                  remote 
                  :remote-method="remoteMethodGetCustomer"
                  :loading="customerLoading"
                  placeholder="请输入名称查询"
                  style="width: 100%"
                  @change="handleCustomerChange">
                  <el-option v-for="item in customerOptions" :key="item.id" :label="item.name" :value="item.id" />
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="12">
              <el-form-item label="销售人员" prop="salesPersonId">
                <el-select v-model="form.salesPersonId" filterable placeholder="请选择" style="width:100%">
                   <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName" :value="user.userId" />
                </el-select>
              </el-form-item>
           </el-col>
        </el-row>

        <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="检疫证号">
               <el-input v-model="form.quarantineNo" placeholder="选填" />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="审批编号" prop="approvalNo">
               <el-input v-model="form.approvalNo" placeholder="必填" />
             </el-form-item>
           </el-col>
        </el-row>

        <el-row :gutter="20">
           <el-col :span="8">
             <el-form-item label="班组" prop="groupCode">
                <el-select v-model="form.groupCode" placeholder="必填" style="width:100%">
                  <el-option v-for="item in staticGroupOptions" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="技术员" prop="technicianId">
                <el-select v-model="form.technicianId" filterable placeholder="必选" style="width:100%">
                   <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName" :value="user.userId" />
                </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="处理人" prop="handlerId">
                <el-select v-model="form.handlerId" filterable placeholder="必选" style="width:100%">
                   <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName" :value="user.userId" />
                </el-select>
             </el-form-item>
           </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="form.remark" placeholder="选填" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, computed, getCurrentInstance, onMounted } from 'vue'
import { 
  listSaleRecord, getSaleRecord, delSaleRecord, addSaleRecord, updateSaleRecord, 
  getSheepInfo, listSheepInventory, searchEarNumbers 
} from '@/api/sale/saleRecord/saleRecord'
import { listSheepfold_management } from '@/api/fileManagement/sheepfold_management'
import { listUser } from '@/api/system/user'
import { listCustomer } from '@/api/sale/customer/customer'
import { regionData } from 'element-china-area-data'

const { proxy } = getCurrentInstance()
const { disease_type } = proxy.useDict('disease_type') 

const saleRecordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const selectedQueryArea = ref([])

// 搜索栏耳号查询候选项
const earNumberQueryOptions = ref([])
const earNumberLoading = ref(false)

const staticSaleTypeOptions = ref([
  { label: '肉羊销售', value: '肉羊销售' },
  { label: '种羊销售', value: '种羊销售' },
  { label: '淘汰销售', value: '淘汰销售' },
  { label: '羊只销售', value: '羊只销售' },
  { label: '羊只屠宰', value: '羊只屠宰' },
  { label: '肉羊屠宰', value: '肉羊屠宰' },
  { label: '淘汰屠宰', value: '淘汰屠宰' }
])

const staticGroupOptions = ref([
  { label: '产羔班', value: '产羔班' },
  { label: '保育班', value: '保育班' },
  { label: '繁育班', value: '繁育班' }
])

const staticDiseaseTypeOptions = ref([
  { label: '生产性能低', value: '生产性能低' },
  { label: '繁殖障碍', value: '繁殖障碍' },
  { label: '病残羊', value: '病残羊' }
])

const diseaseTypeOptions = ref([])
const sheepfoldOptions = ref([])
const earTagOptions = ref([])
const userOptions = ref([])
const customerOptions = ref([])
const customerLoading = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    saleDate: null,
    bsManageTags: null, // 为了兼容旧逻辑，这个字段也保留，但主要用 List
    bsManageTagsList: [], // 【修改】用于查询栏多选
    gender: null,
    sheepName: null,
    breed: null,
    saleType: null,
    pricingMethod: null,
    customerName: null,
    customerArea: null,
    salesPersonId: null,
    approvalNo: null,
    groupCode: null,
    orderByColumn: 'saleDate',
    isAsc: 'desc'
  },
  rules: {
    bsManageTagsList: [{ required: true, message: "耳号不能为空", trigger: "change" }],
    saleDate: [{ required: true, message: "销售日期不能为空", trigger: "blur" }],
    pricingMethod: [{ required: true, message: "计价方式不能为空", trigger: "change" }],
    unitPrice: [{ required: true, message: "单价不能为空", trigger: "blur" }],
    totalWeight: [{ required: true, message: "总体重不能为空", trigger: "blur" }],
    saleType: [{ required: true, message: "销售类别不能为空", trigger: "change" }],
    customerId: [{ required: true, message: "客户不能为空", trigger: "change" }],
    salesPersonId: [{ required: true, message: "销售人员不能为空", trigger: "change" }],
    approvalNo: [{ required: true, message: "审批编号不能为空", trigger: "blur" }],
    groupCode: [{ required: true, message: "班组不能为空", trigger: "change" }],
    technicianId: [{ required: true, message: "技术员不能为空", trigger: "change" }],
    handlerId: [{ required: true, message: "处理人不能为空", trigger: "change" }],
    diseaseType: [{ required: true, message: "疾病类型不能为空", trigger: "change" }],
    secondaryReason: [{ required: true, message: "次要原因不能为空", trigger: "blur" }],
  }
})

const { queryParams, form, rules } = toRefs(data)

const sheepCount = computed(() => {
  return Array.isArray(form.value.bsManageTagsList) ? form.value.bsManageTagsList.length : 0
})

const isElimination = computed(() => {
  const val = form.value.saleType
  return val && (val.includes('淘汰销售') || val.includes('淘汰屠宰'))
})

const isSick = computed(() => {
  const val = form.value.diseaseType
  return val === '病残羊'
})

onMounted(() => {
  diseaseTypeOptions.value = disease_type.value
  getList()
  getSheepfoldOptions()
  getUserOptions()
  
  // 加载客户列表
  listCustomer({ pageNum: 1, pageSize: 1000 }).then(r => {
    customerOptions.value = r.rows
  })
})

function getList() {
  loading.value = true
  listSaleRecord(queryParams.value).then(response => {
    saleRecordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function getUserOptions() {
  listUser({ pageNum: 1, pageSize: 1000 }).then(r => userOptions.value = r.rows)
}

function getSheepfoldOptions() {
  listSheepfold_management().then(r => sheepfoldOptions.value = r.rows || r.data)
}

function remoteMethodGetCustomer(query) {
  customerLoading.value = true
  listCustomer({ name: query, pageNum: 1, pageSize: 20 }).then(r => {
    customerOptions.value = r.rows
    customerLoading.value = false
  })
}

function handleQueryAreaChange(val) {
  if (val && val.length > 0) {
    queryParams.value.customerArea = val[val.length - 1] 
  } else {
    queryParams.value.customerArea = null
  }
}

// 【新增】远程搜索耳号方法
function searchEarNumberMethod(query) {
  if (query !== '') {
    earNumberLoading.value = true
    searchEarNumbers(query).then(res => {
      earNumberQueryOptions.value = res.data || []
      earNumberLoading.value = false
    }).catch(() => {
      earNumberQueryOptions.value = []
      earNumberLoading.value = false
    })
  } else {
    earNumberQueryOptions.value = []
  }
}

// 【新增】移除单个查询耳号
function removeQueryEarTag(tag) {
  const index = queryParams.value.bsManageTagsList.indexOf(tag)
  if (index > -1) {
    queryParams.value.bsManageTagsList.splice(index, 1)
  }
}

// 【新增】清空查询耳号
function clearQueryEarTags() {
  queryParams.value.bsManageTagsList = []
}

function handleSheepfoldChange(val) {
  form.value.bsManageTagsList = [] 
  earTagOptions.value = []
  if(val) {
     listSheepInventory({ sheepfoldId: val }).then(res => {
        const list = res.data || [] 
        earTagOptions.value = list
     }).catch(err => {
        console.error("获取耳号失败", err)
     })
  }
}

function handleTagChange(tags) {
   if (tags && tags.length > 0) {
     const lastTag = tags[tags.length - 1]
     getSheepInfo(lastTag).then(res => {
        if(res.data) {
          form.value.currentWeight = res.data.currentWeight
        }
     })
   }
   calculatePrice()
}

function calculatePrice() {
  const count = sheepCount.value || 1
  const price = parseFloat(form.value.unitPrice)
  if (form.value.pricingMethod === '按个体') {
     form.value.totalWeight = null
     form.value.avgWeight = null
     if (!isNaN(price)) {
        form.value.totalPrice = (price * count).toFixed(2)
        form.value.avgPricePerSheep = price.toFixed(2)
     }
  } else if (form.value.pricingMethod === '按体重') {
     const weight = parseFloat(form.value.totalWeight)
     if (!isNaN(price) && !isNaN(weight)) {
        form.value.totalPrice = (price * weight).toFixed(2)
        form.value.avgWeight = (weight / count).toFixed(2)
        form.value.avgPricePerSheep = (form.value.totalPrice / count).toFixed(2)
     }
  }
}

function handlePricingMethodChange() {
   form.value.unitPrice = undefined
   form.value.totalPrice = undefined
   form.value.totalWeight = undefined
   form.value.avgWeight = undefined
   form.value.avgPricePerSheep = undefined
}

function handleSaleTypeChange() {
  if (!isElimination.value) {
    form.value.diseaseType = null
    form.value.secondaryReason = null
  }
}

function handleDiseaseChange() {
  if (!isSick.value) {
    form.value.secondaryReason = null
  }
}

function handleCustomerChange(val) {}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm("queryForm")
  selectedQueryArea.value = [] 
  queryParams.value.customerArea = null
  queryParams.value.bsManageTagsList = [] // 重置耳号列表
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleAdd() {
  reset()
  open.value = true
  title.value = "新增羊只销售记录"
  form.value.eventType = '销售'
  form.value.saleDate = new Date().toISOString().slice(0, 10)
}

function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getSaleRecord(id).then(response => {
    form.value = response.data
    if (form.value.bsManageTags) {
       form.value.bsManageTagsList = form.value.bsManageTags.split(',')
    }
    open.value = true
    title.value = "修改羊只销售记录"
  })
}

function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSaleRecord(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSaleRecord(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

function handleDelete(row) {
  const deleteIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除选中的数据?').then(() => {
    return delSaleRecord(deleteIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

function handleExport() {
  proxy.download('saleRecord/saleRecord/export', {
    ...queryParams.value
  }, `saleRecord_${new Date().getTime()}.xlsx`)
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    id: null,
    bsManageTagsList: [],
    eventType: '销售',
    pricingMethod: null,
    unitPrice: undefined,
    totalWeight: undefined
  }
  proxy.resetForm("formRef")
}

function diseaseTypeFormat(row) {
  // 由于使用了静态选项，这里可以直接返回 row.diseaseType，或者使用 selectDictLabel 兼容字典
  // 如果静态选项 label 和 value 一样，则直接返回即可
  return row.diseaseType 
}
</script>

<style scoped>
.breadcrumb { margin-bottom: 16px; }
.el-row { margin-bottom: 10px; } 
.el-form-item__content { width: 100%; }
.el-input, .el-select, .el-cascader { width: 100%; }
.selected-ear-numbers {
  margin-bottom: 16px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>