<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="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sheepfold_management:sheepfold_management:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          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="sheepfold_managementList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="羊舍id" align="center" prop="id" sortable/>
      <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/>
      <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="rowNo" sortable/>
      <el-table-column label="栏号" align="center" prop="columns" 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="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sheepfold_management:sheepfold_management:edit']">修改</el-button> -->
          <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="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


<!-- ===== 图形化展示区域 ===== -->
    <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="sheepfoldName">
          <el-input v-model="form.sheepfoldName" placeholder="请输入羊舍名称" />
        </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="rowNo">
          <el-input v-model="form.rowNo" placeholder="请输入排号" />
        </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>

        <!-- <el-form-item label="栏号" prop="columns">
          <el-input v-model="form.columns" 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 { 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 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 data = reactive({
    form: {
    id: null,
    ranchId: null,
    sheepfoldName: null,
    sheepfoldTypeId: null,
    sheepfoldNo: null,
    rowCount: 1, // 默认1排
    rowsConfig: [{ columnCount: 1 }], // 默认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是数字
  count = Number(count)
  
  // 重置rowsConfig
  form.value.rowsConfig = []
  
  // 根据排数生成配置项
  for (let i = 0; i < count; i++) {
    form.value.rowsConfig.push({
      rowLetter: String.fromCharCode(65 + i), // A, B, C...
      columnCount: 1 // 默认1栏
    })
  }
}

/** 查询羊舍管理列表 */
function getList() {
  loading.value = true
  listSheepfold_management(queryParams.value).then(response => {
    sheepfold_managementList.value = response.rows
    total.value = response.total
    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.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  sheepfoldNoExists.value = false
  title.value = "添加羊舍管理"
}

/** 修改按钮操作 */
// function handleUpdate(row) {
//   reset()
//   const _id = row.id || ids.value
//   getSheepfold_management(_id).then(response => {
//     form.value = response.data
//     // 修改时不需要rowsConfig
//     if (form.value.rowsConfig) {
//       delete form.value.rowsConfig
//       delete form.value.rowCount
//     }
//     open.value = true
//     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) => {
          // 使用行索引 + 1 作为排号
          const rowNo = String.fromCharCode(65 + rowIndex) // A, B, C...
          
          for (let i = 1; i <= rowConfig.columnCount; i++) {
            const columnNo = i.toString().padStart(2, '0') // 01, 02, 03...
            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 _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除羊舍管理编号为"' + _ids + '"的数据项？').then(function() {
    return delSheepfold_management(_ids)
  }).then(() => {
    getList()
    loadSeatMap(); 
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

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

/* ===== 图形化展示所需变量和方法 ===== */
const activeNames = ref([]) // 当前展开的牧场
const seatMapTree = ref([]) // 树形结构数据
const loadSeatMap = () => {
  getSeatMap()
    .then(res => (seatMapTree.value = res.data))
    .catch(err => proxy.$modal.msgError('加载座位图失败：' + err.message))
}

    
  


/* 演示：点击栏位切换颜色 */
const occupied = ref(new Set())
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)
}

/* 页面加载时拉取数据 */
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>