<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="牧场" prop="ranchId">
        <el-select v-model="queryParams.ranchId" placeholder="请选择牧场" style="width:200px" clearable>
          <el-option
            v-for="dict in da_ranch"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="羊舍类型" prop="sheepfoldTypeId">
        <el-select v-model="queryParams.sheepfoldTypeId" placeholder="请选择羊舍类型"  style="width:200px"  clearable>
          <el-option
            v-for="dict in bas_sheepfold_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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="['sheepfold_management:sheepfold_management:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleBatchDelete"
          v-hasPermi="['sheepfold_management:sheepfold_management:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sheepfold_management:sheepfold_management:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主表格：羊舍级别汇总数据，每个羊舍一行 -->
    <el-table v-loading="loading" :data="sheepfoldSummaryList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="牧场" align="center" prop="ranchId" sortable>
        <template #default="scope">
          <dict-tag :options="da_ranch" :value="scope.row.ranchId"/>
        </template>
      </el-table-column>
      <!-- 羊舍名称（唯一），添加点击事件 -->
      <el-table-column label="羊舍名称" align="center" prop="sheepfoldName" sortable>
        <template #default="scope">
          <span style="color: #409eff; cursor: pointer;" @click="openSheepfoldDetail(scope.row)">
            {{ scope.row.sheepfoldName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="羊舍类型" align="center" prop="sheepfoldTypeId" sortable>
        <template #default="scope">
          <dict-tag :options="bas_sheepfold_type" :value="scope.row.sheepfoldTypeId"/>
        </template>
      </el-table-column>
      <el-table-column label="羊舍编号" align="center" prop="sheepfoldNo" sortable/>
      <el-table-column label="羊数" align="center" prop="totalSheepCount" sortable/>
      <el-table-column label="备注" align="center" prop="comment" sortable/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sheepfold_management:sheepfold_management:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="sheepfoldSummaryList.length"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 羊舍详情弹窗：栏位级别明细 -->
    <el-dialog 
      title="羊舍栏位详情" 
      v-model="subDialogVisible" 
      width="800px" 
      append-to-body
    >
      <el-table v-loading="subLoading" :data="subSheepfoldList" border>
        <el-table-column label="牧场" align="center" prop="ranchId">
          <template #default="scope">
            <dict-tag :options="da_ranch" :value="scope.row.ranchId"/>
          </template>
        </el-table-column>
    <!-- 羊舍名称列：固定显示点击的主表格名称 -->
        <el-table-column label="羊舍名称" align="center">
          <template #default="scope">
            {{ selectedSheepfoldName }} <!-- 不再用后端返回的，直接用选中的名称 -->
          </template>
        </el-table-column>
        <el-table-column label="栏舍名称" align="center">
          <template #default="scope">
            {{ scope.row.sheepfoldName }}（{{ scope.row.rowNo }}排{{ scope.row.columns }}栏）
          </template>
        </el-table-column>
            <!-- 羊数列：显示单栏位羊数，处理空值为0 -->
        <el-table-column label="羊数" align="center">
          <template #default="scope">
            {{ scope.row.sheepCount || 0 }} <!-- 空值显示0 -->
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="comment"/>
      </el-table>
    <!-- 2. 新增：总羊数展示区域（放在表格下方） -->
    <div style="text-align: left; margin-top: 15px; font-size: 16px; font-weight: bold;">
      该羊舍总羊数：{{ selectedTotalSheepCount }} 只
    </div>


      <template #footer>
        <el-button @click="subDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 牧场羊舍示意图（保留原有） -->
    <!-- <el-divider>牧场羊舍示意图</el-divider>
    <el-collapse
      v-model="activeNames"
      accordion
      style="margin-top: 16px; max-width: 100%; overflow-x: auto"
    >
      <el-collapse-item
        v-for="ranch in seatMapTree"
        :key="ranch.ranchId"
        :title="ranch.ranchName"
        :name="ranch.ranchId"
      >
        <el-collapse accordion>
          <el-collapse-item
            v-for="type in ranch.types"
            :key="type.typeId"
            :title="`${type.typeName} (${type.folds.length}个)`"
          >
            <el-row :gutter="16">
              <el-col
                v-for="fold in type.folds"
                :key="fold.foldNo"
                :xs="24"
                :sm="12"
                :md="8"
                :lg="6"
                :xl="4"
                style="margin-bottom: 16px"
              >
                <el-card shadow="hover">
                  <template #header>
                    <span>{{ fold.foldNo }}号{{type.typeName}}</span>
                  </template>
                  <div
                    v-for="row in fold.rows"
                    :key="row.rowNo"
                    class="seat-block"
                  >
                    <div class="row-label">{{ row.rowNo }}排</div>
                    <div class="seat-row">
                      <div
                        v-for="col in row.columns"
                        :key="col"
                        class="seat"
                        :class="{ occupied: isOccupied(fold.foldNo, row.rowNo, col) }"
                        @click="toggleSeat(fold.foldNo, row.rowNo, col)"
                      >
                        {{ col }}
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-collapse-item>
    </el-collapse> -->

    <!-- 添加或修改羊舍管理对话框（保留原有） -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="sheepfold_managementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="牧场" prop="ranchId">
          <el-select v-model="form.ranchId" placeholder="请选择牧场">
            <el-option
              v-for="dict in da_ranch"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="羊舍类型" prop="sheepfoldTypeId">
          <el-select v-model="form.sheepfoldTypeId" placeholder="请选择羊舍类型">
            <el-option
              v-for="dict in bas_sheepfold_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="羊舍编号" prop="sheepfoldNo">
          <el-input v-model="form.sheepfoldNo" placeholder="请输入羊舍编号" @input="validateSheepfoldNo" />
            <div v-if="sheepfoldNoExists" style="color: red; font-size: 12px; margin-top: 5px;">
              该羊舍编号已存在
            </div>
        </el-form-item>
        <el-form-item label="排数" prop="rowCount">
          <el-input-number 
            v-model="form.rowCount" 
            :min="1" 
            :max="10" 
            @change="handleRowCountChange"
            placeholder="请输入排数" 
          />
        </el-form-item>
        <div v-for="(row, index) in form.rowsConfig" :key="index" class="row-config">
          <el-form-item 
            :label="`${String.fromCharCode(65 + index)}排栏位数`" 
            :prop="`rowsConfig.${index}.columnCount`" 
            :rules="{
              required: true, 
              message: `请填写${String.fromCharCode(65 + index)}排栏位数`, 
              trigger: 'blur'
            }"
          >
            <el-input-number 
              v-model="row.columnCount" 
              :min="1" 
              :max="99" 
              placeholder="请输入栏位数" 
            />
          </el-form-item>
        </div>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="form.comment" placeholder="请输入备注" />
        </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>
</template>

<script setup name="Sheepfold_management">
import { deleteSheepfoldByCondition,batchDeleteSheepfoldByCondition, listSheepfoldSummary, getSeatMap,listSheepfold_management, getSheepfold_management, delSheepfold_management, addSheepfold_management, updateSheepfold_management,checkSheepfoldNoExist } from "@/api/fileManagement/sheepfold_management"

const { proxy } = getCurrentInstance()
const { bas_sheepfold_type, da_ranch } = proxy.useDict('bas_sheepfold_type', 'da_ranch')

// 原有变量
const sheepfold_managementList = ref([]) // 原始栏位明细数据
const sheepfoldSummaryList = 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 sheepfoldNoExists = ref(false)
const activeNames = ref([])
const seatMapTree = ref([])
const occupied = ref(new Set())

// 新增子弹窗相关变量
const subDialogVisible = ref(false) // 子弹窗显示状态
const subLoading = ref(false) // 子表格加载状态
const subSheepfoldList = ref([]) // 子表格数据
const selectedSheepfold = ref(null) // 选中的羊舍信息
const selectedSheepfoldName = ref(''); // 新增：存储点击的羊舍名称（如“1号产羔舍”）
// 2. 新增变量：存储选中行的总羊数（兜底为0）
const selectedTotalSheepCount = ref(0);



const data = reactive({
    form: {
    id: null,
    ranchId: null,
    sheepfoldName: null,
    sheepfoldTypeId: null,
    sheepfoldNo: null,
    rowCount: 1,
    rowsConfig: [{ columnCount: 1 }],
    comment: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ranchId: null,
    sheepfoldTypeId: null,
  },
   rules: {
    rowCount: [
      { required: true, message: "排数不能为空", trigger: "blur" },
      { type: 'number', min: 1, max: 10, message: '排数在1-10之间', trigger: 'blur' }
    ],
    sheepfoldNo: [
      { required: true, message: "羊舍编号不能为空", trigger: "blur" },
      { pattern: /^\d*$/, message: "羊舍编号必须为数字", trigger: "blur" }
    ],
    ranchId: [
      { required: true, message: "牧场不能为空", trigger: "blur" }
    ],
    sheepfoldTypeId: [
      { required: true, message: "羊舍类型不能为空", trigger: "blur" }
    ]
  }
})

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

// 原有方法
const handleRowCountChange = (count) => {
  count = Number(count)
  form.value.rowsConfig = []
  for (let i = 0; i < count; i++) {
    form.value.rowsConfig.push({
      rowLetter: String.fromCharCode(65 + i),
      columnCount: 1
    })
  }
}
// 修改getList方法（主表格加载汇总数据）
function getList() {
  loading.value = true
  // 调用汇总接口，而非原有明细接口
  listSheepfoldSummary(queryParams.value).then(response => {
    sheepfoldSummaryList.value = response.rows // 汇总数据（每个羊舍一行）
    total.value = sheepfoldSummaryList.value.length
    loading.value = false
  })
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    id: null,
    ranchId: null,
    sheepfoldName: null,
    sheepfoldTypeId: null,
    sheepfoldNo: null,
    rowCount: 1,
    rowsConfig: [{ columnCount: 1 }],
    comment: null
  }
  proxy.resetForm("sheepfold_managementRef")
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
  loadSeatMap()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 选中事件：正确存储选中数据+更新禁用状态
function handleSelectionChange(selection) {
  ids.value = selection; // 存储所有选中的行数据（关键）
  single.value = selection.length !== 1; // 单条选中判断（不影响批量）
  multiple.value = selection.length === 0; // 批量按钮禁用逻辑：无选中则禁用
}

function handleAdd() {
  reset()
  open.value = true
  sheepfoldNoExists.value = false
  title.value = "添加羊舍管理"
}

function findDictLabelByValue(dictOptions, value) {
  const formattedValue = String(value);
  const foundOption = dictOptions.value.find(option => option.value === formattedValue);
  return foundOption ? foundOption.label : '';
}

function validateSheepfoldNo() {
  const sheepfoldNo = form.value.sheepfoldNo
  if (sheepfoldNo) {
    const cleanedInput = sheepfoldNo.replace(/\D/g, '')
    if (cleanedInput !== sheepfoldNo) {
      form.value.sheepfoldNo = cleanedInput
      proxy.$modal.msgWarning("羊舍编号只能输入数字")
    }
  }
}

async function checkSheepfoldNoExistence() {
  if (!form.value.sheepfoldNo || !form.value.ranchId || !form.value.sheepfoldTypeId) {
    sheepfoldNoExists.value = false
    return
  }
  try {
    const exist = await checkSheepfoldNoExist(form.value.ranchId, form.value.sheepfoldTypeId, form.value.sheepfoldNo)
    sheepfoldNoExists.value = exist.data
  } catch (error) {
    proxy.$modal.msgError("检查羊舍编号时出错：" + error.message)
    sheepfoldNoExists.value = false
  }
}

function submitForm() {
  proxy.$refs["sheepfold_managementRef"].validate(async valid => {
    if (valid) {
      await checkSheepfoldNoExistence()
      if (sheepfoldNoExists.value) {
        proxy.$modal.msgError("该羊舍编号已存在，无法重复添加")
        return
      }
      if (form.value.id != null) {
        updateSheepfold_management(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
          loadSeatMap()
        })
      } else {
        const requests = []
        const ranchName = findDictLabelByValue(da_ranch, form.value.ranchId)
        const typeName = findDictLabelByValue(bas_sheepfold_type, form.value.sheepfoldTypeId)
        form.value.rowsConfig.forEach((rowConfig, rowIndex) => {
          const rowNo = String.fromCharCode(65 + rowIndex)
          for (let i = 1; i <= rowConfig.columnCount; i++) {
            const columnNo = i.toString().padStart(2, '0')
            const record = {
              ranchId: form.value.ranchId,
              sheepfoldTypeId: form.value.sheepfoldTypeId,
              sheepfoldNo: form.value.sheepfoldNo,
              rowNo: rowNo,
              columns: columnNo,
              comment: form.value.comment,
              sheepfoldName: `${form.value.sheepfoldNo}号-${typeName}-${rowNo}${columnNo}`
            }
            requests.push(addSheepfold_management(record))
          }
        })
        Promise.all(requests)
          .then(() => {
            proxy.$modal.msgSuccess(`新增成功，共添加${requests.length}条记录`)
            open.value = false
            getList()
            loadSeatMap()
          })
          .catch(error => {
            proxy.$modal.msgError("部分记录添加失败：" + error.message)
          })
      }
    }
  })
}

// 单条删除方法（确保调用正确接口，无路径错误）
function handleDelete(row) {
  const deleteData = {
    ranchId: row.ranchId,
    sheepfoldNo: row.sheepfoldNo,
    sheepfoldTypeId: row.sheepfoldTypeId,
  }
  proxy.$modal.confirm(`是否确认删除【${row.sheepfoldName}】的数据？`).then(function() {
    // 仅调用新的组合条件删除接口，无其他DELETE请求
    return deleteSheepfoldByCondition(deleteData)
  }).then(() => {
    getList()
    loadSeatMap(); 
    proxy.$modal.msgSuccess("删除成功")
  }).catch((err) => {
    proxy.$modal.msgError(err.msg || "删除失败")
  })
}

// 批量删除核心方法（完整逻辑）
function handleBatchDelete() {
  // 1. 校验：是否选中数据
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的羊舍数据！");
    return;
  }

  // 2. 组装批量删除参数（每行取核心字段）
  const deleteList = ids.value.map(row => ({
    ranchId: row.ranchId,
    sheepfoldNo: row.sheepfoldNo,
    sheepfoldTypeId: row.sheepfoldTypeId,
    sheepfoldName: row.sheepfoldName // 若后端已移除该字段校验，可删除
  }));

  // 3. 确认删除+调用批量接口
  proxy.$modal.confirm(
    `是否确认删除选中的${ids.value.length}条羊舍数据？删除后不可恢复！`,
    "警告",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    // 调用批量删除接口
    return batchDeleteSheepfoldByCondition(deleteList);
  }).then((response) => {
    // 4. 成功处理：刷新列表+提示
    proxy.$modal.msgSuccess(response.msg || "批量删除成功");
    getList(); // 刷新表格数据
    loadSeatMap(); // 刷新座位图（可选）
  }).catch((err) => {
    // 5. 失败处理：提示错误
    proxy.$modal.msgError(err.msg || "批量删除失败");
  });
}

