<template>
  <el-skeleton :rows="30" :loading="pageBasicsData.loading" />
  <!-- 场景管理 -->
  <div class="regional-grid" v-if="!pageBasicsData.loading">
    <!-- 内容区域 -->
    <div class="regional-grid-content">
      <div>
        <!-- 顶部功能按钮 -->
        <div class="grid-right-btn" ref="topSearchRef">
          <!-- 搜索区域 -->
          <qu-search-area :model="pageBasicsData.screenForm" @search="restSearch" @reset="clearScreen">
              <el-form-item label="所属站点" prop="districtId">
                <div class="screen-item">
                  <el-select
                    filterable
                    placeholder="请选择"
                    v-model="pageBasicsData.screenForm.districtId"
                  >
                    <el-option
                      :label="item.name"
                      :value="item.id"
                      v-for="item in pageBasicsData.districtList"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="网格">
                <el-cascader
                  ref="gridCascaderRef"
                  v-model="gridCascaderValue"
                  :options="gridTreeOptions"
                  :props="{
                    children: 'childNode',
                    label: 'name',
                    value: 'gridId',
                    checkStrictly: true,
                    emitPath: false,
                  }"
                  clearable
                  filterable
                  placeholder="请选择网格"
                  style="width: 200px"
                  @change="gridCascaderChange"
                />
              </el-form-item>
              <el-form-item label="场景名称" prop="name">
                <div class="screen-item">
                  <el-input
                    placeholder="请输入场景名称"
                    clearable
                    v-model="pageBasicsData.screenForm.name"
                  ></el-input>
                </div>
              </el-form-item>
              <el-form-item label="场景级别" prop="scenesLevel">
                <div class="screen-item">
                  <el-select
                    clearable
                    filterable
                    placeholder="请选择"
                    v-model="pageBasicsData.screenForm.scenesLevel"
                  >
                    <el-option
                      :label="item.value"
                      :value="item.key"
                      v-for="item in selectItems['scenesLevel']"
                      :key="item.key"
                    ></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="区域名称" prop="superiorGridName">
                <div class="screen-item">
                  <el-input
                    placeholder="请输入区域名称"
                    clearable
                    v-model="pageBasicsData.screenForm.superiorGridName"
                  ></el-input>
                </div>
              </el-form-item>
              <el-form-item label="品质等级" prop="qualityLevel">
                <div class="screen-item">
                  <el-select
                    filterable
                    clearable
                    placeholder="请选择"
                    v-model="pageBasicsData.screenForm.qualityLevel"
                  >
                    <el-option
                      :label="item.value"
                      :value="item.key"
                      v-for="item in selectItems['qualityLevel']"
                      :key="item.key"
                    ></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="停/启用状态" prop="enableStatus">
                <div class="screen-item">
                  <el-select
                    filterable
                    clearable
                    placeholder="请选择"
                    v-model="pageBasicsData.screenForm.enableStatus"
                  >
                    <el-option
                      :label="item.value"
                      :value="item.key"
                      v-for="item in selectItems['enableStatus']"
                      :key="item.key"
                    ></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="场景属性" prop="scenesType">
                <div class="screen-item">
                  <el-select
                    filterable
                    clearable
                    v-model="pageBasicsData.screenForm.scenesType"
                  >
                    <el-option
                      :label="item.value"
                      :value="item.key"
                      v-for="item in selectItems['scenesType']"
                      :key="item.key"
                    ></el-option>
                  </el-select>
                </div>
              </el-form-item>
          </qu-search-area>
        </div>
      </div>
      <!-- 表格 -->
      <div class="main-table">
        <qu-table
          :custom="true"
          :showPage="true"
          :showIndex="true"
          :height="pageBasicsData.tableHeight"
          :tableData="tableData"
          :tableHeader="tableHeader"
          :pageProps="pageProps"
          @pageChange="pageChange"
          :rowButtons="rowButtons"
          @rowButtonClick="rowButtonClick"
          @fetchTableAttr="fetchTableAttr"
          :tableButtons="[
            {
              cnName: '新建',
              enName: 'add',
              theme: 'success',
              icon: 'plus',
            },
            {
              cnName: '导出',
              enName: 'export',
              theme: 'primary',
              icon: 'top',
            },
          ]"
          @buttonClick="buttonClick"
        ></qu-table>
      </div>
    </div>
  </div>

  <!-- 新建弹窗 -->
  <el-dialog
    v-model="pageBasicsData.isAddDialog"
    title="新建场景"
    width="660px"
    @close="closeAddDialog"
  >
    <el-form
      style="border-top: 1px solid #dcdfe6; border-bottom: 1px solid #dcdfe6"
      label-width="140px"
      ref="addRef"
      :model="addForm"
    >
      <el-scrollbar height="480px" always>
        <el-form-item
          label="所属站点"
          style="padding-top: 40px; padding-left: 20px"
          prop="districtId"
          :rules="{
            required: true,
            message: '请选择所属站点',
            trigger: 'change',
          }"
        >
          <el-select
            style="width: 350px"
            filterable
            placeholder="请选择"
            v-model="addForm.districtId"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in pageBasicsData.districtList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="区域网格"
          style="padding-left: 20px"
          prop="gridSelect"
          :rules="{
            required: true,
            message: '请选择区域网格',
            trigger: 'change',
          }"
        >
          <el-cascader
            style="width: 350px"
            ref="gridRef"
            clearable
            v-model="addForm.gridSelect"
            :options="pageBasicsData.addTreeData"
            :props="pageBasicsData.areaGridSelectProps"
            @change="gridHandleChange"
            @focus="
              () => {
                if (pageBasicsData.addTreeData.length <= 0) {
                  $message.warning(
                    '当前选择的所属站点暂无区域网格,请重新选择!'
                  );
                }
              }
            "
          >
            <template #default="{ data }">
              <span>{{ data.name }}</span>
            </template>
          </el-cascader>
        </el-form-item>
        <div
          class="generated"
          v-for="(scene, index) in addForm.scenes"
          :key="index"
        >
          <div class="generated-left">
            <el-form-item label="场景级别">
              <el-select
                style="width: 350px"
                filterable
                clearable
                :disabled="index > 0"
                placeholder="请选择"
                :prop="`scenes[${index}].scenesLevel`"
                v-model="scene.scenesLevel"
                @change="scenesLevelChange(index, $event)"
              >
                <el-option
                  :label="item.value"
                  :value="item.key"
                  v-for="item in selectItems['scenesLevel']"
                  :key="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="上级场景"
              :prop="`scenes[${index}].superiorScenesId`"
              :rules="{
                required: true,
                message: '请选择上级场景',
                trigger: 'blur',
              }"
              v-if="addForm.scenes[index].scenesLevel > 1"
            >
              <el-select
                style="width: 350px"
                filterable
                clearable
                placeholder="请选择"
                v-model="scene.superiorScenesId"
                @focus="
                  () => {
                    if (pageBasicsData.superiorScenesList.length <= 0) {
                      $message.warning(
                        '当前选择的区域网格暂无上级场景,请重新选择!'
                      );
                    }
                  }
                "
                @change="
                  sceneChange(index, $event, pageBasicsData.superiorScenesList)
                "
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="item in pageBasicsData.superiorScenesList"
                  :key="item.id"
                  :disabled="item.scenesType == 0"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="场景名称"
              :prop="`scenes[${index}].name`"
              :rules="{
                required: true,
                message: '请选择场景名称',
                trigger: 'change',
              }"
            >
              <el-input style="width: 350px" v-model="scene.name" />
            </el-form-item>
            <el-form-item
              label="场景属性"
              :prop="`scenes[${index}].scenesType`"
              :rules="{
                required: true,
                message: '请选择场景属性',
                trigger: 'change',
              }"
            >
              <el-select
                style="width: 350px"
                filterable
                clearable
                placeholder="请选择"
                v-model="scene.scenesType"
                :disabled="addForm.scenes[index].scenesLevel > 1 ? true : false"
              >
                <el-option
                  :label="item.value"
                  :value="item.key"
                  v-for="item in selectItems['scenesType']"
                  :key="item.key"
                  :disabled="item.key == 0"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="场景环境品质等级"
              :prop="`scenes[${index}].qualityLevel`"
              :rules="{
                required: true,
                message: '请选择环境品质等级',
                trigger: 'change',
              }"
            >
              <el-select
                style="width: 350px"
                filterable
                clearable
                placeholder="请选择"
                v-model="scene.qualityLevel"
              >
                <el-option
                  :label="item.value"
                  :value="item.key"
                  v-for="item in selectItems['qualityLevel']"
                  :key="item.key"
                ></el-option>
              </el-select>

              <el-popover width="720px" placement="bottom">
                <template #reference>
                  <el-icon color="orange" size="20px" style="margin-left: 10px"
                    ><warning
                  /></el-icon>
                </template>
                <img class="table-img" src="../../Assets/img/levelInfo.png" />
              </el-popover>
            </el-form-item>
            <el-form-item
              label="停/启用状态"
              :prop="`scenes[${index}].enableStatus`"
              :rules="{
                required: true,
                message: '请选择停/启用状态',
                trigger: 'change',
              }"
            >
              <el-select
                style="width: 350px"
                filterable
                clearable
                placeholder="请选择"
                v-model="scene.enableStatus"
              >
                <el-option
                  :label="item.value"
                  :value="item.key"
                  v-for="item in selectItems['enableStatus']"
                  :key="item.key"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="备注" :prop="`scenes[${index}].note`">
              <el-input
                v-model="scene.note"
                style="width: 350px"
                autosize
                maxlength="500"
                placeholder="请输入备注信息(非必填,限500字以内)"
              />
            </el-form-item>
          </div>
          <div class="generated-right">
            <el-icon
              color="#666666"
              size="18px"
              style="display: block"
              @click="addSceneForm"
              ><plus
            /></el-icon>
            <el-icon
              color="#666666"
              size="18px"
              style="display: block; margin-top: 10px"
              @click="removeSceneForm(scene)"
              ><remove
            /></el-icon>
          </div>
        </div>
      </el-scrollbar>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button style="width: 90px" @click="closeAddDialog()"
          >取消</el-button
        >
        <el-button style="width: 90px" type="primary" @click="submitForm"
          >提交</el-button
        >
      </span>
    </template>
  </el-dialog>

  <!-- 编辑弹窗 -->
  <el-dialog
    v-model="pageBasicsData.isEditDialog"
    title="编辑"
    width="600px"
    @close="closeEditDialog"
  >
    <el-form
      class="dialog-form"
      label-width="140px"
      ref="editRef"
      :model="editForm"
    >
      <el-form-item
        label="所属站点"
        style="padding-top: 40px"
        prop="districtName"
        :rules="{
          required: true,
          message: '请选择所属站点',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          :disabled="true"
          placeholder="请选择"
          v-model="editForm.districtName"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        label="区域网格"
        prop="superiorGridName"
        :rules="{
          required: true,
          message: '请选择区域网格',
          trigger: 'change',
        }"
      >
        <el-input
          style="width: 350px"
          clearable
          :disabled="true"
          v-model="editForm.superiorGridName"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="场景级别">
        <el-select
          style="width: 350px"
          filterable
          clearable
          :disabled="true"
          placeholder="请选择"
          v-model="editForm.scenesLevel"
        >
        </el-select>
      </el-form-item>
      <el-form-item label="上级场景" v-if="editForm.superiorScenesName">
        <el-select
          style="width: 350px"
          filterable
          clearable
          :disabled="true"
          placeholder="请选择"
          v-model="editForm.superiorScenesName"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        label="场景名称"
        prop="name"
        :rules="{
          required: true,
          message: '请输入场景名称',
          trigger: 'change',
        }"
      >
        <el-input style="width: 350px" v-model="editForm.name" />
      </el-form-item>
      <el-form-item
        label="场景属性"
        prop="scenesType"
        :rules="{
          required: true,
          message: '请选择场景属性',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="editForm.scenesType"
          :disabled="editForm.scenesType == 0"
        >
          <el-option
            :label="item.value"
            :value="item.key"
            v-for="item in selectItems['scenesType']"
            :key="item.key"
            :disabled="item.key == 0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="场景环境品质等级"
        prop="qualityLevel"
        :rules="{
          required: true,
          message: '请选择环境品质等级',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="editForm.qualityLevel"
        >
          <el-option
            :label="item.value"
            :value="item.key"
            v-for="item in selectItems['qualityLevel']"
            :key="item.key"
          ></el-option>
        </el-select>

        <el-popover width="720px" placement="bottom">
          <template #reference>
            <el-icon color="orange" size="20px" style="margin-left: 10px"
              ><warning
            /></el-icon>
          </template>
          <img class="table-img" src="../../Assets/img/levelInfo.png" />
        </el-popover>
      </el-form-item>
      <el-form-item
        label="停/启用状态"
        prop="enableStatus"
        :rules="{
          required: true,
          message: '请选择停/启用状态',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="editForm.enableStatus"
        >
          <el-option
            :label="item.value"
            :value="item.key"
            v-for="item in selectItems['enableStatus']"
            :key="item.key"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="editForm.note"
          style="width: 350px"
          type="textarea"
          autosize
          maxlength="500"
          placeholder="请输入备注信息(非必填,限500字以内)"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button style="width: 90px" @click="closeEditDialog">取消</el-button>
        <el-button style="width: 90px" type="primary" @click="editSubmitForm"
          >提交</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import { sceneManageService } from "@/ApiService/basicInfoService";
