<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      
      <el-form-item label="耳号" prop="allEarNumbers">
        <el-select
          v-model="queryParams.allEarNumbers"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入耳号搜索"
          :remote-method="searchEarNumber"
          :loading="earNumberLoading"
          style="width: 240px"
          clearable
        >
          <el-option
            v-for="item in earNumberOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="是否在群" prop="isInHerd">
        <el-select v-model="queryParams.isInHerd" placeholder="请选择" clearable style="width: 240px">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="断奶日期" style="width: 340px">
        <el-date-picker
            v-model="daterangeTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="羊只类别" prop="sheepCategory">
        <el-select v-model="queryParams.sheepCategory" placeholder="请选择羊只类别" clearable style="width: 240px">
          <el-option label="种公羊" value="种公羊"></el-option>
          <el-option label="基础母羊" value="基础母羊"></el-option>
          <el-option label="后备羊" value="后备羊"></el-option>
          <el-option label="羔羊" value="羔羊"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable style="width: 240px">
          <el-option label="公" value="公"></el-option>
          <el-option label="母" value="母"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="是否留养" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否留养" clearable style="width: 240px">
          <el-option label="留养" value="1"></el-option>
          <el-option label="不留养" value="0"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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="Plus"
            @click="handleAdd"
            v-hasPermi="['Weaning:weaning_record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['Weaning:weaning_record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['Weaning:weaning_record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['Weaning:weaning_record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="weaning_recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="断奶日期" align="center" prop="datetime" width="120" fixed="left">
        <template #default="scope">
          <span>{{ parseTime(scope.row.datetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="耳号" align="center" prop="earNumber" width="100" />
      <el-table-column label="品种" align="center" prop="breed" width="100" />
      <el-table-column label="事件类型" align="center" prop="eventType" width="100" />
      <el-table-column label="性别" align="center" prop="gender" width="80" />
      <el-table-column label="父号" align="center" prop="fatherNumber" width="100" />
      <el-table-column label="母号" align="center" prop="motherNumber" width="100" />
      <el-table-column label="月龄" align="center" prop="monthAge" width="80" />
      <el-table-column label="出生重量(kg)" align="center" prop="birthWeight" width="120" />
      <el-table-column label="断奶重量(kg)" align="center" prop="weight" width="120" />
      <el-table-column label="是否留养" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status == '1' ? 'success' : 'danger'">
            {{ scope.row.status == '1' ? '留养' : '不留养' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="电子耳号" align="center" prop="electronicTags" width="120" />
      <el-table-column label="羊舍" align="center" prop="sheepPen" width="100" />
      <el-table-column label="技术员" align="center" prop="technician" width="100" />
      <el-table-column label="羊只类别" align="center" prop="breedingStatus" width="100" />
      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      <el-table-column label="创建日期" align="center" prop="createTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="comment" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['Weaning:weaning_record:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Weaning:weaning_record: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="600px" append-to-body>
      <el-form ref="weaning_recordRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="耳号" prop="earNumber">
              <el-input v-model="form.earNumber" placeholder="请输入耳号" @blur="handleEarNumberBlur" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="断奶日期" prop="datetime">
              <el-date-picker clearable
                              v-model="form.datetime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择断奶日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="断奶重量(kg)" prop="weight">
              <el-input-number v-model="form.weight" :precision="2" :step="0.1" placeholder="请输入" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否留养" prop="status">
               <el-radio-group v-model="form.status">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="技术员" prop="technician">
              <el-input v-model="form.technician" placeholder="请输入技术员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子耳号" prop="electronicTags">
              <el-input v-model="form.electronicTags" placeholder="请输入电子耳号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="comment">
              <el-input v-model="form.comment" type="textarea" 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 name="Weaning_record">
import { listWeaning_record, getWeaning_record, delWeaning_record, addWeaning_record, updateWeaning_record, getSheepIdByEarNumber, searchEarNumbers } from "@/api/Weaning/weaning_record"

const { proxy } = getCurrentInstance()

const weaning_recordList = 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 daterangeTime = ref([]) // 时间范围数组

// 远程搜索相关
const earNumberOptions = ref([])
const earNumberLoading = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    allEarNumbers: [],   // 核心：多选数组
    isInHerd: null,      // 新增：是否在群
    sheepCategory: null, // 新增：羊只类别
    status: null,
    gender: null,
    breed: null,
    technician: null,
    sheepPen: null,
    fatherNumber: null,
    motherNumber: null
  },
  rules: {
    earNumber: [
      { required: true, message: "耳号不能为空", trigger: "blur" }
    ],
    datetime: [
      { required: true, message: "断奶日期不能为空", trigger: "blur" }
    ],
    weight: [
      { required: true, message: "断奶重量不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "是否留养不能为空", trigger: "change" }
    ]
  }
})

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

/** 查询断奶记录列表 */
function getList() {
  loading.value = true
  // 处理时间范围
  queryParams.value.params = {};
  if (null != daterangeTime.value && '' != daterangeTime.value) {
    queryParams.value.params["beginTime"] = daterangeTime.value[0];
    queryParams.value.params["endTime"] = daterangeTime.value[1];
  }
  listWeaning_record(queryParams.value).then(response => {
    weaning_recordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 远程搜索耳号 */
function searchEarNumber(query) {
  if (query !== '') {
    earNumberLoading.value = true
    searchEarNumbers(query).then(response => {
      earNumberOptions.value = response.data || []
      earNumberLoading.value = false
    }).catch(() => {
      earNumberOptions.value = []
      earNumberLoading.value = false
    })
  } else {
    earNumberOptions.value = []
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sheepId: null,
    earNumber: null,
    datetime: null,
    weight: null,
    status: "1", // 修改：默认设为 '1' (是)
    technician: null,
    comment: null,
    createBy: null,
    createTime: null,
    electronicTags: null
  }
  proxy.resetForm("weaning_recordRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeTime.value = []
  earNumberOptions.value = []
  proxy.resetForm("queryRef")
  // 必须手动清空多选数组
  queryParams.value.allEarNumbers = []
  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 = "添加断奶记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getWeaning_record(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改断奶记录"
  })
}

/** 处理耳号失焦事件 */
function handleEarNumberBlur() {
  if (form.value.earNumber) {
    getSheepIdByEarNumber(form.value.earNumber).then(response => {
      if (response.data) {
        form.value.sheepId = response.data
      } else {
        proxy.$modal.msgError("未找到对应的羊只信息")
        form.value.earNumber = null
      }
    })
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["weaning_recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateWeaning_record(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWeaning_record(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除断奶记录编号为"' + _ids + '"的数据项？').then(function () {
    return delWeaning_record(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('Weaning/weaning_record/export', {
    ...queryParams.value
  }, `weaning_record_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>