<template>
  <div class="departmentTree-box" :style="{ width: width, height: '100%' }">
    <div class="depar_foot">
      <div class='titicon'>
        <img :src="getImgUrl('img/zzjgli.png')" /><span>：组织机构</span>
        <img :src="getImgUrl('img/csicon.png')" /><span>：场所</span>
        <img :src="getImgUrl('img/cqicon.png')" /><span>：场区</span>
        <img :src="getImgUrl('img/jzwicon.png')" /><span>：建筑物</span>
        <img :src="getImgUrl('img/lcicon.png')" /><span>：楼层</span>
        <img :src="getImgUrl('img/bwicon.png')" /><span>：部位</span>
      </div>
      <el-tree ref="treeRef" class="filter-tree" :props="endProps" node-key="id" :load="loadNode" lazy
        :default-expanded-keys="treemrData" @node-collapse="handleNodeCollapse" @node-click="nodeClick"
        :filter-node-method="filterNode" :data="treeData">
        <template #default="scoped">
          <div class="menuItem" @contextmenu.prevent="onContextmenu(scoped.data, $event, scoped.node)">
            <img v-if='!scoped.data.siteid' :src="getImgUrl('img/zzjgli.png')" style='cursor:pointer' />
            <img v-if='scoped.data.type == "01" && scoped.data.siteid' :src="getImgUrl('img/csicon.png')"
              style='cursor:pointer' />
            <img v-if='scoped.data.type == "02" && scoped.data.siteid' :src="getImgUrl('img/csicon.png')"
              style='cursor:pointer' />
            <img v-if='scoped.data.type == "03" && scoped.data.jzwlx == "1" && scoped.data.siteid'
              :src="getImgUrl('img/cqicon.png')" style='cursor:pointer' />
            <img v-if='scoped.data.type == "03" && scoped.data.jzwlx != "1" && scoped.data.siteid'
              :src="getImgUrl('img/jzwicon.png')" style='cursor:pointer' />
            <img v-if='scoped.data.type == "04" && scoped.data.siteid' :src="getImgUrl('img/lcicon.png')"
              style='cursor:pointer' />
            <img v-if='scoped.data.type == "05" && scoped.data.siteid' :src="getImgUrl('img/bwicon.png')"
              style='cursor:pointer' />
            <span class="center_text"> {{ scoped.data.name }}</span>
            <el-icon v-if="scoped.data.hasChildren">
              <CaretRight />
            </el-icon>
          </div>
        </template>
      </el-tree>
    </div>
    <Contextmenu ref="contextmenuRef" :items="contextmenuItems.list" @contextmenuItemClick="onContextmenuItem"
      :showmenu="showmenu" />
    <!-- 场所 -->
    <div v-if="csdialogShow" class="dialog-box">
      <PlaceDialog :formData="formData" @saveSuccess="saveSuccess" :type="'1'" />
    </div>

    <!-- 建筑物 -->
    <div v-if="dialogjzw" class="dialog-box">
      <buildDialog :formData="formData" @saveSuccess="saveSuccess" :type="'1'" />
    </div>

    <!-- 楼层 -->
    <div v-if="dialoglc" class="dialog-box">
      <floorDialog :formData="formData" @saveSuccess="saveSuccess" :type="'1'" />
    </div>

    <!-- 部位 -->
    <div v-if="dialogbwshow" class="dialog-box">
      <positionDialog :formData="formData" @saveSuccess="saveSuccess" :type="'1'" />
    </div>
    <!-- 部位 -->
    <div v-if="isShowsbpz" class="dialog-box">
      <sbpz :obj="sbpzObj" @saveSuccess="saveSuccess" />
    </div>

  </div>
</template>

