<template>
  <el-skeleton :rows="30" :loading="pageBasicsData.loading" />
  <!-- 场景对象管理 -->
  <div class="regional-grid" v-if="!pageBasicsData.loading">
    <!-- 顶部功能按钮 -->
    <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="objectIds">
              <div class="screen-item">
                <el-cascader
                  ref="screenObjectRef"
                  clearable
                  v-model="pageBasicsData.screenForm.objectIds"
                  :options="pageBasicsData.treeData[0].childrenNode"
                  :props="pageBasicsData.objectNameProps"
                  @change="screenObjectHandleChange"
                  @focus="
                    () => {
                      if (pageBasicsData.treeData[0].childrenNode.length <= 0) {
                        $message.warning(
                          '当前选择的所属站点暂无对象,请重新选择!'
                        );
                      }
                    }
                  "
                >
                  <template #default="{ data }">
                    <span>{{ data.name }}</span>
                  </template>
                </el-cascader>
              </div>
            </el-form-item>
            <el-form-item label="网格名称" prop="gridName">
              <div class="screen-item">
                <el-input
                  placeholder="请输入网格名称"
                  clearable
                  v-model="pageBasicsData.screenForm.gridName"
                ></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.key"
                    :value="item.value"
                    v-for="item in pageBasicsData.classifyLevelList"
                    :key="item.value"
                  ></el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="场景名称" prop="scenesName">
              <div class="screen-item">
                <el-input
                  placeholder="请输入场景名称"
                  clearable
                  v-model="pageBasicsData.screenForm.scenesName"
                ></el-input>
              </div>
            </el-form-item>
        </qu-search-area>
    </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="pageBasicsData.buttonList"
        @buttonClick="buttonClick"
      ></qu-table>
    </div>
  </div>

  <!-- 新建弹窗 -->
  <el-dialog
    v-model="pageBasicsData.isShowAddDialog"
    title="新建"
    width="600px"
    @close="closeAddDialog"
  >
    <el-form
      class="dialog-form"
      label-width="130px"
      ref="addRef"
      :model="addForm"
    >
      <el-form-item
        style="padding-top: 40px"
        label="所属站点"
        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="场景名称"
        prop="currentScenes"
        :rules="{
          required: true,
          message: '请选择场景名称',
          trigger: 'change',
        }"
      >
        <el-cascader
          style="width: 350px"
          ref="currentScenesRef"
          clearable
          v-model="addForm.currentScenes"
          :options="pageBasicsData.addSceneNameData[0].childNode"
          :show-all-levels="false"
          collapse-tags
          collapse-tags-tooltip
          :props="pageBasicsData.sceneNameProps"
          @change="sceneHandleChange"
          @focus="
            () => {
              if (pageBasicsData.addSceneNameData[0].childNode.length <= 0) {
                $message.warning('当前选择的所属站点暂无场景数据,请重新选择!');
              }
            }
          "
        >
          <template #default="{ data }">
            <span>{{ data.name }}</span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item
        label="对象名称"
        prop="objectIds"
        :rules="{
          required: true,
          message: '请选择对象名称',
          trigger: 'change',
        }"
      >
        <el-cascader
          style="width: 350px"
          ref="addObjectRef"
          clearable
          v-model="addForm.objectIds"
          :options="pageBasicsData.addTreeData[0].childrenNode"
          :props="pageBasicsData.objectNameProps"
          @change="addObjectHandleChange"
          @focus="
            () => {
              if (pageBasicsData.addTreeData[0].childrenNode.length <= 0) {
                $message.warning('当前选择的所属站点暂无对象数据,请重新选择!');
              }
            }
          "
        >
          <template #default="{ data }">
            <span>{{ data.name }}</span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item
        label="停/启用状态"
        prop="status"
        :rules="{
          required: true,
          message: '请选择停/启用状态',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="addForm.status"
        >
          <el-option
            :label="item.key"
            :value="item.value"
            v-for="item in pageBasicsData.statusList"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input
          v-model="addForm.memo"
          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="closeAddDialog">取消</el-button>
        <el-button style="width: 90px" type="primary" @click="submitForm"
          >提交</el-button
        >
      </span>
    </template>
  </el-dialog>

  <!-- 编辑弹窗 -->
  <el-dialog
    v-model="pageBasicsData.isShowEditDialog"
    title="编辑"
    width="600px"
    @close="closeEditDialog"
  >
    <el-form
      class="dialog-form"
      label-width="130px"
      ref="editRef"
      :model="editForm"
    >
      <el-form-item
        style="padding-top: 40px"
        label="所属站点"
        prop="districtId"
        :rules="{
          required: true,
          message: '请选择所属站点',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          :disabled="true"
          filterable
          placeholder="请选择所属站点"
          v-model="editForm.districtName"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        label="场景名称"
        prop="scenesName"
        :rules="{
          required: true,
          message: '请选择场景名称',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          clearable
          :disabled="true"
          filterable
          placeholder="请选择场景名称"
          v-model="editForm.scenesName"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        label="对象名称"
        prop="objectName"
        :rules="{
          required: true,
          message: '请选择对象名称',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          clearable
          :disabled="true"
          filterable
          placeholder="请选择对象名称"
          v-model="editForm.objectName"
        >
        </el-select>
      </el-form-item>
      <el-form-item
        label="停/启用状态"
        prop="status"
        :rules="{
          required: true,
          message: '请选择停/启用状态',
          trigger: 'change',
        }"
      >
        <el-select
          style="width: 350px"
          filterable
          clearable
          placeholder="请选择"
          v-model="editForm.status"
        >
          <el-option
            :label="item.key"
            :value="item.value"
            v-for="item in pageBasicsData.statusList"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="memo">
        <el-input
          v-model="editForm.memo"
          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 { sceneMatterManageService } from "@/ApiService/basicInfoService";
