<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="耳号" prop="manageTags">
        <el-input
            v-model="queryParams.manageTags"
            placeholder="请输入耳号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采精日期" prop="pickDate">
        <el-date-picker clearable
                        v-model="queryParams.pickDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择采精日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="采精量" prop="amount">
        <el-input
            v-model="queryParams.amount"
            placeholder="请输入采精量"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="精液密度" prop="density">
        <el-input
            v-model="queryParams.density"
            placeholder="请输入精液密度"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="精液活力" prop="vitallity">
        <el-input
            v-model="queryParams.vitallity"
            placeholder="请输入精液活力"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否性控" prop="controlled">
        <el-select v-model="queryParams.controlled" placeholder="请选择是否性控" clearable>
          <el-option label="否" value="0" />
          <el-option label="是" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="技术员" prop="technician">
        <el-input
            v-model="queryParams.technician"
            placeholder="请输入技术员"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="阴囊周长" prop="scrotumCircumference">
        <el-input
            v-model="queryParams.scrotumCircumference"
            placeholder="请输入阴囊周长"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="精液品质" prop="semenQuality">
        <el-select v-model="queryParams.semenQuality" placeholder="请选择精液品质" clearable>
          <el-option label="A级" value="A" />
          <el-option label="B级" value="B" />
          <el-option label="C级" value="C" />
          <el-option label="D级" value="D" />
        </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="['Sperm:Sperm:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['Sperm:Sperm:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['Sperm:Sperm:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['Sperm:Sperm:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SpermList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 日期作为第一列 -->
      <el-table-column label="采精日期" align="center" prop="pickDate" width="120" fixed="left">
        <template #default="scope">
          <span>{{ parseTime(scope.row.pickDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="耳号" align="center" prop="manageTags" width="120" />
      <el-table-column label="电子耳号" align="center" prop="electronicTags" width="120" />
      <el-table-column label="月龄" align="center" prop="monthAge" width="80" />
      <el-table-column label="采精量(ml)" align="center" prop="amount" width="100" />
      <el-table-column label="精液密度" align="center" prop="density" width="100" />
      <el-table-column label="精液活力" align="center" prop="vitallity" width="100" />
      <el-table-column label="是否性控" align="center" prop="controlled" width="100">
        <template #default="scope">
          <span>{{ scope.row.controlled == 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性欲情况" align="center" prop="sexualStatus" width="100" />
      <el-table-column label="诊疗信息" align="center" prop="info" width="120" />
      <el-table-column label="技术员" align="center" prop="technician" width="100" />
      <el-table-column label="采精备注" align="center" prop="comment" width="120" />
      <el-table-column label="阴囊周长(cm)" align="center" prop="scrotumCircumference" width="120" />
      <el-table-column label="精液品质" align="center" prop="semenQuality" width="100" />
      <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="['Sperm:Sperm:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Sperm:Sperm: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="700px" append-to-body>
      <el-form ref="SpermRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="耳号" prop="manageTags">
              <el-input
                  v-model="form.manageTags"
                  placeholder="请输入耳号"
                  @blur="validateManageTags"
                  :loading="sheepValidation.isValidating"
              />
              <div v-if="sheepValidation.message"
                   :class="['validation-message', sheepValidation.isValid ? 'success' : 'error']">
                <i :class="sheepValidation.isValid ? 'el-icon-success' : 'el-icon-error'"></i>
                {{ sheepValidation.message }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采精日期" prop="pickDate">
              <el-date-picker clearable
                              v-model="form.pickDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择采精日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 自动填充的羊只信息 -->
        <el-row v-if="sheepValidation.sheepInfo">
          <el-col :span="12">
            <el-form-item label="电子耳号">
              <el-input v-model="form.electronicTags" placeholder="自动填充" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月龄">
              <el-input v-model="form.monthAge" placeholder="自动填充" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="采精量(ml)" prop="amount">
              <el-input-number
                  v-model="form.amount"
                  placeholder="请输入采精量"
                  :min="0"
                  :precision="1"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="精液密度" prop="density">
              <el-input v-model="form.density" placeholder="请输入精液密度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="精液活力" prop="vitallity">
              <el-input v-model="form.vitallity" placeholder="请输入精液活力" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否性控" prop="controlled">
              <el-select v-model="form.controlled" placeholder="请选择是否性控" style="width: 100%">
                <el-option label="否" :value="0" />
                <el-option label="是" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性欲情况" prop="sexualStatus">
              <el-select v-model="form.sexualStatus" placeholder="请选择性欲情况" style="width: 100%">
                <el-option label="良好" value="良好" />
                <el-option label="一般" value="一般" />
                <el-option label="较差" value="较差" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技术员" prop="technician">
              <el-input v-model="form.technician" placeholder="请输入技术员" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="阴囊周长(cm)" prop="scrotumCircumference">
              <el-input-number
                  v-model="form.scrotumCircumference"
                  placeholder="请输入阴囊周长"
                  :min="0"
                  :precision="1"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="精液品质" prop="semenQuality">
              <el-select v-model="form.semenQuality" placeholder="请选择精液品质" style="width: 100%">
                <el-option label="A级" value="A" />
                <el-option label="B级" value="B" />
                <el-option label="C级" value="C" />
                <el-option label="D级" value="D" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="诊疗信息" prop="info">
          <el-input v-model="form.info" type="textarea" placeholder="请输入诊疗信息" :rows="2" />
        </el-form-item>
        <el-form-item label="采集备注" prop="comment">
          <el-input v-model="form.comment" type="textarea" placeholder="请输入采集备注" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sperm">
import {listSperm, getSperm, delSperm, addSperm, updateSperm, getSheepByManageTags} from "@/api/Sperm/Sperm"

const {proxy} = getCurrentInstance()

const SpermList = 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 submitLoading = ref(false)

// 羊只验证相关状态
const sheepValidation = ref({
  isValidating: false,
  isValid: false,
  message: '',
  sheepInfo: null
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageTags: null,
    pickDate: null,
    amount: null,
    density: null,
    vitallity: null,
    controlled: null,
    sexualStatus: null,
    info: null,
    technician: null,
    comment: null,
    scrotumCircumference: null,
    semenQuality: null,
  },
  rules: {
    manageTags: [
      {required: true, message: "耳号不能为空", trigger: "blur"}
    ],
    pickDate: [
      {required: true, message: "采精日期不能为空", trigger: "blur"}
    ],
    amount: [
      {required: true, message: "采精量不能为空", trigger: "blur"}
    ]
  }
})

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

/** 查询采精记录列表 */
function getList() {
  loading.value = true
  listSperm(queryParams.value).then(response => {
    SpermList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error => {
    loading.value = false
    proxy.$modal.msgError("查询失败")
  })
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    manageTags: null,
    electronicTags: null,
    monthAge: null,
    pickDate: null,
    amount: null,
    density: null,
    vitallity: null,
    controlled: 0,
    sexualStatus: null,
    info: null,
    technician: null,
    comment: null,
    scrotumCircumference: null,
    semenQuality: null,
    createBy: null,
    createTime: null
  }

  // 重置验证状态
  sheepValidation.value = {
    isValidating: false,
    isValid: false,
    message: '',
    sheepInfo: null
  }

  proxy.resetForm("SpermRef")
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  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
  getSperm(_id).then(response => {
    form.value = response.data

    // 如果有耳号，自动验证
    if (form.value.manageTags) {
      validateManageTags()
    }

    open.value = true
    title.value = "修改采精记录"
  })
}

/** 验证耳号 */
const validateManageTags = async () => {
  if (!form.value.manageTags || form.value.manageTags.trim() === '') {
    sheepValidation.value = {
      isValidating: false,
      isValid: false,
      message: '',
      sheepInfo: null
    }
    return
  }

  sheepValidation.value.isValidating = true

  try {
    const response = await getSheepByManageTags(form.value.manageTags.trim())
    if (response.code === 200) {
      const sheepInfo = response.data.sheepInfo || response.data
      sheepValidation.value = {
        isValidating: false,
        isValid: true,
        message: response.data.message || '验证通过，该羊只为公羊',
        sheepInfo: sheepInfo
      }

      // 自动填充羊只信息
      if (sheepInfo) {
        form.value.electronicTags = sheepInfo.electronicTags || ''
        form.value.monthAge = sheepInfo.monthAge || null
      }
    } else {
      sheepValidation.value = {
        isValidating: false,
        isValid: false,
        message: response.msg || '验证失败',
        sheepInfo: null
      }

      // 清空自动填充的信息
      form.value.electronicTags = ''
      form.value.monthAge = null
    }
  } catch (error) {
    sheepValidation.value = {
      isValidating: false,
      isValid: false,
      message: '验证失败，请检查网络连接',
      sheepInfo: null
    }

    // 清空自动填充的信息
    form.value.electronicTags = ''
    form.value.monthAge = null
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SpermRef"].validate(valid => {
    if (valid) {
      // 在提交前再次验证耳号
      if (!sheepValidation.value.isValid && form.value.manageTags) {
        proxy.$modal.msgError("请先验证耳号是否为公羊")
        return
      }

      submitLoading.value = true

      if (form.value.id != null) {
        updateSperm(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          proxy.$modal.msgError(error.response?.data?.msg || "修改失败")
        }).finally(() => {
          submitLoading.value = false
        })
      } else {
        addSperm(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(error => {
          proxy.$modal.msgError(error.response?.data?.msg || "新增失败")
        }).finally(() => {
          submitLoading.value = false
        })
      }
    }
  })
}

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

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

// 页面加载时获取数据
getList()
</script>

<style scoped>
.validation-message {
  font-size: 12px;
  margin-top: 4px;
  padding: 2px 0;
  display: flex;
  align-items: center;
  gap: 4px;
}

.validation-message.success {
  color: #67c23a;
}

.validation-message.error {
  color: #f56c6c;
}

.el-input-number {
  width: 100%;
}

.dialog-footer {
  text-align: right;
}

.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>