<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="配方编码" prop="formulaId">
        <el-input v-model="queryParams.formulaId" placeholder="请输入配方编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="羊舍" prop="sheepHouseId">
        <el-input v-model="queryParams.sheepHouseId" 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="['feed:FeedPlan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['feed:FeedPlan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['feed:FeedPlan:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['feed:FeedPlan:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="FeedPlanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="创建日期" align="center" prop="createDate" />
      <el-table-column label="配方编码" align="center" prop="formulaId" />
      <el-table-column label="批号" align="center" prop="batchId" />
      <el-table-column label="羊舍" align="center" prop="sheepHouseId">
        <template #default="scope">
          {{ getSheepHouseName(scope.row.sheepHouseId) }}
        </template>
      </el-table-column>

      <el-table-column label="羊只数量" align="center" prop="sheepCount" />
      <el-table-column label="日均计划量" align="center" prop="planDailySize" />
      <el-table-column label="上午" prop="materialId" align="center">
        <el-table-column label="计划量" align="center" prop="planMorningSize">
          <template #default="{ row }">
            {{ row.planMorningSize ? row.planMorningSize.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="计划总量" align="center" prop="planMorningTotal" /> -->
        <el-table-column label="实际量" align="center" prop="actualMorningSize" />
      </el-table-column>
      <el-table-column label="中午" prop="materialId" align="center">
        <el-table-column label="计划量" align="center" prop="planNoonSize">
          <template #default="{ row }">
            {{ row.planNoonSize ? row.planNoonSize.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="计划总量" align="center" prop="planNoonTotal" /> -->
        <el-table-column label="实际量" align="center" prop="actualNoonSize" />
      </el-table-column>
      <el-table-column label="下午" prop="materialId" align="center">
        <el-table-column label="计划量" align="center" prop="planAfternoonSize">
          <template #default="{ row }">
            {{ row.planAfternoonSize ? row.planAfternoonSize.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="计划总量" align="center" prop="planAfternoonTotal" /> -->
        <el-table-column label="实际量" align="center" prop="actualAfternoonSize" />
      </el-table-column>
      <el-table-column label="饲喂比例(%)" align="center" prop="ratioTotal">
        <el-table-column label="上午" align="center" prop="ratioMorning" />
        <el-table-column label="中午" align="center" prop="ratioNoon" />
        <el-table-column label="下午" align="center" prop="ratioAfternoon" />
      </el-table-column>

      <el-table-column label="计划饲喂总量" align="center" prop="planFeedTotal" />
      <el-table-column label="饲草班人员" align="center" prop="zookeeper" />
      <el-table-column label="饲喂计划日期" align="center" prop="planDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.planDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['feed:FeedPlan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['feed:FeedPlan: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="500px" append-to-body>
      <el-form ref="FeedPlanRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="配方编码" prop="formulaId">
          <!-- <el-input v-model="form.formulaId" placeholder="请输入配方编码" /> -->
          <el-select v-model="form.formulaId" filterable placeholder="请选择配方编码" style="width: 100%"
            @change="handleFormulaIdChange(form, $event)">
            <el-option v-for="item in formulaIdDict" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="批号" prop="batchId">
          <!-- <el-input v-model="form.batchId" placeholder="请输入批号" /> -->
          <el-select v-model="form.batchId" filterable placeholder="请选择配方批号" style="width: 100%">
            <el-option v-for="item in formulaBatchDict" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="羊舍" prop="sheepHouseId">
          <!-- <el-input v-model="form.sheepHouseId" placeholder="请输入羊舍" /> -->
          <el-select v-model="form.sheepHouseId" filterable placeholder="请选择羊舍" style="width: 100%">
            <el-option v-for="item in sheepFolderDict" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="日均计划量" prop="planDailySize">
          <el-input v-model="form.planDailySize" placeholder="请输入日均计划量" />
        </el-form-item>
        <el-form-item label="比例 (%)">
          <div style="display: flex; gap: 10px;">
            <el-input v-model="form.ratioMorning" placeholder="早上比例" style="width: 100px;" />
            <el-input v-model="form.ratioNoon" placeholder="中午比例" style="width: 100px;" />
            <el-input v-model="form.ratioAfternoon" placeholder="下午比例" style="width: 100px;" />
          </div>
        </el-form-item>
        <el-form-item label="饲草班人员" prop="Zookeeper">
          <el-input v-model="form.zookeeper" placeholder="请输入饲草班人员" />
        </el-form-item>
        <el-form-item label="计划日期" prop="planDate">
          <el-date-picker clearable v-model="form.planDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择计划饲喂时间">
          </el-date-picker>
        </el-form-item>
        <div v-if="title === '修改饲喂计划'">
          <el-divider content-position="left">配方详情</el-divider>
          <el-form-item label="实际饲喂量">
            <div style="display: flex; gap: 10px;">
              <el-input v-model="form.actualMorningSize" placeholder="早上" style="width: 100px;" />
              <el-input v-model="form.actualNoonSize" placeholder="中午" style="width: 100px;" />
              <el-input v-model="form.actualAfternoonSize" placeholder="下午" style="width: 100px;" />
            </div>
          </el-form-item>
        </div>
      </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="FeedPlan">
  import { listFeedPlan, getFeedPlan, delFeedPlan, addFeedPlan, updateFeedPlan } from "@/api/feed/FeedPlan"
  import { listFormulaManagement } from "@/api/feed/FormulaManagement";
  import { listSheepfold } from "@/api/produce/manage_sheep/trans_group.js";
  import { get } from "@vueuse/core";
  const { proxy } = getCurrentInstance()

  const FeedPlanList = 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 data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      formulaId: null,
      sheepHouseId: null,
    },
    rules: {
      formulaId: [
        { required: true, message: "配方编码不能为空", trigger: "blur" }
      ],
      batchId: [
        { required: true, message: "批号不能为空", trigger: "blur" }
      ],
      sheepHouseId: [
        { required: true, message: "羊舍不能为空", trigger: "blur" }
      ],
      planDailySize: [
        { required: true, message: "日均计划量不能为空", trigger: "blur" }
      ],
    }
  })

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

  const formulaIdDict = ref([]) // 配方编码字典
  // 用于存储配方批号列表
  const formulaBatchMap = ref([])
  const formulaBatchDict = ref([]) // 配方批号字典(过滤后)
  const sheepFolderDict = ref([]) // 羊舍字典
  // 用于存储羊舍名称的字典
  const sheepNameDict = ref({}) 

  // 获取配方编码 & 配方批号 字典
  function getFormulaDict() {
    listFormulaManagement().then(response => {
      formulaIdDict.value = response.rows.map(item => ({
        label: item.formulaId,
        value: item.formulaId
      }))
      // 清空配方批号字典
      formulaBatchMap.value = []

      // 遍历每个配方列表，提取子配方中的批号
      response.rows.forEach(item => {
        if (item.subFormulaList) {
          item.subFormulaList.forEach(subItem => {
            formulaBatchMap.value.push({
              label: subItem.batchId,
              value: subItem.batchId,
              formulaId: item.formulaId // 关联配方ID
            })
          })
        }
      })
    })
  }

  // 处理配方编码变化
  function handleFormulaIdChange(row, value) {
    // 清空配方批号字典
    if (!value) {
      formulaBatchDict.value = []
    } else {
      // 根据选择的formulaId筛选batchId
      formulaBatchDict.value = formulaBatchMap.value;
      formulaBatchDict.value = formulaBatchDict.value.filter(item => item.formulaId === value)
    }

    // 重新设置批号为第一个
    if (formulaBatchDict.value.length > 0) {
      row.batchId = formulaBatchDict.value[0].value;
    }
  }

  function getSheepfoldDict() {
    listSheepfold().then(response => {
      sheepFolderDict.value = response.rows.map(item => ({
        label: item.sheepfoldName,
        value: item.id
      }))
      sheepNameDict.value = response.rows.map(item => ({
        label: item.id,
        value: item.sheepfoldName
      }))
    })
  }

  // 根据id获取羊舍名称
  function getSheepHouseName(id) {
    const dictItem = sheepFolderDict.value.find(item => item.value === id)
    return dictItem ? dictItem.label : id
  }

  // 羊舍ID与名称转换函数：输入可以是 ID 或 羊舍名称
function getSheepHouseId(inputValue, sheepNameDict) {
  if (!inputValue) return '';

  // 输入是纯数字，直接返回
  if (/^\d+$/.test(inputValue)) {
    return inputValue;
  }

  // 输入是名称，返回对应的 id
  const match = sheepNameDict.find(item => item.value === inputValue);
  return match ? match.label : '';
}


  /** 查询饲喂计划列表 */
  function getList() {
    loading.value = true
    listFeedPlan(queryParams.value).then(response => {
      FeedPlanList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

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

  // 表单重置
  function reset() {
    form.value = {
      createDate: null,
      formulaId: null,
      batchId: null,
      sheepHouseId: null,
      sheepCount: null,
      planDailySize: null,
      ratioMorning: null,
      ratioNoon: null,
      ratioAfternoon: null,
      planMorningSize: null,
      planMorningTotal: null,
      actualMorningSize: null,
      planNoonSize: null,
      planNoonTotal: null,
      actualNoonSize: null,
      planAfternoonSize: null,
      planAfternoonTotal: null,
      actualAfternoonSize: null,
      planFeedTotal: null,
      zookeeper: null,
      planDate: null,
      remark: null
    }
    proxy.resetForm("FeedPlanRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    // 如果羊舍ID是名称，则转换为ID
    queryParams.value.sheepHouseId = getSheepHouseId(queryParams.value.sheepHouseId, sheepNameDict.value);
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.createDate)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = "添加饲喂计划"
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const _createDate = row.createDate || ids.value
    getFeedPlan(_createDate).then(response => {
      form.value = response.data
      open.value = true
      title.value = "修改饲喂计划"
    })
  }

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

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _createDates = row.createDate || ids.value
    proxy.$modal.confirm('是否确认删除饲喂计划编号为"' + _createDates + '"的数据项？').then(function () {
      return delFeedPlan(_createDates)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => { })
  }

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

  getList()
  // 获取配方编码字典
  getFormulaDict()
  // 获取羊舍字典
  getSheepfoldDict()
</script>
