<template>
  <div class="app-container">
    <!-- 顶部按钮 -->
    <el-button type="warning" icon="Upload" @click="handleExportForm">导出</el-button>
    <el-button type="primary" plain icon="Plus" @click="handleImport"
      v-hasPermi="['produce:add_sheep:import']">导入</el-button>

    <!-- 新增/编辑表单 -->
    <el-form :model="form" ref="formRef" label-position="left" label-width="100px" style="margin-top:15px">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="耳号" prop="earNumber">
            <el-input v-model="form.earNumber" placeholder="请输入耳号" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="羊舍" prop="sheepfold">
            <el-select v-model="form.sheepfold" placeholder="请选择羊舍" clearable>
              <el-option v-for="item in sheepfoldOptions" :key="item.id" :label="item.sheepfoldName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="父号" prop="father">
            <el-input v-model="form.father" placeholder="请输入父号" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="母号" prop="mother">
            <el-input v-model="form.mother" placeholder="请输入母号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="出生体重(kg)" prop="bornWeight">
            <el-input v-model="form.bornWeight" placeholder="请输入出生体重" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker v-model="form.birthday" type="date" placeholder="选择出生日期" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="公" :value="2" />
              <el-option label="母" :value="1" />
              <el-option label="阉羊" :value="3" />
              <!-- <el-option label="兼性" :value="3" /> -->
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="胎次" prop="parity">
            <el-input v-model="form.parity" placeholder="请输入胎次" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="品种" prop="varietyId">
            <el-select v-model="form.varietyId" placeholder="请选择品种" clearable>
              <el-option v-for="item in varietyOptions" :key="item.id" :label="item.variety" :value="Number(item.id)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="入群日期" prop="joinDate">
            <el-date-picker v-model="form.joinDate" type="date" placeholder="选择入群日期" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="技术员" prop="technician">
            <el-input v-model="form.technician" placeholder="请输入技术员" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="备注" prop="comment">
            <el-input v-model="form.comment" type="textarea" rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 导入弹窗 -->
  <el-dialog title="导入羊只信息" v-model="importOpen" width="400px" append-to-body>
    <el-upload ref="uploadRef" :limit="1" accept=".xlsx,.xls" :action="importUrl" :headers="headers"
      :auto-upload="false" :on-success="handleImportSuccess" :on-error="handleImportError" drag>
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <template #footer>
      <el-button type="info" @click="downloadTemplate">下载模板</el-button>
      <el-button type="primary" @click="submitUpload">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import request from '@/utils/request'
import { addSheep, exportSheepForm } from '@/api/produce/manage_sheep/add_sheep'
import { listSheepfold_management as listSheepfold } from '@/api/fileManagement/sheepfold_management'
import { getToken } from '@/utils/auth'


const { proxy } = getCurrentInstance()
/* -------------------- 表单 -------------------- */
const form = ref({
  earNumber: '',
  sheepfold: '',
  father: '',
  mother: '',
  bornWeight: '',
  birthday: '',
  gender: '',
  parity: '',
  varietyId: '',
  joinDate: '',
  comment: '',
  technician: ''
})
const formRef = ref(null)

const rules = {
  earNumber: [{ required: true, message: '请输入耳号', trigger: 'blur' }],
  sheepfold: [{ required: true, message: '请选择羊舍', trigger: 'change' }],
  bornWeight: [{ required: true, message: '请输入出生体重', trigger: 'blur' }],
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  varietyId: [{ required: true, message: '请选择品种', trigger: 'change' }]
}

/* -------------------- 下拉数据 -------------------- */
const sheepfoldOptions = ref([])
const varietyOptions = ref([])

function getSheepfoldOptions() {
  listSheepfold({ pageNum: 1, pageSize: 9999 }).then(res => {
    sheepfoldOptions.value = res.rows || []
  })
}

function getVarietyOptions() {
  request({
    url: '/base/variety/list',
    method: 'get',
    params: { pageNum: 1, pageSize: 9999 }
  }).then(res => {
    varietyOptions.value = res.rows || []
  })
}

/* -------------------- 功能方法 -------------------- */
function submitForm() {
  formRef.value.validate(valid => {
    if (!valid) return
    addSheep(form.value).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess('新增成功')
        resetForm()
      } else {
        proxy.$modal.msgError(res.msg || '新增失败')   // 这里显示“耳号已存在”等后端报错
      }
    }).catch(() => {
      proxy.$modal.msgError('请求异常，请稍后重试')
    })
  })
}

function resetForm() {
  form.value = {
    earNumber: '',
    sheepfold: '',
    father: '',
    mother: '',
    bornWeight: '',
    birthday: '',
    gender: '',
    parity: '',
    varietyId: '',
    joinDate: '',
    comment: '',
    technician: ''
  }
}

function handleExportForm() {
  exportSheepForm(form.value).then(res => {
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `羊只信息_${Date.now()}.xlsx`
    link.click()
  })
}

/* -------------------- 导入 -------------------- */
const uploadRef = ref(null)
const importOpen = ref(false)
const importUrl = ref(import.meta.env.VITE_APP_BASE_API + '/produce/manage_sheep/add_sheep/importData')
const headers = ref({ Authorization: 'Bearer ' + getToken() })

function handleImport() {
  importOpen.value = true
}
function downloadTemplate() {
  request({ url: '/produce/manage_sheep/add_sheep/importTemplate', method: 'get', responseType: 'blob' }).then(res => {
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `羊只模板_${Date.now()}.xlsx`
    link.click()
  })
}
function submitUpload() {
  uploadRef.value?.submit()
}

// 上传成功回调
function handleImportSuccess(res) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess(res.msg || '导入成功')
    importOpen.value = false
    uploadRef.value?.clearFiles()
  } else {
    // 业务失败
    proxy.$modal.msgError('导入失败：' + (res.msg || '未知原因'))
  }
}

// 上传失败（网络/服务器异常）
function handleImportError(err) {
  const msg = JSON.parse(err.message || '{}')?.msg || '网络异常'
  proxy.$modal.msgError('导入失败：' + msg)
}


/* -------------------- 初始化 -------------------- */

  getSheepfoldOptions()
  getVarietyOptions()

</script>

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