import { dropdownService } from "@/ApiService/dropdownService";

// 页面基础数据
const pageBasicsData = reactive({
  tableHeight: 200, //表格高度
  treeData: [{ childrenNode: [] }], // 左侧树结构数据
  addTreeData: [{ childNode: [] }], // 添加时树结构数据
  sceneNameData: [{ childNode: [] }], // 场景名称树结构数据
  addSceneNameData: [{ childNode: [] }], // 场景名称树结构数据
  loading: true, // 加载状态
  screenForm: {
    // 顶部搜索字段
    districtId: "",
    objectIds: "",
    gridName: "",
    scenesLevel: "",
    scenesName: "",
  },
  buttonList: [
    // 顶部按钮列表
    {
      cnName: "新建",
      enName: "add",
      theme: "success",
      icon: "plus",
    },
    {
      cnName: "导出",
      enName: "export",
      theme: "primary",
      icon: "top",
    },
  ],
  isShowAddDialog: false, //新增弹窗
  isShowEditDialog: false, //编辑弹窗
  districtList: [], // 所属站点列表
  classifyLevelList: [
    {
      key: "一级",
      value: 1,
    },
    {
      key: "二级",
      value: 2,
    },
  ],
  statusList: [
    {
      key: "停用",
      value: 0,
    },
    {
      key: "启用",
      value: 1,
    },
  ],
  sceneNameProps: {
    // 场景名称级联配置
    expandTrigger: "hover",
    value: "gridId",
    label: "name",
    children: "childNode",
    checkStrictly: true,
    multiple: true,
    disabled: "disable",
  },
  objectNameProps: {
    // 对象名称级联配置
    expandTrigger: "hover",
    value: "id",
    label: "name",
    children: "childrenNode",
    checkStrictly: true,
    multiple: true,
  },
});

// 新增弹窗字段
let addForm = reactive({
  districtId: "",
  scenes: [
    {
      id: "",
      level: "",
      name: "",
    },
  ],
  objectIds: [],
  status: "",
  memo: "",
});
// 编辑弹窗字段
const editForm = reactive({});