import { dropdownService } from "@/ApiService/dropdownService";

// 页面基础数据
const pageBasicsData = reactive({
  treeData: [], // 左侧树结构数据
  addTreeData: [], // 添加时树结构数据
  tableHeight: 200, //表格高度
  loading: true, // 加载状态
  screenForm: {
    // 顶部搜索字段
    districtId: "",
    name: "",
    scenesLevel: 1,
    superiorGridName: "",
    qualityLevel: "",
    enableStatus: "",
    gridLevel: "",
    gridId: "",
    scenesType: "",
  },
  isAddDialog: false, // 新增弹窗
  isEditDialog: false, // 编辑弹窗
  districtList: [], // 所属站点
  superiorScenesList: [], // 一级场景下拉
  areaGridSelectProps: {
    // 区域网格级联配置
    expandTrigger: "hover",
    multiple: true,
    value: "gridId",
    label: "name",
    children: "childNode",
    checkStrictly: true,
  },
});

// 新增弹窗字段
let addForm = reactive({
  districtId: "",
  gridSelect: [],
  scenes: [
    {
      scenesLevel: 1,
      superiorScenesId: "",
      name: "",
      qualityLevel: "",
      enableStatus: "",
      note: "",
      scenesType: "",
    },
  ],
});
// 编辑弹窗字段
const editForm = reactive({});
// 元素ref
const gridRef = ref(); // 区域网格ref
const topSearchRef = ref(); // 顶部搜索区域ref
const addRef = ref(); // 新增弹窗ref,表单校验
const editRef = ref(); // 编辑弹窗ref,表单校验
const screenFormRef = ref(); // 搜索区ref元素
const gridCascaderRef = ref(); // 搜索区网格级联ref
const gridCascaderValue = ref(""); // 搜索区网格级联选中值

