<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="冲胚时间" style="width: 388px;">
        <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="供体母号" prop="donorFemaleNo">
        <el-input
            v-model="queryParams.donorFemaleNo"
            placeholder="请输入供体母号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供体父号" prop="donorMaleNo">
        <el-input
            v-model="queryParams.donorMaleNo"
            placeholder="请输入供体父号"
            clearable
            @keyup.enter="handleQuery"
        />
      </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="['embryo:flush:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['embryo:flush:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['embryo:flush:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['embryo:flush:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="flushList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="冲胚时间" align="center" prop="flushTime" width="110">
        <template #default="scope">
          <span>{{ parseTime(scope.row.flushTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="胚胎品种" align="center" prop="embryoVariety" width="100" />
      <el-table-column label="供体母号" align="center" prop="donorFemaleNo" width="110" />
      <el-table-column label="母羊品种" align="center" prop="donorFemaleVariety" width="100" />
      <el-table-column label="供体父号" align="center" prop="donorMaleNo" width="110" />
      <el-table-column label="公羊品种" align="center" prop="donorMaleVariety" width="100" />
      <el-table-column label="胎龄(天)" align="center" prop="embryoAge" width="80" />
      <el-table-column label="A+" align="center" prop="gradeAPlus" width="60" />
      <el-table-column label="A" align="center" prop="gradeA" width="60" />
      <el-table-column label="B" align="center" prop="gradeB" width="60" />
      <el-table-column label="C" align="center" prop="gradeC" width="60" />
      <el-table-column label="D" align="center" prop="gradeD" width="60" />
      <el-table-column label="2/4细胞" align="center" prop="cell24" width="70" />
      <el-table-column label="8细胞" align="center" prop="cell8" width="60" />
      <el-table-column label="16细胞" align="center" prop="cell16" width="70" />
      <el-table-column label="未受精" align="center" prop="unfertilized" width="70" />
      <el-table-column label="退化" align="center" prop="degenerated" width="60" />
      <el-table-column label="冲胚数" align="center" prop="totalEmbryo" width="70" />
      <el-table-column label="有效胚" align="center" prop="validEmbryo" width="70" />
      <el-table-column label="移胚数" align="center" prop="transferred" width="70" />
      <el-table-column label="受体数" align="center" prop="recipientCnt" width="70" />
      <el-table-column label="胚胎类型" align="center" prop="embryoType" width="90" />
      <el-table-column label="胚胎来源" align="center" prop="embryoSource" width="90" />
      <el-table-column label="去向" align="center" prop="destination" width="80" />
      <el-table-column label="存储方式" align="center" prop="storageMethod" width="100" />
      <el-table-column label="冲胚人" align="center" prop="flushOperator" width="80" />
      <el-table-column label="捡胚人" align="center" prop="collectOperator" width="80" />
      <el-table-column label="所在牧场" align="center" prop="ranchName" width="100" />
      <el-table-column label="备注" align="center" prop="remark" width="120" show-overflow-tooltip />
      <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="['embryo:flush:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['embryo:flush: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="900px" append-to-body>
      <el-form ref="flushRef" :model="form" :rules="rules" label-width="100px">
        <!-- 基础信息 -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="冲胚时间" prop="flushTime">
              <el-date-picker clearable
                              v-model="form.flushTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="选择冲胚时间"
                              style="width: 100%"
                              @change="handleFlushTimeChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供体母号" prop="donorFemaleNo">
              <el-select
                  v-model="form.donorFemaleNo"
                  filterable
                  placeholder="请选择供体母羊"
                  @change="handleDonorFemaleChange"
                  style="width: 100%">
                <el-option
                    v-for="item in donorFemaleOptions"
                    :key="item.manageTag"
                    :label="item.manageTag"
                    :value="item.manageTag">
                  <span>{{ item.manageTag }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ item.variety }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="母羊品种">
              <el-input v-model="form.donorFemaleVariety" disabled placeholder="自动填充" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供体父号" prop="donorMaleNo">
              <el-input v-model="form.donorMaleNo" placeholder="自动填充/可修改" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公羊品种">
              <el-input v-model="form.donorMaleVariety" disabled placeholder="自动填充" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="胚胎品种">
              <el-input v-model="form.embryoVariety" placeholder="自动计算/可修改" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="胎龄(天)">
              <el-input-number v-model="form.embryoAge" :min="0" controls-position="right" placeholder="自动计算" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在牧场">
              <el-input v-model="form.ranchName" disabled placeholder="自动填充" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 胚胎等级 -->
        <el-divider content-position="left">胚胎等级</el-divider>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="A+">
              <el-input-number v-model="form.gradeAPlus" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="A">
              <el-input-number v-model="form.gradeA" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="B">
              <el-input-number v-model="form.gradeB" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="C">
              <el-input-number v-model="form.gradeC" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="D">
              <el-input-number v-model="form.gradeD" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 发育阶段 -->
        <el-divider content-position="left">发育阶段</el-divider>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="2/4细胞">
              <el-input-number v-model="form.cell24" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="8细胞">
              <el-input-number v-model="form.cell8" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="16细胞">
              <el-input-number v-model="form.cell16" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="未受精">
              <el-input-number v-model="form.unfertilized" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="退化">
              <el-input-number v-model="form.degenerated" :min="0" controls-position="right" @change="calculateTotal" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 统计信息 -->
        <el-divider content-position="left">统计信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="冲胚数">
              <el-input v-model="form.totalEmbryo" disabled placeholder="自动计算" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="有效胚">
              <el-input v-model="form.validEmbryo" disabled placeholder="自动计算" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="移胚数" prop="transferred">
              <el-input-number v-model="form.transferred" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="移植受体数" prop="recipientCnt">
              <el-input-number v-model="form.recipientCnt" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 其他信息 -->
        <el-divider content-position="left">其他信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="胚胎类型" prop="embryoType">
              <el-select v-model="form.embryoType" placeholder="请选择" 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="embryoSource">
              <el-select v-model="form.embryoSource" placeholder="请选择" 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="destination">
              <el-input v-model="form.destination" placeholder="默认遗弃可自行修改" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="存储方式" prop="storageMethod">
              <el-input v-model="form.storageMethod" placeholder="默认胚胎保存液" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="冲胚人" prop="flushOperator">
              <el-input v-model="form.flushOperator" placeholder="请输入冲胚人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="捡胚人" prop="collectOperator">
              <el-input v-model="form.collectOperator" placeholder="请输入捡胚人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="1" />
            </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="Flush">
import { listFlush, getFlush, delFlush, addFlush, updateFlush, getDonorInfo, getDonorFemaleList } from "@/api/embryo/flush"

const { proxy } = getCurrentInstance()

const flushList = 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 dateRange = ref([])
const donorFemaleOptions = ref([])
// 保存配种日期用于计算胎龄
const matingDateCache = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    donorFemaleNo: null,
    donorMaleNo: null
  },
  rules: {
    flushTime: [
      { required: true, message: "冲胚时间不能为空", trigger: "blur" }
    ],
    donorFemaleNo: [
      { required: true, message: "供体母号不能为空", trigger: "change" }
    ],
    embryoType: [
      { required: true, message: "胚胎类型不能为空", trigger: "change" }
    ],
    embryoSource: [
      { required: true, message: "胚胎来源不能为空", trigger: "change" }
    ],
    flushOperator: [
      { required: true, message: "冲胚人不能为空", trigger: "blur" }
    ],
    collectOperator: [
      { required: true, message: "捡胚人不能为空", trigger: "blur" }
    ]
  }
})

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