// 元素ref
const topSearchRef = ref(); //顶部搜索区域ref
const screenObjectRef = ref(); // 搜索区对象ref
const addObjectRef = ref(); // add对象ref
const addRef = ref(); // 新增弹窗ref,表单校验
const editRef = ref(); // 新增弹窗ref,表单校验
const screenFormRef = ref(); //搜索区ref元素
const currentScenesRef = ref(); //场景名称
const gridCascaderRef = ref(); // 网格级联ref
const gridCascaderValue = ref(''); // 网格级联选中值

// 网格级联选项数据（来自场景树）
const gridTreeOptions = computed(() => pageBasicsData.sceneNameData[0].childNode);

onMounted(() => {
  fetchDistricts();
  // 表格行内按钮
  buttonsClickFun.data = {
    // 编辑
    edit: () => {
      pageBasicsData.isShowEditDialog = true;
    },
    // 删除
    delete: () => {
      $messageBox
        .confirm("确定要删除此数据么？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          sceneMatterManageService
            .removeSceneObject({
              id: editForm.id,
            })
            .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(
  () => addForm.districtId,
  (val) => {
    if (val) {
      fetchObjectTree(val, true);
      fetchSceneTree(val, true);
    }
  }
);
watch(
  () => pageBasicsData.screenForm.districtId,
  () => {
    gridCascaderValue.value = '';
    pageBasicsData.screenForm.treeFlag = 0;
    pageBasicsData.screenForm.isscene = undefined;
    pageBasicsData.screenForm.level = undefined;
    pageBasicsData.screenForm.sceneId = undefined;
    pageBasicsData.screenForm.gridId = undefined;
  }
);
// #endregion watch定义end

// #region 函数定义start
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  if (enName == "add") {
    pageBasicsData.isShowAddDialog = true;
  }
  if (enName == "export") {
    const { page, rows } = pageProps;
    sceneMatterManageService.sceneObjectExport({
      page,
      rows,
      ...pageBasicsData.screenForm,
    });
  }
};

// 顶部搜索对象级联change事件
const screenObjectHandleChange = () => {
  let checkArr = screenObjectRef.value.getCheckedNodes();
  let screenObjectProps = [];
  checkArr.forEach((item) => {
    screenObjectProps.push(item.value);
  });
  return screenObjectProps;
};
// 场景级联change事件
const sceneHandleChange = () => {
  let checkArr = currentScenesRef.value.getCheckedNodes();
  let lastArr = [];
  checkArr.forEach((item) => {
    lastArr.push({
      id: item.data.sceneId,
      name: item.data.name,
      level: item.data.level,
    });
  });
  addForm.scenes = lastArr;
};
// 对象级联change事件
const addObjectHandleChange = () => {
  let checkArr = addObjectRef.value.getCheckedNodes();
  let objectProps = [];
  checkArr.forEach((item) => {
    objectProps.push(item.value);
  });
  return objectProps;
};

// 添加表单提交
const submitForm = () => {
  addRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          // delete addForm.currentScenes;
          addForm.objectIds = addObjectHandleChange();
          sceneMatterManageService.setSceneObject(addForm).then((res) => {
            if (res.code == 0) {
              $message.success(res.data);
              closeAddDialog();
              fetchData();
            } else {
              $message.error(res.err);
            }
          });
        });
    }
  });
};
// 编辑表单提交
const editSubmitForm = () => {
  const { id, status, memo } = editForm;
  editRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          sceneMatterManageService
            .updateSceneObject({ id, status, memo })
            .then((res) => {
              if (res.code == 0) {
                $message.success(res.data);
                closeEditDialog();
                fetchData();
              } else {
                $message.error(res.err);
              }
            });
        });
    }
  });
};
// 关闭添加弹窗事件
const closeAddDialog = () => {
  pageBasicsData.isShowAddDialog = false;
  addRef.value.resetFields();
};
// 关闭编辑弹窗事件
const closeEditDialog = () => {
  pageBasicsData.isShowEditDialog = false;
  editRef.value.resetFields();
};
// 获取所属站点
const fetchDistricts = () => {
  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();
        fetchObjectTree();
        fetchSceneTree();
      } else {
        $message.error("暂无站点信息,请配置站点!");
      }
    }
  });
};

