<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <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="zookeeper">
        <el-input v-model="queryParams.zookeeper" placeholder="请输入饲草班人员" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="配料日期" prop="deployDate">
        <el-date-picker clearable v-model="queryParams.deployDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择配料日期">
        </el-date-picker>
      </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:FeedList:add']">新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['feed:FeedList:edit']">修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['feed:FeedList:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['feed:FeedList:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" height="1000px" :data="FeedListList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" type="index" width="60" align="center" prop="id" /> -->
      <el-table-column label="配方编号" align="center" prop="formulaId" />
      <el-table-column label="配方批号" align="center" prop="formulaBatchId" />
      <el-table-column label="饲草班人员" align="center" prop="zookeeper" />
      <el-table-column label="计划日期" align="center" prop="rootPlan.planDate" width="180">
        <template #default="scope">
          <!-- <span>{{ parseTime(scope.row.rootPlan.planDate, '{y}-{m}-{d}') }}</span> -->
          <span>{{ scope.row.rootPlan ? parseTime(scope.row.rootPlan.planDate, '{y}-{m}-{d}') : '' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="配料日期" align="center" prop="deployDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deployDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['feed:FeedList:edit']">修改</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['feed:FeedList: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
      v-if="openModel === 'add' || openModel === 'edit'">
      <el-form ref="FeedListRef" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="饲草班人员" prop="zookeeper">
          <el-input v-model="form.zookeeper" placeholder="请输入饲草班人员名称" />
        </el-form-item> -->
          <el-form-item label="技术员">
            <el-select v-model="form.zookeeper" filterable clearable placeholder="请输入饲草班人员姓名" style="width: 100%"
              @change="handleTechnicalChange">
              <el-option v-for="item in technicalOptions" :key="item.value" :label="item.label" :value="item.value">
                <span style="float: left">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="配料日期" prop="deployDate">
          <el-date-picker clearable v-model="form.deployDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择配料日期">
          </el-date-picker>
        </el-form-item> -->
      </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>

  <!-- 弹框：详情/修改 -->
  <el-dialog :title="title" v-model="open" width="60%" append-to-body v-if="openModel === 'view'">
    <!-- 详情页：只读展示 -->
    <div style="padding-bottom:20px ;">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="配方编号">{{ showFeedList.formulaId }}</el-descriptions-item>
        <el-descriptions-item label="配方批号">{{ showFeedList.formulaBatchId }}</el-descriptions-item>
        <el-descriptions-item label="饲养阶段">{{ showFeedList.rootFormula.feedStage }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">配料列表</el-divider>

      <el-table :data="showFeedList.rootFormula.sgFormulaList" stripe border style="width: 100%" max-height="300">
        <el-table-column label="序号" type="index" width="60" align="center" />
        <!-- <el-table-column label="原料编号" prop="materialId" align="center" /> -->
        <el-table-column label="原料" align="center">
          <el-table-column label="名称" prop="materialName" align="center" />
          <el-table-column label="类型" align="center" prop="isGranular">
            <template #default="scope">
              <dict-tag :options="material_type" :value="scope.row.isGranular" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="配量" align="center" prop="ratio">
          <el-table-column label="上午" align="center" prop="ratio" sortable>
            <template #default="scope">
              {{ (scope.row.ratio / 100 * showFeedList.rootPlan.planMorningSize).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="中午" align="center" prop="ratio" sortable>
            <template #default="scope">
              {{ (scope.row.ratio / 100 * showFeedList.rootPlan.planNoonSize).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="下午" align="center" prop="ratio" sortable>
            <template #default="scope">
              {{ (scope.row.ratio / 100 * showFeedList.rootPlan.planAfternoonSize).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="类型" prop="isSupplement" align="center">
          <template #default="scope">
            <dict-tag :options="materialType" :value="scope.row.isSupplement" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
</template>

<script setup name="FeedList">
  import { listFeedList, getFeedList, delFeedList, addFeedList, updateFeedList } from "@/api/feed/FeedList"
  import { getUserByPost } from '@/api/common/user'
  const { proxy } = getCurrentInstance()

  const FeedListList = 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,
      zookeeper: null,
      deployDate: null
    },
    rules: {
    }
  })

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

  const showFeedList = ref({})
  const openModel = ref("")
  // 原料类型字典
  const { material_type } = proxy.useDict('material_type')
  // 原料类型
  const materialType = [
    { value: '1', label: '补饲原料' },
    { value: '0', label: '原料' }
  ]
  function handleView(row) {
    showFeedList.value = row
    open.value = true
    openModel.value = "view"
    title.value = "配料清单详情"
    console.log("查看配料清单", row)
    console.log("HandView", showFeedList.value)
  }

  /** 查询配料清单列表 */
  function getList() {
    loading.value = true
    listFeedList(queryParams.value).then(response => {
      FeedListList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

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

  // 表单重置
  function reset() {
    form.value = {
      id: null,
      formulaId: null,
      formulaBatchId: null,
      zookeeper: null,
      deployDate: null
    }
    proxy.resetForm("FeedListRef")
  }

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

  /** 重置按钮操作 */
  function resetQuery() {
    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()
    open.value = true
    title.value = "添加配料清单"
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const _id = row.id || ids.value
    console.log("HandleUpdate => 配料清单ID =>", _id)
    getFeedList(_id).then(response => {
      form.value = response.data
      open.value = true
      openModel.value = "edit"
      title.value = "修改配料清单"
    })
  }

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

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal.confirm('是否确认删除配料清单编号为"' + _ids + '"的数据项？').then(function () {
      return delFeedList(_ids)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => { })
  }

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

  const technicalOptions = ref([])   //自定义技术员数组变量

  // 获取技术员列表
  const fetchTechnicalList = () => {
    getUserByPost({ postCode: "techs" })
      .then(res => {
        if (res.code === 200 && Array.isArray(res.data)) {
          technicalOptions.value = res.data.map(item => ({
            // value: item.userId,
            value: item.nickName,
            label: item.nickName,
            // postName: item.postName,      // 保留用于下拉显示
            // postCode: item.postCode       // 保留用于逻辑判断
          }))
          console.log(technicalOptions.value);

        } else {
          technicalOptions.value = []
          ElMessage.warning(res.msg || '获取技术员列表失败')
        }
      })

  }
  /* ------------------ 初始化 ------------------ */
  onMounted(() => {
    fetchTechnicalList()   //在onMounted()函数中调用获取技术员列表的函数
  })
  getList()
</script>