/** 查询冲胚记录列表 */
function getList() {
  loading.value = true
  listFlush(proxy.addDateRange(queryParams.value, dateRange.value, 'FlushTime')).then(response => {
    flushList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 加载供体母羊下拉列表 */
function loadDonorFemaleList() {
  getDonorFemaleList().then(response => {
    donorFemaleOptions.value = response.data || []
  }).catch(error => {
    console.error('加载供体母羊列表失败:', error)
    donorFemaleOptions.value = []
  })
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    flushTime: proxy.parseTime(new Date(), '{y}-{m}-{d}'),
    donorFemaleNo: null,
    donorFemaleVariety: null,
    donorMaleNo: null,
    donorMaleVariety: null,
    embryoVariety: null,
    embryoAge: null,
    gradeAPlus: 0,
    gradeA: 0,
    gradeB: 0,
    gradeC: 0,
    gradeD: 0,
    cell24: 0,
    cell8: 0,
    cell16: 0,
    unfertilized: 0,
    degenerated: 0,
    totalEmbryo: 0,
    validEmbryo: 0,
    transferred: 0,
    recipientCnt: 0,
    embryoType: null,
    embryoSource: '自繁',
    destination: '遗弃',
    storageMethod: '胚胎保存液',
    flushOperator: null,
    collectOperator: null,
    ranchId: null,
    ranchName: null,
    remark: null
  }
  matingDateCache.value = null
  proxy.resetForm("flushRef")
}

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

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  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()
  loadDonorFemaleList()
  open.value = true
  title.value = "添加冲胚记录"
}

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

/** 冲胚时间变化时重新计算胎龄 */
function handleFlushTimeChange(val) {
  calculateEmbryoAge()
}

/** 供体母羊选择变化 */
function handleDonorFemaleChange(val) {
  if (!val) {
    form.value.donorFemaleVariety = null
    form.value.donorMaleNo = null
    form.value.donorMaleVariety = null
    form.value.embryoVariety = null
    form.value.ranchId = null
    form.value.ranchName = null
    form.value.embryoAge = null
    matingDateCache.value = null
    return
  }

  // 调用接口获取关联信息
  getDonorInfo(val).then(response => {
    const info = response.data || {}
    form.value.donorFemaleVariety = info.donorFemaleVariety || null
    form.value.donorMaleNo = info.donorMaleNo || null
    form.value.donorMaleVariety = info.donorMaleVariety || null
    form.value.embryoVariety = info.embryoVariety || null
    form.value.ranchId = info.ranchId || null
    form.value.ranchName = info.ranchName || null

    // 缓存配种日期
    matingDateCache.value = info.matingDate || null

    // 计算胎龄
    calculateEmbryoAge()
  }).catch(error => {
    console.error('获取供体母羊关联信息失败:', error)
    proxy.$modal.msgError('获取供体母羊信息失败')
  })
}

/** 计算胎龄 */
function calculateEmbryoAge() {
  if (matingDateCache.value && form.value.flushTime) {
    const matingDate = new Date(matingDateCache.value)
    const flushDate = new Date(form.value.flushTime)
    const diffTime = flushDate.getTime() - matingDate.getTime()
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
    form.value.embryoAge = diffDays > 0 ? diffDays : 0
  }
}

/** 计算冲胚数和有效胚 */
function calculateTotal() {
  const gradeAPlus = form.value.gradeAPlus || 0
  const gradeA = form.value.gradeA || 0
  const gradeB = form.value.gradeB || 0
  const gradeC = form.value.gradeC || 0
  const gradeD = form.value.gradeD || 0
  const cell24 = form.value.cell24 || 0
  const cell8 = form.value.cell8 || 0
  const cell16 = form.value.cell16 || 0
  const unfertilized = form.value.unfertilized || 0
  const degenerated = form.value.degenerated || 0

  // 有效胚 = A+ + A + B + C + D
  form.value.validEmbryo = gradeAPlus + gradeA + gradeB + gradeC + gradeD

  // 冲胚数 = 所有数量总和
  form.value.totalEmbryo = gradeAPlus + gradeA + gradeB + gradeC + gradeD
      + cell24 + cell8 + cell16 + unfertilized + degenerated
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除所选的冲胚记录？').then(function () {
    return delFlush(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('embryo/flush/export', {
    ...queryParams.value
  }, `冲胚记录_${new Date().getTime()}.xlsx`)
}

getList()
</script>