<script lang="ts" setup>
import {ref, onMounted,watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage,ElMessageBox } from 'element-plus-secondary'
import { useI18n } from '@/hooks/web/useI18n'
import { publicTree } from '@/utils/validate';
import { moduleList,moduleAdd,moduleUpdate,moduleDel,moduleCopy } from '@/api/application/module'
const emit = defineEmits(['handleNodeClick'])
const { t } = useI18n()
const router = useRouter()
const props = defineProps({
  projectInfo: {
    type: String,
    default: ''
  }
})
const typeList:any = ref([{
  code:'01',
  name:'登录页面'
},{
  code:'02',
  name:'主框架页面'
},{
  code:'03',
  name:'GIS大屏页面'
},{
  code:'0301',
  name:'数据看板页面'
},{
  code:'04',
  name:'二级弹窗页面'
},{
  code:'05',
  name:'数据填报页面'
},{
  code:'06',
  name:'文档资源页面'
},{
  code:'09',
  name:'自定义页面'
}])
const popupType:any = ref(0)
const isSwitch =ref(false)
const treeloading = ref(false) // 树加载中
const keywords =ref("") // 关键字
const projectInfo:any=ref({}) // 项目信息
const title =ref("目录") // 新建目录标题
const isDialog =ref(false) // 新建目录弹窗
const isTreeDrag =ref(false)
const dataInfo:any =ref({
  pid: '',
  level: '',
  type: '',
  nodeType: '',
  name:'',
  appId:''
})
const treeData:any=ref([])// 树数据
const defaultProps =  { label: "name" }