<script setup>
import { getImgUrl } from "@/utils/tools.js"
import { COMPONENT_WIDTH } from "@/constant";
import { ElMessage, ElMessageBox } from "element-plus";
import Contextmenu from "@/components/contextmenu/index.vue";
import PlaceDialog from "@/components/dialog/placeindex.vue";
import buildDialog from "@/components/dialog/buildindex.vue";
import floorDialog from "@/components/dialog/floorindex.vue";
import positionDialog from "@/components/dialog/positionindex.vue";
import { ref, defineProps, defineEmits, reactive, onMounted } from "vue";
import { exportXlsx, downloadImg } from "@/excel/Export2Excel.js";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { useStore } from "vuex";
import sbpz from "@/views/integrationCenter/sbpz/index.vue"

const store = useStore();
const props = defineProps({
  //获取组件传值
  placeholder: {
    default: "请选择",
    type: String
  },
  multiple: {
    default: false,
    type: Boolean
  },
  showfunction: {
    default: true,
    type: Boolean
  },
  filterable: {
    default: true,
    type: Boolean
  },
  modelValue: {
    type: String
  },
  width: {
    default: COMPONENT_WIDTH,
    type: String
  }
});
/** 显示设备配置 */
const isShowsbpz = ref(false)
/** 设备配置参数 */
const sbpzObj = ref({})
const csdialogShow = ref(false);
const dialogbwshow = ref(false)
const dialogjzw = ref(false);
const dialoglc = ref(false);
const dialogbw = ref(false);
const showmenu = ref(false);
const formData = ref({
  title: ""
});
const listQuery = ref({
  parentid: "",
  type: '',
});
// 自定义右键菜单的功能列表
const contextmenuItems = reactive({
  list: []
});
const contextmenuRef = ref();
const treeRef = ref(null);
const node_had = ref([]);
const resolve_had = ref([]);
const treemrData = ref([]);
const treeDataObj = ref({});
// 每次展开记忆点开的那个树
let saveData = ref([])
const emits = defineEmits(["update:modelValue", "getdeptId", "getdeptData"]);
onMounted(() => {
  saveData.value = store.state.user.treeList
});
// saveData.value = store.state.treeList
//获取部门数据
function getTreeData() {
  getApi(listQuery.value, "/mosty-jcgl/site/querySceneTree").then((res) => {
    if (res.length == 1) {
      res.forEach((element) => {
        treemrData.value.push(element.id);
        treeDataObj.value[element?.id] = element;
        emits("getdeptData", element);
      });
    }
    for (let i = 0; i < res.length; i++) {
      res[i].leaf = !res[i].hasChildren;
    }
    if (res.length > 0) treeData.value = res;
    saveData.value.map((item, index) => {
      if (index > 0) {
        treemrData.value.push(item.id)
        treeDataObj.value[item.id] = item;
      }
    })
  });
}