// 获取列表数据
const fetchData = () => {
  const { page, rows } = pageProps;
  if (pageBasicsData.screenForm.objectIds) {
    objectIds = screenObjectHandleChange();
  }
  sceneMatterManageService
    .sceneObjectPageList({
      page,
      rows,
      ...pageBasicsData.screenForm,
    })
    .then(async (res) => {
      if (res.code == 0) {
        pageBasicsData.loading = false;
        tableData.value = res.data.rows;
        pageProps.records = res.data.records;
      }
    });
};

// 左侧场景树结构点击事件（保留以兼容潜在调用）
const nodeClick = ({ dom }) => {
  pageBasicsData.screenForm.treeFlag = 1;
  pageBasicsData.screenForm.isscene = dom.isscene;
  pageBasicsData.screenForm.level = dom.level;
  pageBasicsData.screenForm.sceneId = dom.sceneId;
  pageBasicsData.screenForm.gridId = dom.gridId;
  fetchData();
};
// 网格级联选择change事件
const gridCascaderChange = (val) => {
  if (val) {
    const checkedNodes = gridCascaderRef.value.getCheckedNodes();
    const node = checkedNodes && checkedNodes[0] ? checkedNodes[0].data : null;
    pageBasicsData.screenForm.treeFlag = 1;
    pageBasicsData.screenForm.isscene = node ? node.isscene : undefined;
    pageBasicsData.screenForm.level = node ? node.level : undefined;
    pageBasicsData.screenForm.sceneId = node ? node.sceneId : undefined;
    pageBasicsData.screenForm.gridId = val;
  } else {
    pageBasicsData.screenForm.treeFlag = 0;
    pageBasicsData.screenForm.isscene = undefined;
    pageBasicsData.screenForm.level = undefined;
    pageBasicsData.screenForm.sceneId = undefined;
    pageBasicsData.screenForm.gridId = undefined;
  }
};
// 左侧场景树数据
const fetchSceneTree = (id, isAdd) => {
  const { districtId } = pageBasicsData.screenForm;
  dropdownService
    .gridSceneTree({ districtId: (id ||= districtId) })
    .then(async (res) => {
      if (res.code == 0) {
        let newData = [];
        newData.push(res.data);
        if (!isAdd) {
          pageBasicsData.sceneNameData = newData;
        } else {
          pageBasicsData.addSceneNameData = newData;
        }
      }
    });
};

// 对象树数据
const fetchObjectTree = (id, isAdd) => {
  const { districtId } = pageBasicsData.screenForm;
  dropdownService
    .getObjectTree({ districtId: id ? id : districtId })
    .then(async (res) => {
      if (res.code == 0) {
        let newData = [];
        newData.push(res.data);
        if (!isAdd) {
          pageBasicsData.treeData = newData;
        } else {
          pageBasicsData.addTreeData = newData;
        }
      }
    });
};
//查询
const restSearch = () => {
  pageProps.page = 1;
  fetchData();
  fetchSceneTree();
  fetchObjectTree();
};
// 清空搜索
const clearScreen = () => {
  screenFormRef.value.resetFields();
  gridCascaderValue.value = '';
  pageBasicsData.screenForm.treeFlag = 0;
  pageBasicsData.screenForm.isscene = undefined;
  pageBasicsData.screenForm.level = undefined;
  pageBasicsData.screenForm.sceneId = undefined;
  pageBasicsData.screenForm.gridId = undefined;
  fetchData();
  fetchSceneTree();
};
// 自定义表格头
const fetchTableAttr = (tableAttr) => {
  tableHeader.value = tableAttr;
};
// 表格按钮
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,
} = templateHooks(fetchData);
// #endregion 函数定义 end
</script>
<script>
export default {
  name: "SceneObjectManage",
};
</script>
<style lang="scss" scoped>
.regional-grid {
  height: calc(100vh - var(--page-top-offset));
  box-sizing: border-box;
  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;
    }
  }
}
.generated {
  display: flex;
  .generated-left {
    padding-right: 60px;
    padding-top: 20px;
    margin-bottom: 20px;
    border: 1px solid #dcdfe6;
  }
  .generated-right {
    margin-left: 20px;
    padding-top: 13%;
  }
}
</style>