// 搜索区网格级联数据（与左侧树结构共用同一份数据）
const gridTreeOptions = computed(() => pageBasicsData.treeData);

onMounted(() => {
  fetchDistricts();
  // 表格行内按钮
  buttonsClickFun.data = {
    // 编辑
    edit: () => {
      if (editForm.scenesType == 0) {
        return $message.warning("场景属性为【卫生间】的场景不允许修改");
      }
      pageBasicsData.isEditDialog = true;
    },
    // 删除
    delete: () => {
      $messageBox
        .confirm("确定要删除此数据么？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          sceneManageService
            .delete({
              id: editForm.id,
              scenesLevel: editForm.scenesLevel,
            })
            .then((res) => {
              if (res.code == 0) {
                $message.success(res.data);
                fetchData();
              } else {
                $message.error(res.err);
              }
            });
        })
        .catch(() => {});
    },
  };
});

// #region watch定义start
// 设置表格高度
watch(
  () => topSearchRef.value,
  (val) => {
    let wHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    nextTick(() => {
      pageBasicsData.tableHeight = wHeight - val.clientHeight - 184;
    });
  }
);
// 站点变化清空其它查询条件
watch(
  () => pageBasicsData.screenForm.districtId,
  (val) => {
    if (val) {
      for (const key in pageBasicsData.screenForm) {
        if (key != "districtId") {
          pageBasicsData.screenForm[key] = "";
        }
      }
      pageBasicsData.screenForm.scenesLevel = 1;
      gridCascaderValue.value = "";
    }
  }
);
// 监听添加时所属站点change
watch(
  () => addForm.districtId,
  (val) => {
    addForm.gridSelect = [];
    fetchTree(val, true);
  }
);
// 监听添加时场景级别change
watch(
  () => addForm.scenes[0].scenesLevel,
  () => {
    if (addForm.scenes.length > 1) {
      addForm.scenes.splice(1, addForm.scenes.length - 1);
    }
  }
);
// #endregion watch定义end