function handleExport() {
  // 修改为调用汇总导出接口
  proxy.download('sheepfold_management/sheepfold_management/exportSummary', {
    ...queryParams.value
  }, `羊舍管理汇总数据_${new Date().getTime()}.xlsx`)
}

const loadSeatMap = () => {
  getSeatMap()
    .then(res => (seatMapTree.value = res.data))
    .catch(err => proxy.$modal.msgError('加载座位图失败：' + err.message))
}

const isOccupied = (foldNo, rowNo, col) =>
  occupied.value.has(`${foldNo}-${rowNo}-${col}`)
const toggleSeat = (foldNo, rowNo, col) => {
  const key = `${foldNo}-${rowNo}-${col}`
  occupied.value.has(key)
    ? occupied.value.delete(key)
    : occupied.value.add(key)
}

// 辅助方法：获取字典标签
const getDictLabel = (dictOptions, value) => {
  const formattedValue = String(value);
  const foundOption = dictOptions.find(option => option.value === formattedValue);
  return foundOption ? foundOption.label : '';
}



// 打开羊舍详情弹窗
const openSheepfoldDetail = (row) => {
  selectedSheepfold.value = row
  // 新增：给选中的羊舍名称赋值
  selectedSheepfoldName.value = row.sheepfoldName 
    // 2. 核心：存储选中行的总羊数，兜底为0（避免无数据时显示空）
  selectedTotalSheepCount.value = row.totalSheepCount || 0;
  subDialogVisible.value = true
  getSubSheepfoldList()
}


