<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="请输入羊只id" />
          </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="出生体重" 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="1" />
              <el-option label="母" value="0" />
              <el-option label="阉羊" value="2" />
              <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-input v-model="form.varietyId" placeholder="请输入品种" />
          </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"></i>
      <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 } from 'vue';
import { addSheep } from '@/api/produce/manage_sheep/add_sheep/add_sheep';
import { listSheepfold_management as listSheepfold } from '@/api/sheepfold_management/sheepfold_management';

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' }],
  father: [{ message: '请输入父号', trigger: 'blur' }],
  mother: [{ message: '请输入母号', trigger: 'blur' }],
  bornWeight: [{ required: true, message: '请输入出生体重', trigger: 'blur' }],
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  parity: [{ message: '请输入胎次', trigger: 'blur' }],
  varietyId: [{ required: true, message: '请输入品种', trigger: 'blur' }],
  joinDate: [{ message: '请选择入群日期', trigger: 'change' }],
  technician: [{ message: '请输入技术员', trigger: 'blur' }],
};


//表单验证 提交表单数据
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      addSheep(form.value) // 调用 API 方法，addSheep 应已在 @/api/sheep/sheep.js 中定义
        .then(response => {
          if (response.code === 200) {
            alert('新增成功');
            resetForm();
            // 可以在这里添加刷新列表的逻辑，例如调用 list 方法
          } else {
            alert(response.msg || '新增失败');
          }
        })
        .catch(error => {
          console.error('新增失败:', error);
          alert('新增失败，请稍后重试');
        });
    } else {
      alert('请填写所有必填字段');
    }
  });
};
const resetForm = () => {
  form.value = {
    earNumber: '',
    sheepfold: '',
    father: '',
    mother: '',
    bornWeight: '',
    birthday: '',
    gender: '',
    parity: '',
    varietyId: '',
    joinDate: '',
    comment: '',
    technician: '',
  };
};


//导出
import { exportSheepForm } from '@/api/produce/manage_sheep/add_sheep/add_sheep';

function handleExportForm() {
  // 把当前表单数据直接传后端
  exportSheepForm(form.value).then(res => {
    // 使用 Ruoyi 自带的下载方法
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const fileName = `羊只信息_${new Date().getTime()}.xlsx`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
  });
}


//导入
import { getToken } from '@/utils/auth';

const uploadRef = ref();
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() {
  proxy.download('/produce/manage_sheep/add_sheep/importTemplate', {}, `羊只模板_${Date.now()}.xlsx`);
}
function submitUpload() { uploadRef.value?.submit(); }
function handleImportSuccess(res) {
  proxy.$modal.msgSuccess(res.msg || '导入成功');
  importOpen.value = false;
  uploadRef.value?.clearFiles();
}
function handleImportError(err) {
  proxy.$modal.msgError(JSON.parse(err.message)?.msg || '导入失败');
}


/**获取羊舍数据 */
const sheepfoldOptions = ref([]);
function getSheepfoldOptions() {
  listSheepfold({ pageNum: 1, pageSize: 9999 }).then(res => {
    sheepfoldOptions.value = res.rows;   
  });
}
onMounted(() => {
  getSheepfoldOptions();
});


</script>

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