// #region 函数定义start
// 上级场景change事件
const sceneChange = (i, e, list) => {
  list.forEach((item) => {
    if (item.id == e && addForm.scenes[i].scenesLevel > 1) {
      console.log(item);
      addForm.scenes[i].scenesType = item.scenesType;
    }
  });
};
// 场景级别change
const scenesLevelChange = (index, val) => {
  if (val > 1) {
    let parData = {
      districtId: addForm.districtId,
      gridSelect: gridHandleChange(),
    };
    fetchSuperiorScenes(parData);
  }
  addForm.scenes[index].superiorScenesId = "";
  addForm.scenes[index].scenesType = "";
};
// 场景项添加
const addSceneForm = () => {
  if (!addForm.gridSelect.length || addForm.scenes[0].scenesLevel == "") {
    return $message.error("请先选择区域网格和场景级别后再点击批量增加!");
  }
  let checkedScenesLevel = [];
  selectItems.value["scenesLevel"].map((item) => {
    if (item.key == addForm.scenes[0].scenesLevel) {
      checkedScenesLevel.push(item);
    }
  });
  addForm.scenes.push({
    superiorGridName: "",
    scenesLevel: checkedScenesLevel[0].key || "",
    superiorScenesId: "",
    name: "",
    qualityLevel: "",
    enableStatus: "",
    note: "",
    scenesType: "",
  });
};
// 场景项移除
const removeSceneForm = (item) => {
  if (addForm.scenes.length <= 1) return;
  const index = addForm.scenes.indexOf(item);
  if (index !== -1) {
    addForm.scenes.splice(index, 1);
  }
};