// 点击主表格羊舍名称的方法（修改：传入选中的羊舍名称）
const openSubTable = (row) => {
  selectedSheepfoldName.value = row.sheepfoldName; // 存储点击的羊舍名称（主表格的名称）
  subDialogVisible.value = true;
  getSubSheepfoldList(row); // 调用子表格数据查询
};

// 获取羊舍详情列表（按羊舍编号+牧场+类型筛选）
const getSubSheepfoldList = () => {
  subLoading.value = true
  // 构造查询参数：筛选当前羊舍的所有栏位
  const params = {
    ranchId: selectedSheepfold.value.ranchId,
    sheepfoldTypeId: selectedSheepfold.value.sheepfoldTypeId,
    sheepfoldNo: selectedSheepfold.value.sheepfoldNo,
    pageNum: 1,
    pageSize: 999 // 一次性加载所有栏位
  }
  listSheepfold_management(params).then(response => {
    subSheepfoldList.value = response.rows
    subLoading.value = false
  }).catch(err => {
    proxy.$modal.msgError('加载羊舍详情失败：' + err.message)
    subLoading.value = false
  })
}

onMounted(() => {
  getList()
  loadSeatMap()
})

getList()
loadSeatMap()
</script>

<style scoped>
.row-config {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.seat-block {
  margin-bottom: 8px;
}
.row-label {
  font-weight: bold;
  margin-bottom: 4px;
}
.seat-row {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
.seat {
  width: 32px;
  height: 32px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  cursor: pointer;
  background: #f2f6fc;
}
.seat.occupied {
  background: #67c23a;
  color: #fff;
}
</style>