const endProps = {
  children: "childDeptList",
  value: "id",
  label: "name",
  isLeaf: "leaf"
};
const treeData = ref([]);
//懒加载方法
async function loadNode(node, resolve) {
  listQuery.value.parentid = node.data.id;
  listQuery.value.type = node.data.type;
  if (node.level === 0) {
    node_had.value = node;
    resolve_had.value = resolve;
    getTreeData();
  }
  if (node.level >= 1) {
    saveData.value.push({ name: node.data.name, siteid: node.data.siteid, id: node.data.id })
    store.commit("user/setTreeList", saveData.value);
    getApi(listQuery.value, "/mosty-jcgl/site/querySceneTree").then(
      (res) => {
        for (let i = 0; i < res.length; i++) {
          res[i].leaf = !res[i].hasChildren;
        }
        resolve(res);
      }
    );
  }
}
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.includes(value);
};
const handleNodeCollapse = (nodeData, node) => {
  if (saveData.value.find(v => v.id == nodeData.id)) {
    saveData.value.map((item, index) => {
      if (item.id == nodeData.id) {
        saveData.value.splice(index, 1)
      }
    })
  }
}
const nodeClick = (node) => {
  showmenu.value = true;
  const id = node.id;
  emits("update:modelValue", id);
  emits("getdeptId", id);
  emits("getdeptData", node);
};
// 类型,01增加场所，02增减建筑物，03，增加楼层，04增加部位
const onContextmenu = (menu, el, node) => {
  const parentData = node?.parent?.data || {};
  let level = node.parent && node.parent.childNodes && node.parent.childNodes.length ? node.parent.childNodes.length : 0;
  showmenu.value = false;
  switch (menu.type) {
    case "01":
      contextmenuItems.list = [
        { name: "addGroup", label: "新增场所", icon: "Plus" },
        { name: "dccsewm", label: "批量导出场所二维码", icon: "Downloads" },
        { name: "dcbwewm", label: "批量导出部位二维码", icon: "Downloads" },
      ];
      break;
    case "02":
      contextmenuItems.list = [
        { name: "addGroup", label: "新增建筑物", icon: "Plus" },
        { name: "addcqGroup", label: "新增场区", icon: "Plus" },
        { name: "edit", label: "修改场所", icon: "Edit" },
        // { name: "sbsssdst", label: "设备实施撒点上图", icon: "Location" }, // 待弄完在放开，避免打包进去
        { name: "delete", label: "删除场所", icon: "Delete" },
        { name: "up", label: "上移", icon: "CaretTop" },
        { name: "down", label: "下移", icon: "CaretBottom" },
        { name: "dcbwewm", label: "批量导出部位二维码", icon: "Downloads" },
      ];
      break;
    case "03":
      //判断是否为场区1：是场区（场区只能新增部位）
      if (node.data.jzwlx == '1') {
        contextmenuItems.list = [
          { name: "addGroup", label: "新增场区部位", icon: "Plus" },
          { name: "edit", label: "修改场区", icon: "Edit" },
          { name: "delete", label: "删除场区", icon: "Delete" },
          { name: "up", label: "上移", icon: "CaretTop" },
          { name: "down", label: "下移", icon: "CaretBottom" }
        ];
      } else {
        contextmenuItems.list = [
          { name: "addGroup", label: "新增楼层", icon: "Plus" },
          { name: "edit", label: "修改建筑物", icon: "Edit" },
          // { name: "sbsssdst", label: "设备实施撒点上图", icon: "Location" }, // // 待弄完在放开，避免打包进去
          { name: "delete", label: "删除建筑物", icon: "Delete" },
          { name: "up", label: "上移", icon: "CaretTop" },
          { name: "down", label: "下移", icon: "CaretBottom" },

        ];
      }

      break;
    case "04":
      contextmenuItems.list = [
        { name: "addGroup", label: "新增部位", icon: "Plus" },
        { name: "edit", label: "修改楼层", icon: "Edit" },
        // { name: "sbsssdst", label: "设备实施撒点上图", icon: "Location" }, // // 待弄完在放开，避免打包进去
        { name: "delete", label: "删除楼层", icon: "Delete" },
        { name: "up", label: "上移", icon: "CaretTop" },
        { name: "down", label: "下移", icon: "CaretBottom" }
      ];
      break;
    case "05":
      if (node.data.jzwlx == '1') {
        contextmenuItems.list = [
          { name: "edit", label: "修改场区部位", icon: "Edit" },
          { name: "delete", label: "删除部位", icon: "Delete" },
          { name: "bwup", label: "置顶", icon: "Upload" },
          { name: "bwdown", label: "置底", icon: "Download" },
          { name: "up", label: "上移", icon: "CaretTop" },
          { name: "down", label: "下移", icon: "CaretBottom" }
        ];
      } else {
        contextmenuItems.list = [
          { name: "edit", label: "修改部位", icon: "Edit" },
          { name: "delete", label: "删除部位", icon: "Delete" },
          { name: "bwup", label: "置顶", icon: "Upload" },
          { name: "bwdown", label: "置底", icon: "Download" },
          { name: "up", label: "上移", icon: "CaretTop" },
          { name: "down", label: "下移", icon: "CaretBottom" }
        ];
      }

  }
  // 右键菜单的位置
  const { clientX, clientY } = el;
  contextmenuRef.value.onShowContextmenu(menu, {
    x: clientX,
    y: clientY
  }, parentData);
};
// 菜单的每个具体功能
const onContextmenuItem = (item, parentData) => {
  const { name, menu } = item;
  switch (name) {
    case "addGroup":
      formData.value = {}
      formData.value.title = contextmenuItems.list[0].label;
      formData.value.saveBtnShow = true
      if (menu.type == "01") {
        formData.value.orgid = menu.id;
        formData.value.orgname = menu.name;
        if (menu.departmentlevel == "10") {
          formData.value.departmentlevel = "10";
          formData.value.orgidSzgs = null;
          formData.value.orgidXgs = null;
        } else if (menu.departmentlevel == "20") {
          formData.value.departmentlevel = "20";
          formData.value.orgidSzgs = menu.id;
          formData.value.orgidXgs = null;
        } else if (menu.departmentlevel == "30") {
          formData.value.orgidSzgs = null;
          formData.value.orgidXgs = menu.id;
          formData.value.departmentlevel = "30";
        } else if (menu.departmentlevel == "40") {
          formData.value.orgidSzgs = null;
          formData.value.orgidXgs = null;
          formData.value.departmentlevel = "40";
        }
        // formData.value.deptname = getItem("deptId").ssbmmc;
        // formData.value.deptid = getItem("deptId").ssbmid;
        csdialogShow.value = true;
      } else if (menu.type == "02") {
        formData.value.siteid = menu.id;
        formData.value.sitename = menu.name;
        formData.value.publicarea = '2'
        formData.value.saveBtnShow = true
        dialogjzw.value = true;
      } else if (menu.type == "03") {
        // 查询场所信息
        getApi({}, "/mosty-jcgl/site/querySceneSiteById?id=" + menu.siteid).then((res) => {
          formData.value.siteid = res.id;
          formData.value.sitename = res.placename;
          formData.value.buildingid = menu.id;
          formData.value.buildingname = menu.name;
          formData.value.saveBtnShow = true
          if (menu.jzwlx == '1') {
            formData.value.type = 'cq';
            formData.value.publicarea = '1';
            dialogbwshow.value = true;
          } else {
            dialoglc.value = true;
          }
        });
      } else if (menu.type == "04") {
        // 查询场所信息
        getApi({}, "/mosty-jcgl/building/querySceneBuildingsById?id=" + menu.buildingid).then((res) => {
          formData.value.siteid = res.siteid;
          formData.value.sitename = res.sitename;
          formData.value.buildingid = res.id;
          formData.value.buildingname = res.buildingname;
          formData.value.floorid = menu.id;
          formData.value.floorname = menu.name;
          formData.value.type = 'cgl - bw';
          formData.value.saveBtnShow = true
          dialogbwshow.value = true;
        })
      }
      break;
    case "addcqGroup":
      formData.value.title = '新增场区';
      formData.value.siteid = menu.id;
      formData.value.sitename = menu.name;
      formData.value.publicarea = '1';
      formData.value.saveBtnShow = true
      dialogjzw.value = true;
      break;
    case "edit":
      getxqData(menu, parentData);
      break;
    case "delete":
      deleteMenu(menu);
      break;
    case "up":
      _changeOrderno(menu, "1", null);
      break;
    case "down":
      _changeOrderno(menu, "2", null);
      break;
    case "bwup":
      _changebw(menu, "1", '1');//置顶
      break;
    case "bwdown":
      _changebw(menu, "2", '2');
      break;
    case "dccsewm":
      _changeewm(menu, '01');
      break;
    case "dcbwewm":
      _changeewm(menu, '02');
      break;
    case "sbsssdst":
      _changeSbsssdst(menu, parentData);
      break;
  }
};
// 新增成功
const saveSuccess = () => {
  listQuery.value.parentid = '';
  listQuery.value.type = '';
  formData.value = {};
  csdialogShow.value = false
  dialogjzw.value = false;
  dialoglc.value = false;
  dialogbwshow.value = false;
  getTreeData();
};
// 菜单更换位置
const _changeOrderno = (menu, type) => {
  if (menu.type == "02") {
    postApi({ id: menu.id, orderno: type }, "/mosty-jcgl/site/updateSceneSiteOrderno").then(() => {
      ElMessage.success("操作成功");
      saveSuccess();
    });
  } else if (menu.type == "03") {
    postApi({ id: menu.id, orderno: type }, "/mosty-jcgl/building/updateSceneBuildingsOrderno").then(() => {
      ElMessage.success("操作成功");
      saveSuccess();
    });
  } else if (menu.type == "04") {
    postApi({ id: menu.id, orderno: type }, "/mosty-jcgl/floor/updateSceneFloorOrderno").then(() => {
      ElMessage.success("操作成功");
      saveSuccess();
    });
  } else if (menu.type == "05") {
    postApi({ id: menu.id, orderno: type }, "/mosty-jcgl/part/updateScenePartOrderno").then(() => {
      ElMessage.success("操作成功");
      saveSuccess();
    });
  }
};
function _changebw(menu, orderno, type) {
  postApi({ id: menu.id, orderno: type ? null : orderno, type: type }, "/mosty-jcgl/part/updateTopOrBottom").then(() => {
    ElMessage.success("操作成功");
    saveSuccess();
  });
}
//导出二维码
function _changeewm(menu, type) {
  let orgid = ''
  let siteid = ''
  let url = ''
  if (type == '01') {
    orgid = menu.id
    siteid = null
    url = '/mosty-api/mosty-jcgl/common/exportQrcodeZip?type=' + type + '&orgid=' + orgid
    onloadewm1(url, '场所二维码')
  } else {
    orgid = null
    siteid = menu.siteid ? menu.siteid : menu.id
    url = '/mosty-api/mosty-jcgl/common/exportQrcodeZip?type=' + type + '&siteid=' + siteid
    onloadewm1(url, '部位二维码')
  }

}
/**设备实施撒点上图
 * @param {Object} menu 菜单数据 buildingid floorid siteid partid sitetype departmentlevel
 * @param {Object} parentData 父级数据
 */