// 添加时区域网格change
const gridHandleChange = () => {
  let checkArr = gridRef.value.getCheckedNodes();
  let parArr = [];
  checkArr.forEach((item) => {
    parArr.push({
      gridId: item.value,
      gridLevel: item.level,
    });
  });
  let parData = {
    districtId: addForm.districtId,
    gridSelect: parArr,
  };
  if (parArr.length > 0 && addForm.scenes[0].scenesLevel) {
    fetchSuperiorScenes(parData);
  }
  return parArr;
};

const fetchTableAttr = (tableAttr) => {
  tableHeader.value = tableAttr;
};
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  if (enName == "add") {
    pageBasicsData.isAddDialog = true;
  }
  if (enName == "export") {
    sceneManageService.export({
      districtId: pageBasicsData.screenForm.districtId,
    });
  }
};

// 添加表单提交
const submitForm = () => {
  let params = {
    districtId: addForm.districtId,
    gridSelect: gridHandleChange(),
    scenes: addForm.scenes,
  };
  addRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          sceneManageService.add(params).then((res) => {
            if (res.code == 0) {
              $message.success("新建成功!");
              closeAddDialog();
              fetchData();
            } else {
              $message.error(res.err);
            }
          });
        })
        .catch(() => {});
    }
  });
};
// 编辑表单提交
const editSubmitForm = () => {
  editRef.value.validate((valid) => {
    if (valid) {
      return new Promise(() => {
        sceneManageService
          .update(editForm)
          .then((res) => {
            if (res.code == 0) {
              $message.success(res.data);
              closeEditDialog();
              fetchData();
            } else {
              $message.error(res.err);
            }
          })
          .catch(() => {});
      });
    }
  });
};
// 关闭添加弹窗
const closeAddDialog = () => {
  pageBasicsData.isAddDialog = false;
  addRef.value.resetFields();
  addForm.scenes = [
    {
      scenesLevel: 1,
      superiorScenesId: "",
      name: "",
      qualityLevel: "",
      enableStatus: "",
      note: "",
      scenesType: "",
    },
  ];
  pageBasicsData.superiorScenesList = [];
};
// 关闭编辑弹窗
const closeEditDialog = () => {
  pageBasicsData.isEditDialog = false;
  editRef.value.resetFields();
};
// 获取所属站点
const fetchDistricts = () => {
  return new Promise(() => {
    dropdownService.getDistrict().then(async (res) => {
      if (res.code == 0) {
        pageBasicsData.districtList = res.data;
        if (pageBasicsData.districtList?.length) {
          pageBasicsData.screenForm.districtId =
            pageBasicsData.districtList[0].id;
          fetchData();
          fetchTree();
        } else {
          $message.error("暂无站点信息,请配置站点!");
        }
      }
    });
  });
};
// 获取列表数据
const fetchData = () => {
  const { page, rows } = pageProps;
  return new Promise(() => {
    sceneManageService
      .pageList({
        page,
        rows,
        ...pageBasicsData.screenForm,
      })
      .then((res) => {
        if (res.code == 0) {
          pageBasicsData.loading = false;
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        } else {
          $message.error(res.err);
        }
      });
  });
};

