<script lang="ts" setup>

import { userStror } from "@/utils/pinia/stores/modules/userOrders";
import router from "@/utils/router";
import BottomPage from '@/views/common/bottom/index.vue'
import { matterInfo} from "@/api/doc/type"
import { getMySpaces,doCreateSpace} from "@/api/doc/index"
import SvgIcon from "@/components/svgIcon/index.vue";
import { doDelSpace,spaceMatterRename,doAccessManage} from "@/api/doc/space"
import sharePermission from './sharePermission.vue';
import spacePermission from './spacePermission.vue';
import { h } from 'vue'
import {
  Delete,
  Promotion,
  Edit,
  Setting,
} from '@element-plus/icons-vue'

const userStore = userStror();
const uid=btoa("p0"+userStore.userInfoCont.userId);
const rawUid="p0"+userStore.userInfoCont.userId
const spaceTreeData=ref<matterInfo[]>([])//{name:'个人空间',uuid:'root',children:[]}
const showPopup=ref(false)
const currentHoverRow=ref<matterInfo>({}) //table 行的按钮控制
const Departs = computed(() => {
    return `${'p0'+userStore.userInfoCont.userId},${userStore.userInfoCont.company},${userStore.userInfoCont.department},${userStore.userInfoCont.organization}`
})
const dynamicVNode = ref<VNode | null>(null) //permission 组件的父组件
const CutLevelPermit=ref(0)

function onSelectSpace(data:matterInfo,recycling?:boolean){
  if(data){
    router.push({ 
      name: "spaces",
      params:{fa:7, spaceid:data.uuid},
      state:{
       space: toRaw(data),  //这里一定要用toRaw
      }
    }); 
  }else{
    if(recycling) {
       router.push({ path: "/mysapce",query:{fa:7,recycling:recycling}}); 
      return
    }
    router.push({ path: "/mysapce",query:{fa:7}}); 
  }
}

//-------------------space feature---------------------
function onNewSpace(){
  const newname=ref("")
  ElMessageBox({
    title:"请输入空间名称",
    customStyle: { bottom:'200px'},
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    message: () => h(ElInput, {
      style: { width:'360px' },  
      modelValue: newname.value,
      'onUpdate:modelValue': (val) => {
        newname.value = val
      },
    }),
  }).then(() => {
    if(newname.value!==""){
      doCreateSpace(uid,newname.value).then((resp)=>{
        //spaceTreeRef.value.append({name:resp.data.name,uuid:resp.data.uuid,dir:false,userUuid:resp.data.userUuid})
        router.replace({ query: { t: Date.now() } }) //直接刷新
      })
    }
  })
}

function onSpaceMatterRename(row:matterInfo){
  const newname=ref(row.name)
  ElMessageBox({
    title:"请输入新的文件名",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    message: () => h(ElInput, {
      style: { width:'360px' },  
      modelValue: newname.value,
      'onUpdate:modelValue': (val) => {
        newname.value = val
      },
    }),
  }).then(() => {
    if(newname.value&&newname.value!=""){
      spaceMatterRename(uid,{
        space:row.uuid,
        uuid:row.uuid,
        name:newname.value,
      }).then(()=>{
         router.replace({ query: { t: Date.now() } }) //直接刷新
      })
    }
  })
}

//空间成员管理
function onAccessManage(row:matterInfo){
  dynamicVNode.value = h(sharePermission, {
    uid: uid,
    uuid: "",
    spaceid:row.uuid, //
    confirmFunc: (_list: string[],_infos:string[]) => {
      // 组织权限数据
      //_len=_list.length
      let permited = btoa(_list.join("|"))
      doAccessManage(uid,{
        "space":row.uuid,
        "roles":permited, 
        "owner":row.userUuid,
        "len":_list.length
      }).then(()=>{
        
      })
    },
    closeFunc: () => {
      dynamicVNode.value=null
    }
  })
}

//删除空间
function onDeleteSpace(row:matterInfo){
  ElMessageBox.confirm(`确认删除空间 ( ${row.name}) ? 空间内所有文件将不可恢复！取消则放弃删除操作。`, "警告", {
    confirmButtonText: "确定删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(()=>{
    doDelSpace(uid,{
      "space":row.uuid,
    }).then(()=>{
      router.replace({ query: { t: Date.now() } })
    })
  })
}

//空间权限控制管理
function onSpacePManage(row:matterInfo){
  dynamicVNode.value=h(spacePermission,{
    uid:rawUid,   //当前用户的uuid
    uuid:row.uuid,  //文档的uuid
    suid:row.userUuid,
    spaceid:row.uuid, //空间uuid
    closeFunc:()=>dynamicVNode.value=null
  })
}
//------------------------------------------------------

function onSpaceConfig(row:matterInfo){
  showPopup.value=true;
  currentHoverRow.value=row
  if (row.manager) {
    CutLevelPermit.value=9
  }else{
    let _pert: Record<string, number>
    _pert = JSON.parse(row.permits!.data)
    let val=_pert[rawUid.replace("p0","")]
    if(val){
      CutLevelPermit.value = val
    }else{
      CutLevelPermit.value = 0//没有权限！！
    }
  }
}