watch(() => props.projectInfo, val => { // 初始化数据
  projectInfo.value = val
  getInit()
})
onMounted(()=>{

  const canvas_style_data= {"width":1920,"height":1080,"refreshViewEnable":false,"refreshViewLoading":false,"refreshUnit":"minute","refreshTime":5,"scale":60,"scaleWidth":100,"scaleHeight":100,"backgroundColorSelect":false,"backgroundImageEnable":true,"backgroundType":"backgroundColor","background":"/static-resource/7127292608094670848.png","openCommonStyle":true,"opacity":1,"fontSize":14,"themeId":"10001","color":"#000000","backgroundColor":"rgba(245, 246, 247, 1)","dashboard":{"gap":"yes","gapSize":5,"resultMode":"all","resultCount":1000,"themeColor":"light","mobileSetting":{"customSetting":false,"imageUrl":null,"backgroundType":"image","color":"#000"}},"component":{"chartTitle":{"show":true,"fontSize":"18","hPosition":"left","vPosition":"top","isItalic":false,"isBolder":true,"remarkShow":false,"remark":"","fontFamily":"Microsoft YaHei","letterSpace":"0","fontShadow":false,"color":"#000000","remarkBackgroundColor":"#ffffff","modifyName":"color"},"chartColor":{"basicStyle":{"colorScheme":"default","colors":["#1E90FF","#90EE90","#00CED1","#E2BD84","#7A90E0","#3BA272","#2BE7FF","#0A8ADA","#FFD700"],"alpha":100,"gradient":true,"mapStyle":"normal","areaBaseColor":"#FFFFFF","areaBorderColor":"#303133","gaugeStyle":"default","tableBorderColor":"#E6E7E4","tableScrollBarColor":"#00000024"},"misc":{"mapLineGradient":false,"mapLineSourceColor":"#146C94","mapLineTargetColor":"#576CBC","nameFontColor":"#000000","valueFontColor":"#5470c6"},"tableHeader":{"tableHeaderBgColor":"#1E90FF","tableHeaderFontColor":"#000000"},"tableCell":{"tableItemBgColor":"#FFFFFF","tableFontColor":"#000000"},"modifyName":"gradient"},"chartCommonStyle":{"backgroundColorSelect":true,"backgroundImageEnable":false,"backgroundType":"innerImage","innerImage":"board/board_1.svg","outerImage":null,"innerPadding":12,"borderRadius":8,"backgroundColor":"rgba(255, 255, 255, 1)","innerImageColor":"rgba(16, 148, 229,1)"},"filterStyle":{"layout":"horizontal","titleLayout":"left","labelColor":"#1F2329","titleColor":"#1F2329","color":"#1f2329","borderColor":"#BBBFC4","text":"#1F2329","bgColor":"#FFFFFF"},"tabStyle":{"headPosition":"left","headFontColor":"#000000","headFontActiveColor":"#000000","headBorderColor":"#ffffff","headBorderActiveColor":"#ffffff"}}}
 
 
  projectInfo.value = props.projectInfo
})
function getInit() { // 初始化
  let params = {appId:projectInfo.value.id}
  moduleList(params).then(res => {
    treeData.value = publicTree(res.data.data,"")
  })
}
function addClic(name:any,level:any,pid:any){ // 新建目录、模块
  dataInfo.value={
    appId:projectInfo.value.id,
    pid: pid,
    level: level,
    nodeType: "",
    name:'',
    type:'',
  }
  
  if(name == '目录'){
    dataInfo.value.nodeType = '01'
  }else{
    dataInfo.value.nodeType = '02'
  }
  title.value = '新建' + name


  isSwitch.value = false
  isDialog.value=true
  
}
function handleDatasetName(){  // 关键字搜索

}
const handleNodeClick = (data: any) => { // 树节点点击
  if(data.node_type == '02'){
    emit('handleNodeClick', data)
  }else{
    emit('handleNodeClick', {})
  }
}
function moreClic(event:any ,data:any){ // 更多操作
  let element = document.getElementById("drag_main_area")
  if(element !=null){
    const x = event.clientX;  // 水平坐标（相对于元素边界）
    const y = event.clientY;  // 垂直坐标（相对于元素边界）
    element.style.left = x + 10 + 'px';
    element.style.top = y - 5 + 'px';
  }
  if(data.nodeType == '01'){
    popupType.value = 3
  }else{
    popupType.value = 2
  }
 dataInfo.value = JSON.parse(JSON.stringify(data)) 
 isSwitch.value = false
 isTreeDrag.value = true
}
function editClic(data:any){
  if(data.type == '03'){
    window.open('/#/dvsCanvas?dvId=' + data.id+'&appId=' + projectInfo.value.id,  '_blank');
  }else if(data.type == '0301'){
    window.open('/#/dashboard?resourceId=' + data.id + '&appId='+projectInfo.value.id, '_blank');
  }else if(data.type == '04'||data.type == '05'||data.type == '06'){
    window.open('/#/formcreatedesigner?moduleId=' +data.id + '&appId='+projectInfo.value.id,  '_blank');
  } else if(data.type == '02'){
     const route = router.resolve({
      path: '/editNavbar',
      query: { dvId: data.id,appId:projectInfo.value.id,name:data.name,appname:projectInfo.value.name }
    });
    window.open(route.href, '_blank');
  } else if(data.type == '01'){
     const route = router.resolve({
      path: '/editLogin',
      query: { dvId: data.id,appId:projectInfo.value.id,name:data.name,appname:projectInfo.value.name }
    });
    window.open(route.href, '_blank');
  }
}
function addTreeChildNode(event:any,level:any,data:any){  // 添加子节点
  let element = document.getElementById("drag_main_area")
  if(element !=null){
    const x = event.clientX;  // 水平坐标（相对于元素边界）
    const y = event.clientY;  // 垂直坐标（相对于元素边界）
    element.style.left = x + 10 + 'px';
    element.style.top = y - 5 + 'px';
  }
  popupType.value = 1
  dataInfo.value={
    appId:projectInfo.value.id,
    pid: data.id,
    level: level,
    nodeType: "",
    name:'',
    type:data.type
  }
  isTreeDrag.value = true
}
function addTreeClic(name:any){ // 新建
  popupType.value = 1
  if(name == '目录'){
    dataInfo.value.nodeType = '01'
  }else{
    dataInfo.value.nodeType = '02'
  }
  title.value = '新建' + name
  isSwitch.value = false
  isDialog.value= true
}
function paramsCloseForm(){
  isDialog.value = false
}
function saveData(){ // 保存
  if(isSwitch.value == true){
    return
  }
  isSwitch.value = true
  if(dataInfo.value.id !=null && dataInfo.value.id !=''){
    let data = {
      id:dataInfo.value.id,
      name:dataInfo.value.name,
      type:dataInfo.value.type,
    }
    moduleUpdate(data).then(() => {
      ElMessage.success('修改成功')
      getInit()
      isDialog.value = false
    }).catch(() => {
      isSwitch.value = false
    })
  }else{
    moduleAdd(dataInfo.value).then(() => {
      ElMessage.success('添加成功')
      getInit()
      isDialog.value = false
    }).catch(() => {
      isSwitch.value = false
    })
  }
  
}
function copyClick(){
  ElMessageBox.confirm('是否确定复制该'+ (dataInfo.value.nodeType == '01'?'目录' : '模块'), {
      confirmButtonType: 'primary',
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(() => {
      moduleCopy(dataInfo.value.id).then((res) => {
        if(res.code == '0' && res.data.code == '0'){
          ElMessage.success('复制成功')
        getInit()
        }else{
          ElMessage.error(res.data.msg)
        }
       
        isDialog.value = false
      }).catch(() => {
        isSwitch.value = false
      })
    })
  
}
function moveTreeClic(){ // 
  
}
function editTreeClic(){  // 编辑
  isSwitch.value = false
  if(dataInfo.value.nodeType == '01'){
    title.value = '编辑目录'
  }else{
    title.value = '编辑模块'
  }
  isDialog.value = true
}
function delTreeClic(){ // 删除
    ElMessageBox.confirm('是否确定删除该'+ (dataInfo.value.nodeType == '01'?'目录' : '模块'), {
      confirmButtonType: 'primary',
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(() => {
      moduleDel(dataInfo.value.id).then(res => {
        if(res.data.code == '0'){
          ElMessage.success('删除成功')
          getInit()
        }else{
          ElMessage.error("删除成功")
        }
      })
    })

}

</script>
<template>
<div class="project-left-box">
  <div class="project-left-top">
    <div class="project-left-title">模块列表</div>
    <img src="@/assets/newimg/u76.png" alt="" style="margin-right: 10px;cursor: pointer;" @click="addClic('目录','1','00')">
    <img src="@/assets/newimg/u43.png" alt="" style="cursor: pointer;" @click="addClic('模块','1','00')">
  </div>
  <el-input
    placeholder="请输入"
    class="keywordsClass"
    maxlength="64"
    v-model="keywords"
    @blur="handleDatasetName"
    >
    <template #prepend>
      <img src="@/assets/newimg/u62.png" alt="">
    </template>
  </el-input>
  <el-scrollbar style="height: calc(100vh - 260px);margin-top: 10px;">
    <el-tree v-loading="treeloading" id="treeRefClickId" ref="treeRef" node-key="id" :data="treeData" default-expand-all 
      :highlight-current="true" :props="defaultProps" :expand-on-click-node="false"
      @node-click="handleNodeClick">
      <template #default="{ data }">
        <!-- @mouseleave="isTreeDrag = false" -->
        <div class="el-tree-node__content"  >
          <img v-if="data.node_type=='01'" src="@/assets/newimg/u74.png" alt="" style="width: 14px;height: 13px;margin-right: 10px;">
          <div class="el-tree-node__label">{{ data.name }}</div>
          <div class="operation-button-box">
            <div  style="    
            width: 20px;
             height: 24px;">
              <img v-if="data.node_type == '01'" src="@/assets/newimg/icon/add.png" alt="" style="width: 14px;height: 13px;" @click.stop="addTreeChildNode($event, Number(data.level)+1,data)">
              <img v-if="data.node_type == '02'"  src="@/assets/newimg/icon/bianji.png" alt="" style="width: 14px;height: 13px;" @click.stop="editClic(data)">
            </div>
            <div style="    
              width: 20px;
              height: 24px;"  @click.stop="moreClic($event,data)">
              <img src="@/assets/newimg/icon/dian.png" alt="" style="width: 4px;height: 14px;margin-left: 15px;">
            </div>
           
          </div>
        </div>
      </template>
    </el-tree>
  </el-scrollbar>
  <el-dialog
    :title="title"
    v-model="isDialog"
    width="570px"
    class="create-project-dialog"
    :before-close="paramsCloseForm"
  >
    <el-form
      ref="paramsObjRef"
      :model="dataInfo"
      label-width="100px"
    >
      <el-form-item :label="dataInfo.nodeType=='01'?'目录名称：':'模块名称：'" prop="name">
        <el-input
          :placeholder="'请输入'"
          v-model="dataInfo.name"
        />
      </el-form-item>

      <el-form-item :label="dataInfo.nodeType=='01'?'目录类型：':'模块类型：'" prop="type">
        <el-select
          v-model="dataInfo.type"
          placeholder=""
          style="width: 100%"
          :disabled="dataInfo.nodeType=='02'"
        >
          <el-option
            v-for="item in typeList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>


    </el-form>
    <template #footer >
      <el-button class="root-class" @click="paramsCloseForm">{{ t('dataset.cancel') }} </el-button>
      <el-button class="root-class" type="primary" @click="saveData">{{ t('dataset.confirm') }} </el-button>
    </template>
  </el-dialog>
  <div id="drag_main_area" v-show="isTreeDrag" 
  @mousemove="isTreeDrag = true"
  @mouseleave="isTreeDrag = false"
  >
    <div class="drag-main-text" v-if="popupType == 1" @click="addTreeClic('目录')">新建目录</div>
    <div class="drag-main-text" v-if="popupType == 1"  @click="addTreeClic('模块')">新建模块</div>


    <div class="drag-main-text" v-if="popupType == 2"  @click="copyClick">复制</div>
    <!-- <div class="drag-main-text" v-if="popupType == 2 || popupType == 3"  @click="moveTreeClic">移动到</div> -->
    <div class="drag-main-text" v-if="popupType == 2 || popupType == 3"  @click="editTreeClic">重命名</div>
    <div class="drag-main-text" v-if="popupType == 2 || popupType == 3"  @click="delTreeClic">删除</div>


  </div>
</div>
</template>

<style lang="less" scoped>
.project-left-box{
  width: 260px;
  height: calc(100vh - 60px);
  background-color: rgba(37, 38, 38, 1);
  box-sizing: border-box;
  border-right: 1px solid rgba(79, 80, 82, 1);
  .keywordsClass{
    margin-left:10px;
    width: calc(100% - 20px) ;
    height: 40px;
    background: inherit;
    background-color: rgba(37, 38, 38, 1);
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    border-color: rgba(51, 51, 51, 1);
    border-radius: 4px;
    :deep(.ed-input__wrapper){
      background-color: rgba(37, 38, 38, 1);
      box-sizing: border-box;
      border-width: 1px;
      border-style: solid;
      border-color: rgba(51, 51, 51, 0);
      border-radius: 4px;
      box-shadow:none ;
      border: none !important;
    }
    :deep(.ed-input__inner){
      background-color: rgba(37, 38, 38, 1);
      box-sizing: border-box;
      border-width: 1px;
      border-style: solid;
      border-color: rgba(51, 51, 51, 0);
      border-radius: 4px;
      color: #fff;
    }
    :deep(.ed-input-group__prepend){
      background-color: rgba(37, 38, 38, 1) !important;
      border: 0;
      box-shadow:0 0 0 1px transparent ;
      padding:0 10px;
      padding-right: 0;
    }
    :deep(.ed-input__wrapper:hover){
      border: none;
    }
  }
  :deep(.ed-tree){
    background: transparent;
  }
  :deep(.ed-tree-node__content){
    height: 40px;
  }
  .operation-button-box{
    display: none;
    position: absolute;
    right: 20px;
    // display: flex;
    align-items: center;

  }
  :deep(.ed-tree-node__content:hover){
    background: rgba(255, 255, 255, 0.1);
    .operation-button-box{
      display: flex;
    }
  }
  :deep(.ed-tree--highlight-current .ed-tree-node.is-current>.ed-tree-node__content){
    background: rgba(0, 137, 255, 0.3);
  }
  
  .el-tree-node__content{
    display: flex;
    align-items: center;
  }
  .el-tree-node__label{
    width: calc(100% - 40px);
    font-size: 14px;
    color: #F2F4F5;
    text-align: left;
    font-family: 'Arial Normal', 'Arial';
    font-weight: 400;
    font-style: normal;
  }
}
.project-left-top{
  display: flex;
  align-items: center;  
  padding:20px 10px;
}
.project-left-title{
  width: 200px;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
  font-weight: 700;
  font-style: normal;
  font-size: 16px;
  color: #F2F4F5;
}
:deep(.ed-input__wrapper){
  background-color: rgba(37, 38, 38, 1);
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(51, 51, 51, 0);
  border-radius: 4px;
  box-shadow:0 0 0 1px rgba(67, 67, 67, 1) ;
}
:deep(.ed-input__inner){
  background-color: rgba(37, 38, 38, 1);
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(51, 51, 51, 0);
  border-radius: 4px;
  color: #fff;
}
:deep(.ed-input__wrapper:hover){
  border: 1px solid #0089ff;
}
:deep(.ed-input.is-disabled .ed-input__wrapper){
  background-color: rgba(37, 38, 38, 0);
  border: 1px solid rgba(80, 80, 80, 1);
}
:deep(.ed-input.is-disabled .ed-input__inner){
  background-color: rgba(37, 38, 38, 0);
}
:deep(.ed-select__popper.ed-popper){
  background: rgb(41,41,41) !important;

}
</style>
<style>
.create-project-dialog{
  --ed-dialog-bg-color: rgba(33, 33, 33, 1);
}
.create-project-dialog .ed-dialog__title{
    font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
    font-weight: 700;
    font-style: normal;
    font-size: 16px;
    color: #F2F4F5;
}
.create-project-dialog .ed-form-item__label{
  font-family: 'Arial Normal', 'Arial';
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  color: #D2D2D2;
}
#drag_main_area{
  position: fixed;
  top: 0;
  left: 0;
  width: 150px;
  background-color: rgba(51, 51, 51, 1);
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: rgba(70, 70, 70, 1);
  border-radius: 5px;
  color: #ffffff;
}
.drag-main-text{
  box-sizing: border-box;
  padding-left: 10px;
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  color: #F2F4F5;
  text-align: left;
  margin-top: 5px;
  cursor: pointer;
}
.drag-main-text:hover{
  background-color: rgba(100, 100, 100, 1);
}
.root-class.ed-button{
  color: #F2F4F5;
  background-color: #212121;
  border: 1px solid #434343;
}
.root-class.ed-button--primary{
  background-color:#0089FF;
  border: 1px solid #0089FF;
}
.ed-input__wrapper:hover{
  border: 1px solid #434343;
}
.ed-select__popper.ed-popper{
  background: rgb(41,41,41) !important;
  color: #fff;
  border:1px solid #434343;
}
.ed-select-dropdown__item{
  color: #F2F4F5;
}
.ed-select-dropdown__item.hover, .ed-select-dropdown__item:hover{
  background-color: rgba(255, 255, 255, .1)
}                                                  
.ed-select .ed-input__wrapper:hover {
  box-shadow: none;
  border: 1px solid #5f5f5f;
}
.ed-select .ed-input.is-focus .ed-input__wrapper{                                                    
  box-shadow: none;
  border: 1px solid #5f5f5f;
}
.ed-select .ed-input__wrapper.is-focus{
  box-shadow: none;
  border: 1px solid #5f5f5f;
}
.ed-select .ed-input.is-disabled:not(.ed-input--dark) .ed-input__wrapper:hover{
  box-shadow: none !important;
}
.ed-input.is-disabled .ed-input__wrapper{
  box-shadow: none !important;
}
</style>
