<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="68px">
      <el-form-item label="耳号" prop="bsManageTags">
        <el-input
          v-model="queryParams.bsManageTags"
          placeholder="请输入耳号"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="销售日期" prop="saleDate">
        <el-date-picker
          v-model="queryParams.saleDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="small"
        />
      </el-form-item>

      <el-form-item label="销售类别" prop="saleType">
        <el-select v-model="queryParams.saleType" clearable placeholder="请选择" size="small" style="width: 180px">
          <el-option
            v-for="d in saleTypeOptions"
            :key="d.dictValue"
            :label="d.dictLabel"
            :value="d.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['saleRecord:saleRecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['saleRecord:saleRecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['saleRecord:saleRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['saleRecord:saleRecord:export']"
        >导出</el-button>
      </el-col>
      <!-- 修复：使用 v-model:showSearch 替代 :showSearch.sync -->
      <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" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="耳号" align="center" prop="bsManageTags" width="120" 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="100" show-overflow-tooltip />
      <el-table-column label="销售日期" align="center" prop="saleDate" width="120">
        <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="80" />
      <el-table-column label="月龄" align="center" prop="monthAge" width="80" />
      <el-table-column label="胎次" align="center" prop="parity" width="80" />
      <el-table-column label="计价方式" align="center" prop="pricingMethod" width="100" show-overflow-tooltip />
      <el-table-column label="单价" align="center" prop="unitPrice" width="100">
        <template #default="scope">
          <span v-if="scope.row.unitPrice !== null && scope.row.unitPrice !== undefined">{{ scope.row.unitPrice }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="总价" align="center" prop="totalPrice" width="100">
        <template #default="scope">
          <span v-if="scope.row.totalPrice !== null && scope.row.totalPrice !== undefined">{{ scope.row.totalPrice }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="总体重" align="center" prop="totalWeight" width="100">
        <template #default="scope">
          <span v-if="scope.row.totalWeight">{{ scope.row.totalWeight }}kg</span>
        </template>
      </el-table-column>
      <el-table-column label="平均体重" align="center" prop="avgWeight" width="100">
        <template #default="scope">
          <span v-if="scope.row.avgWeight">{{ scope.row.avgWeight }}kg</span>
        </template>
      </el-table-column>
      <el-table-column label="平均单只价格" align="center" prop="avgPricePerSheep" width="120">
        <template #default="scope">
          <span v-if="scope.row.avgPricePerSheep">{{ scope.row.avgPricePerSheep }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="销售类别" align="center" prop="saleType" width="120" :formatter="saleTypeFormat" show-overflow-tooltip />
      <el-table-column label="客户名称" align="center" prop="customerName" width="140" show-overflow-tooltip />
      <el-table-column label="客户电话" align="center" prop="customerPhone" width="130" 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="120" show-overflow-tooltip />
      <el-table-column label="检疫证号" align="center" prop="quarantineNo" width="130" show-overflow-tooltip />
      <el-table-column label="审批编号" align="center" prop="approvalNo" width="130" show-overflow-tooltip />
      <el-table-column label="疾病类型" align="center" prop="diseaseType" width="120" :formatter="diseaseTypeFormat" 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" :formatter="groupFormat" />
      <el-table-column label="繁育状态" align="center" prop="breed" width="100" show-overflow-tooltip />
      <el-table-column label="产后天数" align="center" prop="postLambingDay" width="90" />
      <el-table-column label="泌乳天数" align="center" prop="lactationDay" width="90" />
      <el-table-column label="怀孕天数" align="center" prop="lambingDay" width="90" />
      <el-table-column label="创建人" align="center" prop="createdByName" width="120" show-overflow-tooltip />
      <el-table-column label="创建日期" align="center" prop="createdAt" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="技术员" align="center" prop="technicianName" width="120" show-overflow-tooltip />
      <el-table-column label="处理人" align="center" prop="handlerName" width="120" show-overflow-tooltip />
      <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="150" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['saleRecord:saleRecord:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-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"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改羊只销售记录对话框 -->
    <!-- 修复：使用 v-model 替代 :visible.sync -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="羊舍" prop="sheepfoldId">
              <el-select
                v-model="form.sheepfoldId"
                placeholder="请选择羊舍"
                clearable
                @change="handleSheepfoldChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in sheepfoldOptions"
                  :key="item.id || item.sheepfoldId"
                  :label="item.sheepfoldName || item.name"
                  :value="item.id || item.sheepfoldId"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="耳号" prop="bsManageTagsList">
              <!-- 通过 allow-create + 回车新增耳号，使用 watch 捕捉新增项并拉取详情 -->
              <el-select
                v-model="form.bsManageTagsList"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请先选择羊舍，或手动输入耳号并回车确认"
                style="width: 100%"
              >
                <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="8"><el-form-item label="品种">{{ form.variety }}</el-form-item></el-col>
          <el-col :span="8"><el-form-item label="羊只类别">{{ form.sheepName }}</el-form-item></el-col>
          <el-col :span="8"><el-form-item label="性别">{{ form.gender }}</el-form-item></el-col>
          <el-col :span="8"><el-form-item label="月龄">{{ form.monthAge }}</el-form-item></el-col>
          <el-col :span="8"><el-form-item label="胎次">{{ form.parity }}</el-form-item></el-col>
          <el-col :span="8"><el-form-item label="繁育状态">{{ form.breed }}</el-form-item></el-col>
          <el-col :span="8"><el-form-item label="产后天数">{{ form.postLambingDay }}</el-form-item></el-col>
          <el-col :span="8"><el-form-item label="泌乳天数">{{ form.lactationDay }}</el-form-item></el-col>
          <el-col :span="8"><el-form-item label="怀孕天数">{{ form.lambingDay }}</el-form-item></el-col>
        </el-row>

        <el-divider />

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="事件类型" prop="eventType">
              <el-input v-model="form.eventType" placeholder="默认为销售" readonly />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="销售日期" prop="saleDate">
              <el-date-picker
                v-model="form.saleDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="计价方式" prop="pricingMethod">
              <el-select
                v-model="form.pricingMethod"
                placeholder="请选择计价方式"
                @change="handlePricingMethodChange"
                style="width: 100%"
              >
                <el-option label="按个体" value="按个体" />
                <el-option label="按体重" value="按体重" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 动态字段：按个体 -->
          <template v-if="form.pricingMethod === '按个体'">
            <el-col :span="8">
              <el-form-item label="单价(元/只)" prop="unitPrice">
                <el-input v-model="form.unitPrice" placeholder="请输入单价" @input="calculateIndividualPrice">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总价" prop="totalPrice">
                <el-input v-model="form.totalPrice" placeholder="自动计算" readonly>
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </template>

          <!-- 动态字段：按体重 -->
          <template v-if="form.pricingMethod === '按体重'">
            <el-col :span="8">
              <el-form-item label="总重量" prop="totalWeight">
                <el-input v-model="form.totalWeight" placeholder="请输入总重量" @input="calculateWeightPrice">
                  <template #append>kg</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单价(元/kg)" prop="unitPrice">
                <el-input v-model="form.unitPrice" placeholder="请输入单价" @input="calculateWeightPrice">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总价" prop="totalPrice">
                <el-input v-model="form.totalPrice" placeholder="自动计算" readonly>
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="平均体重">
                <el-input v-model="form.avgWeight" placeholder="自动计算" readonly>
                  <template #append>kg</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="平均单只价格">
                <el-input v-model="form.avgPricePerSheep" placeholder="自动计算" readonly>
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </template>
        </el-row>

        <el-divider />

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售类别" prop="saleType">
              <el-select
                v-model="form.saleType"
                placeholder="请选择销售类别"
                @change="handleSaleTypeChange"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in saleTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="form.customerId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入客户名称"
                :remote-method="remoteMethodGetCustomer"
                :loading="customerLoading"
                @change="handleCustomerChange"
                style="width: 100%"
              >
                <!-- 使用 sx_customer.name 作为显示字段 -->
                <el-option
                  v-for="item in customerOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 淘汰相关：仅在 销售类别=淘汰销售/淘汰屠宰 时显示 -->
          <template v-if="isEliminationSale">
            <el-col :span="12">
              <el-form-item label="疾病类型" prop="diseaseType">
                <el-select v-model="form.diseaseType" placeholder="请选择疾病类型" @change="handleDiseaseTypeChange" style="width: 100%">
                  <el-option
                    v-for="dict in diseaseTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="班组" prop="groupCode">
                <el-select v-model="form.groupCode" placeholder="请选择班组" style="width: 100%">
                  <el-option
                    v-for="dict in groupOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="diseaseTypeLabel === '病残羊'">
              <el-form-item label="次要原因" prop="secondaryReason">
                <el-input v-model="form.secondaryReason" placeholder="请输入次要原因" />
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="12">
            <el-form-item label="销售人员" prop="salesPersonId">
              <el-select v-model="form.salesPersonId" 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="12">
            <el-form-item label="检疫证号" prop="quarantineNo">
              <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-col :span="12">
            <el-form-item label="技术员" prop="technicianId">
              <el-select v-model="form.technicianId" 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="12">
            <el-form-item label="处理人" prop="handlerId">
              <el-select v-model="form.handlerId" 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="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="2" />
            </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>
import {
  listSaleRecord,
  getSaleRecord,
  delSaleRecord,
  addSaleRecord,
  updateSaleRecord,
  getSheepInfo,
} from '@/api/sale/saleRecord/saleRecord'
import { listSheepfold_management } from '@/api/fileManagement/sheepfold_management'
import { listUser } from '@/api/system/user'
import { getDicts } from '@/api/system/dict/data'
import { listCustomer } from '@/api/sale/customer/customer'

export default {
  name: 'SxSheepSale',
  data() {
    return {
      // 通用
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      saleRecordList: [],
      title: '',
      open: false,

      // 查询
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bsManageTags: null,
        sheepfoldId: null,
        saleDate: null,
        saleType: null,
      },

      // 表单
      form: {},

      // 字典
      saleTypeOptions: [],
      diseaseTypeOptions: [],
      groupOptions: [],

      // 下拉数据
      sheepfoldOptions: [],
      earTagOptions: [],
      userOptions: [],
      customerOptions: [],
      customerLoading: false,

      // 耳号变更侦听缓存
      _prevTags: [],

      // 校验规则（包含动态必填的自自定义 validator）
      rules: {
        sheepfoldId: [{ required: true, message: '羊舍不能为空', trigger: 'change' }],
        bsManageTagsList: [{ type: 'array', required: true, message: '至少需要一个耳号', trigger: 'change' }],
        saleDate: [{ required: true, message: '销售日期不能为空', trigger: 'change' }],
        pricingMethod: [{ required: true, message: '计价方式不能为空', trigger: 'change' }],
        unitPrice: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
        saleType: [{ required: true, message: '销售类别不能为空', trigger: 'change' }],
        customerId: [{ required: true, message: '客户不能为空', trigger: 'change' }],
        salesPersonId: [{ required: true, message: '销售人员不能为空', trigger: 'change' }],
        diseaseType: [
          {
            validator: (rule, val, cb) => {
              if (this.isEliminationSale && !val) return cb(new Error('淘汰销售必须选择疾病类型'))
              cb()
            },
            trigger: 'change',
          },
        ],
        groupCode: [
          {
            validator: (rule, val, cb) => {
              if (this.isEliminationSale && !val) return cb(new Error('淘汰销售必须选择班组'))
              cb()
            },
            trigger: 'change',
          },
        ],
        secondaryReason: [
          {
            validator: (rule, val, cb) => {
              if (this.diseaseTypeLabel === '病残羊' && !val) return cb(new Error('疾病类型为病残羊时必须填写次要原因'))
              cb()
            },
            trigger: 'blur',
          },
        ],
      },
    }
  },
  computed: {
    // 根据"标签(label)"判断淘汰类，避免 dictValue 不一致导致判断失效
    isEliminationSale() {
      const opt = this.saleTypeOptions.find(o => o.dictValue === this.form.saleType)
      const label = opt ? opt.dictLabel : ''
      return label === '淘汰销售' || label === '淘汰屠宰'
    },
    diseaseTypeLabel() {
      const opt = this.diseaseTypeOptions.find(o => o.dictValue === this.form.diseaseType)
      return opt ? opt.dictLabel : ''
    },
  },
  watch: {
    // 监听耳号多选变化：只对"新添加"的耳号拉取一次详情
    'form.bsManageTagsList'(val = []) {
      const added = Array.isArray(val) ? val.filter(v => !this._prevTags.includes(v)) : []
      if (added.length > 0) {
        this.fetchSheepInfo(added[added.length - 1])
      }
      this._prevTags = Array.isArray(val) ? [...val] : []

      // 计价联动
      if (this.form.pricingMethod === '按个体') {
        this.calculateIndividualPrice()
      } else if (this.form.pricingMethod === '按体重') {
        this.calculateWeightPrice()
      }
    },
    'form.unitPrice': function () {
      if (this.form.pricingMethod === '按个体') {
        this.calculateIndividualPrice()
      } else if (this.form.pricingMethod === '按体重') {
        this.calculateWeightPrice()
      }
    },
    'form.totalWeight': function () {
      if (this.form.pricingMethod === '按体重') this.calculateWeightPrice()
    }
  },
  created() {
    this.getList()
    this.getDictsData()
    this.getSheepfoldOptions()
    this.getUserOptions()
    this.remoteMethodGetCustomer('') // 初始化客户列表
  },
  methods: {
    /** 禁用未来日期 */
    disabledDate(time) {
      return time.getTime() > Date.now()
    },
    
    /** 查询列表 */
    getList() {
      this.loading = true
      listSaleRecord(this.queryParams)
        .then(res => {
          this.saleRecordList = res.rows || []
          this.total = res.total || 0
        })
        .finally(() => (this.loading = false))
    },

    // 字典翻译
    saleTypeFormat(row) {
      return this.selectDictLabel(this.saleTypeOptions, row.saleType)
    },
    diseaseTypeFormat(row) {
      return this.selectDictLabel(this.diseaseTypeOptions, row.diseaseType)
    },
    groupFormat(row) {
      return this.selectDictLabel(this.groupOptions, row.groupCode)
    },

    // 顶部搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 选择行
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 新增
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加羊只销售记录'
      this.form.eventType = '销售'
      // 设置销售日期默认值为今天 (保持与 value-format="yyyy-MM-dd" 一致的字符串格式)
      this.form.saleDate = new Date().toISOString().slice(0, 10)
    },

    // 修改
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSaleRecord(id).then(response => {
        this.form = response.data || {}
        if (this.form.bsManageTags) {
          this.form.bsManageTagsList = String(this.form.bsManageTags).split(',').filter(Boolean)
        }
        this._prevTags = Array.isArray(this.form.bsManageTagsList) ? [...this.form.bsManageTagsList] : []
        this.open = true
        this.title = '修改羊只销售记录'
      })
    },

    // 取消
    cancel() {
      this.open = false
      this.reset()
    },

    // 重置
    reset() {
      this.form = {
        id: null,
        bsManageTags: null,
        bsManageTagsList: [],
        sheepfoldId: null,
        variety: null,
        sheepName: null,
        gender: null,
        monthAge: null,
        parity: null,
        breed: null,
        postLambingDay: null,
        lactationDay: null,
        lambingDay: null,
        eventType: '销售',
        saleDate: null,
        pricingMethod: null,
        unitPrice: null,
        totalPrice: null,
        totalWeight: null,
        avgWeight: null,
        avgPricePerSheep: null,
        saleType: null,
        diseaseType: null,
        secondaryReason: null,
        groupCode: null,
        customerId: null,
        customerName: null,
        customerPhone: null,
        customerAddress: null,
        salesPersonId: null,
        salesPersonName: null,
        quarantineNo: null,
        approvalNo: null,
        technicianId: null,
        technicianName: null,
        handlerId: null,
        handlerName: null,
        createdBy: null,
        createdByName: null,
        createdAt: null,
        remark: null
      }
      this._prevTags = []
      this.resetForm('formRef')
    },

    /** 提交 */
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        // 耳号数组 → 逗号串
        if (Array.isArray(this.form.bsManageTagsList) && this.form.bsManageTagsList.length > 0) {
          this.form.bsManageTags = this.form.bsManageTagsList.join(',')
        } else {
          this.form.bsManageTags = null
        }

        // 由后端设置 createdBy / createdAt，更稳妥
        const api = this.form.id ? updateSaleRecord : addSaleRecord
        api(this.form)
          .then(() => {
            this.$modal.msgSuccess(this.form.id ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          })
          .catch(err => {
            this.$modal.msgError((this.form.id ? '修改失败：' : '新增失败：') + (err.message || '未知错误'))
          })
      })
    },

    /** 删除 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除羊只销售记录编号为"' + ids + '"的数据项？')
        .then(() => delSaleRecord(ids))
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    /** 导出 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有羊只销售记录数据项？').then(() => {
        this.download('/saleRecord/saleRecord/export', { ...this.queryParams }, `saleRecord_${new Date().getTime()}.xlsx`)
      })
    },

    /** 字典数据（注意 disease_type） */
    getDictsData() {
      getDicts('sale_type').then(r => (this.saleTypeOptions = r.data || []))
      getDicts('disease_type').then(r => (this.diseaseTypeOptions = r.data || []))
      getDicts('group').then(r => (this.groupOptions = r.data || []))
    },

    /** 羊舍下拉 */
    getSheepfoldOptions() {
      listSheepfold_management().then(r => {
        this.sheepfoldOptions = r.rows || r.data || []
      })
    },

    /** 用户下拉（销售人员、技术员、处理人） */
    getUserOptions() {
      listUser().then(r => {
        this.userOptions = r.rows || r.data || []
      })
    },

    /** 客户远程搜索：使用 sx_customer.name 字段 */
    remoteMethodGetCustomer(query) {
      this.customerLoading = true
      const p = query ? { name: query } : {}
      listCustomer(p)
        .then(r => {
          this.customerOptions = r.rows || r.data || []
        })
        .finally(() => (this.customerLoading = false))
    },

    /** 客户选择后回填 name/phone/address 到表单 */
    handleCustomerChange(customerId) {
      const customer = this.customerOptions.find(item => item.id === customerId)
      if (customer) {
        this.form.customerName = customer.name
        this.form.customerPhone = customer.phone
        this.form.customerAddress = customer.address
      } else {
        this.form.customerName = null
        this.form.customerPhone = null
        this.form.customerAddress = null
      }
    },

    /** 羊舍改变：加载耳号（此处示例，替换成你的真实接口） */
    handleSheepfoldChange(sheepfoldId) {
      this.form.bsManageTagsList = []
      this.earTagOptions = []
      // TODO: 替换为真实接口 getEarTagsBySheepfold(sheepfoldId)
      if (sheepfoldId) {
        this.earTagOptions = ['1001', '1002', '1003', '1004', '1005']
      }
    },

    /** 根据耳号查羊只信息 */
    fetchSheepInfo(bsManageTags) {
      if (!bsManageTags) return
      getSheepInfo(bsManageTags).then(response => {
        if (response.code === 200 && response.data) {
          const data = response.data
          this.form.variety = data.variety
          this.form.sheepName = data.sheepName
          this.form.gender = data.gender
          this.form.monthAge = data.monthAge
          this.form.parity = data.parity
          this.form.breed = data.breed
          this.form.postLambingDay = data.postLambingDay
          this.form.lactationDay = data.lactationDay
          this.form.lambingDay = data.lambingDay
          if (!this.form.sheepfoldId && data.sheepfoldId) {
            this.form.sheepfoldId = data.sheepfoldId
            this.handleSheepfoldChange(data.sheepfoldId)
          }
        } else {
          this.$modal.msgError(response.msg || '未查询到羊只信息')
        }
      })
    },

    /** 计价方式切换 */
    handlePricingMethodChange(method) {
      if (method === '按个体') {
        this.form.totalWeight = null
        this.form.avgWeight = null
        this.calculateIndividualPrice()
      } else if (method === '按体重') {
        this.calculateWeightPrice()
      }
    },

    /** 按个体计价 */
    calculateIndividualPrice() {
      if (this.form.pricingMethod !== '按个体') return
      const unitPrice = parseFloat(this.form.unitPrice) || 0
      const count = Array.isArray(this.form.bsManageTagsList) ? this.form.bsManageTagsList.length : 0
      const total = unitPrice * count
      this.form.totalPrice = Number.isFinite(total) ? Number(total.toFixed(2)) : 0
      this.form.avgPricePerSheep = Number.isFinite(unitPrice) ? Number(unitPrice.toFixed(2)) : 0
    },

    /** 按体重计价 */
    calculateWeightPrice() {
      if (this.form.pricingMethod !== '按体重') return
      const unitPrice = parseFloat(this.form.unitPrice) || 0
      const totalWeight = parseFloat(this.form.totalWeight) || 0
      const count = Array.isArray(this.form.bsManageTagsList) && this.form.bsManageTagsList.length > 0 ? this.form.bsManageTagsList.length : 1
      const total = unitPrice * totalWeight
      this.form.totalPrice = Number.isFinite(total) ? Number(total.toFixed(2)) : 0
      const avgW = totalWeight / count
      this.form.avgWeight = Number.isFinite(avgW) ? Number(avgW.toFixed(2)) : 0
      const avgP = this.form.totalPrice / count
      this.form.avgPricePerSheep = Number.isFinite(avgP) ? Number(avgP.toFixed(2)) : 0
    },

    /** 销售类别变化：清理并重新校验 */
    handleSaleTypeChange() {
      if (!this.isEliminationSale) {
        this.form.diseaseType = null
        this.form.groupCode = null
        this.form.secondaryReason = null
      }
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate(['diseaseType', 'groupCode', 'secondaryReason'])
      })
    },

    /** 疾病类型变化：联动"次要原因" */
    handleDiseaseTypeChange() {
      if (this.diseaseTypeLabel !== '病残羊') {
        this.form.secondaryReason = null
      }
      this.$nextTick(() => this.$refs.formRef.clearValidate('secondaryReason'))
    },
  },
}
</script>

<style scoped>
.breadcrumb { margin-bottom: 16px; }
.app-container { position: relative; }
.el-table { width: 100%; overflow-x: auto; }
</style>