// 上级场景下拉列表
const fetchSuperiorScenes = (data) => {
  return new Promise(() => {
    sceneManageService.oneScenesList(data).then(async (res) => {
      if (res.code == 0) {
        pageBasicsData.superiorScenesList = res.data;
      }
    });
  });
};
// 左侧树结构点击事件（保留供内部复用逻辑参考）
const nodeClick = ({ dom }) => {
  pageBasicsData.screenForm.gridLevel = dom.gridLevel;
  pageBasicsData.screenForm.gridId = dom.gridId;
  fetchData(true);
};
// 搜索区网格级联选择事件
const gridCascaderChange = (val) => {
  if (val) {
    const findNode = (list, gridId) => {
      for (const item of list) {
        if (item.gridId === gridId) return item;
        if (item.childNode && item.childNode.length) {
          const found = findNode(item.childNode, gridId);
          if (found) return found;
        }
      }
      return null;
    };
    const node = findNode(pageBasicsData.treeData, val);
    pageBasicsData.screenForm.gridLevel = node ? node.gridLevel : "";
    pageBasicsData.screenForm.gridId = val;
  } else {
    delete pageBasicsData.screenForm.gridLevel;
    delete pageBasicsData.screenForm.gridId;
  }
};
// 左侧树结构数据
const fetchTree = (id, isAdd) => {
  const { districtId } = pageBasicsData.screenForm;
  return new Promise(() => {
    dropdownService
      .gridTree({ districtId: id ? id : districtId })
      .then(async (res) => {
        if (res.code == 0) {
          if (!isAdd) {
            pageBasicsData.treeData = res.data.childNode;
          } else {
            pageBasicsData.addTreeData = res.data.childNode;
            setTreeData(pageBasicsData.addTreeData);
          }
        }
      });
  });
};
const setTreeData = (arr) => {
  arr.forEach((item) => {
    if (item.gridLevel == 1) {
      item.disabled = true;
    }
  });
};
//查询
const restSearch = () => {
  pageProps.page = 1;
  fetchData();
  fetchTree();
};
// 清空搜索
const clearScreen = () => {
  screenFormRef.value.resetFields();
  gridCascaderValue.value = "";
  delete pageBasicsData.screenForm.gridLevel;
  delete pageBasicsData.screenForm.gridId;
  pageBasicsData.screenForm.districtId = pageBasicsData.districtList[0].id;
  fetchData();
  fetchTree();
};

// 表格按钮
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    editForm[i] = row[i];
  }
  buttonsClickFun.data[$column.enName]();
};

const {
  tableData,
  rowButtons,
  pageProps,
  tableHeader,
  pageChange,
  buttonsClickFun,
  $message,
  $messageBox,
  selectItems,
} = templateHooks(fetchData);
// #endregion 函数定义end
</script>
<script>
export default {
  name: "SceneManage",
};
</script>
<style lang="scss" scoped>
.regional-grid {
  box-sizing: border-box;
  height: calc(100vh - var(--page-top-offset));
  .regional-grid-content {
    height: 100%;
    padding: var(--spacing-md);
    background-color: var(--color-bg-card);
    overflow: auto;
    .grid-right-search {
      padding: var(--spacing-md) var(--spacing-lg);
      display: flex;
      align-items: center;
    }
    .el-form {
      margin: 8px 0;
    }
  }
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

.dialog-item {
  width: 100%;
  display: flex;
  align-items: center;
  margin-left: 30px;
  .dialog-item-left {
    margin-right: 30px;
    div {
      margin-bottom: 30px;
    }
  }
  .dialog-item-right {
    .el-button {
      margin-bottom: 26px;
    }
  }
}
.el-select-dropdown__item.hover,
.el-select-dropdown__item:hover {
  background-color: #fff;
}
.generated {
  display: flex;
  .generated-left {
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 20px;
    border: 1px solid #dcdfe6;
  }
  .generated-right {
    margin-left: 20px;
    padding-top: 13%;
  }
}
.table-img {
  width: 90%;
}
</style>
