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


    <!-- 新增/编辑表单 -->
    <el-form :model="form" ref="formRef" label-position="left" label-width="120px" style="margin-top:15px"
      :rules="rules">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="耳号" prop="earNumber">
            <el-input v-model="form.earNumber" placeholder="请输入耳号" @blur="handleEarNumberBlur" />
          </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="ranchId">
            <el-select v-model="form.ranchId" placeholder="请选择牧场" clearable @change="handleRanchChange" required>
              <el-option v-for="ranch in ranchOptions" :key="ranch.id" :label="ranch.ranchName" :value="ranch.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="羊舍" prop="sheepfold">
            <el-select v-model="form.sheepfold" placeholder="请选择羊舍" clearable :disabled="!form.ranchId">
              <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-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="胎次" prop="parity">
            <el-input-number v-model="form.parity" :min="0" label="胎次" />
          </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="typeId">
            <el-select v-model="form.typeId" placeholder="请选择羊只类别" clearable>
              <el-option v-for="type in sheepTypeList" :key="type.id" :label="type.name" :value="Number(type.id)" />
            </el-select>
          </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>

    <!-- 导入弹窗 -->
    <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>
  </div>
</template>

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


const { proxy } = getCurrentInstance()
const form = ref({
  earNumber: '',
  ranchId: null,
  sheepfold: '',
  father: '',
  mother: '',
  bornWeight: '',
  birthday: '',
  gender: '',
  parity: '',
  varietyId: '',
  typeId: null,
  joinDate: '',
  comment: '',
  technician: ''
})
const formRef = ref(null)
const sheepfoldOptions = ref([])
const varietyOptions = ref([])
const ranchOptions = ref([])
const rules = {
  earNumber: [
    { required: true, message: '请输入耳号', trigger: 'blur' },
    { validator: checkEarNumberExists, trigger: 'blur' }
  ],
  ranchId: [{ required: true, message: '请选择牧场', trigger: 'change' }],
  sheepfold: [{ required: true, message: '请选择羊舍', trigger: 'change' }],
  bornWeight: [{ required: true, message: '请输入出生体重', trigger: 'change' }],
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  varietyId: [{ required: true, message: '请选择品种', trigger: 'change' }],
  joinDate: [{ required: true, message: '请选择入群日期', trigger: 'change' }],
  technician: [{ required: true, message: '请输入技术员', trigger: 'change' }],
}

// 校验耳号是否存在
function checkEarNumberExists(rule, value, callback) {
  if (!value.trim()) {
    return callback(new Error('请输入耳号'))
  }

  request({
    url: `/sheep/sheep/existsByManageTags/${value.trim()}`,
    method: 'get'
  })
    .then(response => {
      if (response.data === true) {
        callback(new Error('耳号已存在，无法新增'))
      } else {
        callback()
      }
    })
    .catch(error => {
      const status = error.response?.status;
      const errorMsg = error.response?.data?.msg || '';
      if (status === 404) {
        callback();
      } else {
        callback(new Error('请求异常，请稍后重试'));
      }
    });
}

function handleEarNumberBlur() {
  formRef.value.validateField('earNumber')
}

function handleRanchChange(ranchId) {
  form.value.sheepfold = '';
  sheepfoldOptions.value = [];

  if (!ranchId) return;

  listSheepfold({
    pageNum: 1,
    pageSize: 9999,
    ranchId: ranchId
  }).then(res => {
    if (res.rows && res.rows.length > 0) {
      sheepfoldOptions.value = res.rows || [];
    } else {
      proxy.$modal.msgWarning(`该牧场下暂无羊舍数据`);
    }
  }).catch(error => {
    console.error('加载羊舍数据失败', error);
    proxy.$modal.msgError('获取羊舍数据失败');
  });
}

//羊舍列表
//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 loadRanchList() {
  listRanch().then(res => {
    ranchOptions.value = res.rows.map(ranch => ({
      id: ranch.id,
      ranchName: ranch.ranch
    }));
  }).catch(error => {
    console.error('加载牧场列表失败', error);
    proxy.$modal.msgError('获取牧场数据失败');
  });
}

// 加载羊只类别数据
const sheepTypeList = ref([]);
function loadSheepTypeList() {
  getSheepTypeList().then(response => {
    sheepTypeList.value = response.rows || [];
  }).catch(error => {
    console.error('加载羊只类别失败', error);
  });
}

//确保日期格式一致
function formatDate(date) {
  if (!date) return null;
  const d = new Date(date);
  const yyyy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  return `${yyyy}-${mm}-${dd}`;
}
//提交表单
function submitForm() {
  formRef.value.validate(valid => {
    if (!valid) return;

    const formData = JSON.parse(JSON.stringify(form.value));

    formData.birthday = formatDate(formData.birthday);
    formData.joinDate = formatDate(formData.joinDate);

    if (formData.bornWeight) {
      formData.bornWeight = Number(formData.bornWeight);
    }

    addSheep(formData).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess('新增成功');
        formRef.value.clearValidate();
        resetForm();
      } else {
        proxy.$modal.msgError(res.msg || '新增失败');
      }
    });
  });
}

function resetForm() {
  form.value = {
    earNumber: '',
    sheepfold: '',
    father: '',
    mother: '',
    bornWeight: '',
    birthday: '',
    gender: '',
    parity: 0,
    varietyId: '',
    typeId: null,
    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)
}

onMounted(() => {
  // getSheepfoldOptions()
  loadSheepTypeList()
  loadRanchList()
  getVarietyOptions()
})
</script>

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