onMounted(()=>{
  if(userStore.userInfoCont == ""){
    userStore.getInfo().then(()=>{
      getMySpaces(uid,{roles:Departs.value}).then((resp)=>{
        resp.data.forEach((item)=>{
          let ismanager=false
          if(item.userUuid==rawUid || item.managers.includes(rawUid)) ismanager=true;
          spaceTreeData.value.push({name:item.name,uuid:item.uuid,dir:false,userUuid:item.userUuid,manager:ismanager,permits:item.permits})
        })
      })
    })
  }else{
    getMySpaces(uid,{roles:Departs.value}).then((resp)=>{
      resp.data.forEach((item)=>{
        let ismanager=false
        if(item.userUuid==rawUid || item.managers.includes(rawUid)) ismanager=true;
        spaceTreeData.value.push({name:item.name,uuid:item.uuid,dir:false,userUuid:item.userUuid,manager:ismanager,permits:item.permits})
      })
    })
  }
})

</script>

<template>
    <div class="app_container">
      <div>
        我的
        <ul>
          <li @click="onSelectSpace(null)">
            <div style="display: flex;align-items: center;"><svg-icon icon-class="folder-icon" :size="30" />
               <span>我的空间</span>
            </div>
          </li>
          <li @click="onSelectSpace(null,true)">
            <div style="display: flex;align-items: center;"><svg-icon icon-class="folder-icon" :size="30" /> <span>回收站</span>
            </div>
          </li>
        </ul>
      </div>
      <div style="margin: 20px 0;">
        共享
        <ul>
          <li v-for="value in spaceTreeData" @click="onSelectSpace(value)">
            <div style="display: flex;align-items: center;">
              <svg-icon icon-class="folder-icon" :size="30" />
              <span>{{ value.name }}</span> 
              <el-button type="text" icon="MoreFilled" size="small"
                @click="(e)=>{e.stopPropagation(); onSpaceConfig(value);}"></el-button>
            </div>
            <!-- <hr> -->
          </li>
        </ul>
      </div>
      <div style="margin: 20px 0; display: flex;align-items:center;" @click="onNewSpace"><Plus style="width: 18px; height: 18px;"></Plus> 创建共享空间</div>
    </div>
    <div v-if="showPopup" class="mask" @click="showPopup = false"></div>

    <div v-if="dynamicVNode">
      <component :is="dynamicVNode" />
    </div>
    <!-- 主体 -->
    <Transition name="popuper">
      <div v-if="showPopup" class="bs-wrapper">
        <div class="popupTitle">
          <svg-icon  icon-class="folder-icon" size="30px"/>
           {{ currentHoverRow.name }} 
          <el-button type="text" @click="showPopup=false">关闭</el-button>
        </div>
        <hr>
        <div class="blocker-list" v-if="CutLevelPermit>=5">
          <span class="blocker" @click="onAccessManage(currentHoverRow)">
            <Edit style="width: 24px; height: 24px;"></Edit>成员管理</span>
          <span class="blocker"  @click="onSpacePManage(currentHoverRow)">
            <Setting style="width: 24px; height: 24px;"></Setting>权限设置</span>
          <span class="blocker"  @click="onDeleteSpace(currentHoverRow)">
            <Delete style="width: 24px; height: 24px;"></Delete>删除</span>
          <span class="blocker"  @click="onSpaceMatterRename(currentHoverRow)">
            <Promotion style="width: 24px; height: 24px;"></Promotion>重命名</span>
        </div>
      </div>
    </Transition>

    <BottomPage />
</template>

<style lang="scss" scoped>
.app_container {
  padding: 40px 29px;;
  height: calc(100vh - 65px);
  overflow: hidden;
  position: relative;
}
hr{
  margin: 8px 5px 8px auto;
  border: none;
  width: 88%;
  align-self: center;
  background: #63616145;
}
ul >li{
  padding: 10px 0px 10px 10px;
  background: white;
  border-radius: 10px;
  margin: 4px;
  span{
    margin-left: 10px;
  }
  button{
    margin-left: auto;
    margin-right: 0px;
  }
}

//---------------animation
/* 遮罩: popup 的遮罩 */
.mask{
  position: fixed;
  inset: 0;
  background:rgba(0,0,0,.4);
  z-index:999;
}

.bs-wrapper{
  position: fixed;
  display: flex;
  flex-direction: column;
  left:0;
  right:0;
  bottom:0;
  height:36vh;          /* 半屏停住 */
  background:#f1f1f1;
  border-radius:16px 16px 0 0;
  z-index:1000;
  overflow-y:auto;
  padding: 8px 16px;
  hr{
    margin: 8px 0;
    border: none;
    width: 88%;
    align-self: center;
    background: #63616145;
  }
}
.popupTitle{
  display: flex;
  align-items: center;
  button{
    margin-left: auto;
    margin-right: 5px;
  }
}
.blocker-list{
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  font-size: small;
  .blocker{
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 15px;
    background-color: white;
    border-radius: 5px;
    margin: 6px;
    width: 70px;
    height: 70px;
  }
}

.popuper-enter-from{
  transform:translateY(100%);
  opacity:0;
}
/* 进入过程 */
.popuper-enter-active{
  transition:all .3s ease-out;
}
/* 离开后：回到下方 */
.popuper-leave-to{
  transform:translateY(50px);
  opacity:0;
}
.popuper-leave-active{
  transition:all .3s ease-in;
}
//---------------------------

</style>