function _changeSbsssdst(menu, parentData) {

  console.log('parentData: ', parentData);
  console.log('menu: ', menu);
  sbpzObj.value = menu
  isShowsbpz.value = true
}
function onloadewm1(url, filename) {
  var a = document.createElement('a');      // 创建一个a节点插入的document
  var event = new MouseEvent('click')          // 模拟鼠标click点击事件
  a.download = filename;                  // 设置a节点的download属性值
  a.href = url;                                     // 将图片的src赋值给a节点的href
  a.dispatchEvent(event)
  a.remove(); // 下载之后把创建的元素删除
}
//详情
const getxqData = (menu, parentData) => {
  let parenObj = treeDataObj.value[parentData.id] || {}
  formData.value.showMode += "";
  formData.value.menuType += "";
  if (menu.type == "02") {
    getApi({ id: menu.id }, "/mosty-jcgl/site/querySceneSiteById").then((res) => {
      if (res) {
        // 编辑回显的所属部门id 和父级id不一致，使用父级的id
        if (parenObj.id && parenObj.id != res.orgid) {
          res.orgid = parenObj.id
          res.orgname = parenObj.name
        }
        formData.value = res;
        formData.value.title = "修改场所";
        formData.value.saveBtnShow = true
        csdialogShow.value = true;
      }

    }
    );
  } else if (menu.type == "03") {
    getApi({ id: menu.id }, "/mosty-jcgl/building/querySceneBuildingsById").then((res) => {
      if (res) {
        formData.value = res;
        if (formData.value.publicarea == '1') {
          formData.value.type = 'cq'
          formData.value.title = "修改场区";
        } else {
          formData.value.title = "修改建筑物";
        }
        formData.value.saveBtnShow = true
        dialogjzw.value = true;
      }

    });
  } else if (menu.type == "04") {
    getApi({ id: menu.id }, "/mosty-jcgl/floor/querySceneFloorById").then((res) => {
      if (res) {
        formData.value = res;
        formData.value.title = "修改楼层";
        formData.value.saveBtnShow = true
        dialoglc.value = true;
      }

    }
    );
  } else if (menu.type == "05") {
    getApi({ id: menu.id }, "/mosty-jcgl/part/queryScenePartById").then((res) => {
      if (res) {
        formData.value = res;
        //判断是否为场区
        if (res.sfcq == '1') {
          res.type = 'cq'
          formData.value.title = "修改场区部位";
          formData.value.publicarea = "1";
        } else {
          res.type = 'cgl-bw'
          formData.value.title = "修改建筑物部位";
        }
        formData.value.partname = res.qtmc ? res.qtmc : res.partname;
        formData.value.checktype = res.checktype
        formData.value.qtmc = res.qtmc
        formData.value.saveBtnShow = true
        dialogbwshow.value = true;
      }

    }
    );
  }
};



// 删除菜单数据
const deleteMenu = (menu) => {
  if (menu.type == "02") {
    // 场所删除
    ElMessageBox.confirm("确定删除该场所数据?", "删除场所").then(() => {
      getApi({ id: menu.id }, `/mosty-jcgl/site/deleteSceneSiteOne`).then(() => {
        ElMessage.success("删除成功");
        saveSuccess();
      }
      );
    });
  }
  if (menu.type == "03") {
    // 建筑物
    ElMessageBox.confirm("确定删除该建筑物数据?", "删除建筑物").then(() => {
      getApi(
        { id: menu.id },
        `/mosty-jcgl/building/deleteSceneBuildingsOne`
      ).then((res) => {
        ElMessage.success("删除成功");
        saveSuccess();
      });
    });
  }
  if (menu.type == "04") {
    // 楼层
    ElMessageBox.confirm("确定删除该楼层数据?", "删除楼层").then(() => {
      getApi({ id: menu.id }, `/mosty-jcgl/floor/deleteSceneFloorOne`).then(
        (res) => {
          ElMessage.success("删除成功");
          saveSuccess();
        }
      );
    });
  }
  if (menu.type == "05") {
    // 部位
    ElMessageBox.confirm("确定删除该部位数据?", "删除部位").then(() => {
      getApi({ id: menu.id }, `/mosty-jcgl/part/deleteScenePartOne`).then(
        (res) => {
          ElMessage.success("删除成功");
          saveSuccess();
        }
      );
    });
    // //判断是否能删除部位
    // getApi({ id: menu.id }, '/mosty-jcgl/part/getSbss').then(res => {
    //   if (res === true) {
    //     ElMessageBox.confirm("确定删除该部位数据?", "删除部位").then(() => {
    //       getApi({ id: menu.id }, `/mosty-jcgl/part/deleteScenePartOne`).then(
    //         (res) => {
    //           ElMessage.success("删除成功");
    //           saveSuccess();
    //         }
    //       );
    //     });
    //   } else {
    //     ElMessage.warning("该部位下还存在设备设施，请先删除该部位下的设备设施才能删除该部位");
    //   }
    // })

  }
};
</script>

<style lang="scss" scoped>
.titicon {
  >span {
    color: #000;
    margin-right: 30px;
    margin-bottom: 10px;
  }
}

.menu {
  padding: 10px 0;
  overflow-y: scroll;
}

.menuItem {
  width: 100%;

  .left_icon {
    margin: 0 10px;
    font-size: 18px;
  }

  .center_text {
    font-size: 15px;
  }
}

::v-deep .el-tree-node__content {
  .el-tree-node__expand-icon {
    display: none;
  }
}

.depar_hear {
  height: 32px;
}

.depar_foot {
  // height: calc(100% - 8px);
  height: 70vh;
  overflow: overlay;
  padding: 0 10px;
  // width: 380px;
}

.departmentTree-box {
  height: 80vh;
  // overflow-y: scroll;
}
</style>
