<template>
  <div class="q-px-md q-pt-lg column full-height" ref="currentRootDom">
    <div class="q-pl-lg row q-mb-lg">
      <div class="col row items-center q-pl-md">
        <h5 class="row items-center">
          <span
            class="pointer"
            @click="BackInquire"
            ><el-icon class="q-pt-md" v-if="queryObj.FileId > 0" size="20"
              ><ArrowLeft /></el-icon
          ></span>
          <span class="q-pl-md"
          :class="[queryObj.FileId == 0?'':'row items-center']">
            <span class="pointer" @click="queryObj.FileId=0,refreshHandler()">
              <template v-if="currentMenu == 3">行程文档</template>
              <template v-else-if="currentMenu == 4">广告图</template>
            </span>
            <breadPeeling v-if="queryObj.FileId" :navigations="Navigations" 
            @Inquire="breadPeelingInquire"></breadPeeling>
          </span>
        </h5>
        <div class="select-btn q-pl-lg pointer q-mt-sm">
          <el-icon>
            <RefreshRight
              v-if="!RefreshLoading"
              @click="() => refreshHandler()"
            />
            <Refresh v-else />
          </el-icon>
        </div>
      </div>
      <div>
        <el-dropdown v-if="datas.selectedDatas.length>0" trigger="click" class="q-px-md">
          <el-button>
            <el-icon><CopyDocument /></el-icon>
            <span class="">批量操作</span>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item icon="Expand" @click="MoveFile(0)">移动至</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click">
          <el-button>新建</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="() => operaFolder(0, '')"
                >新建文件夹</el-dropdown-item
              >
              <el-dropdown-item
                @click="openMarketHandler('/trip')"
                v-if="currentMenu == 3"
                >新建行程</el-dropdown-item
              >
              <el-dropdown-item
                @click="openMarketHandler('/ad')"
                v-if="currentMenu == 4"
                >新建广告图</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="col full-width q-ml-md">
        <journeyAdsList 
        :current-menu="currentMenu"
        :set-file-list="datas.setFileList"
        :list="dataList"
        :msg="queryObj"
        :navigations="Navigations"
        :selected-datas="datas.selectedDatas"
        @UpdateData="UpdateData"
        @success="success"
        @refreshHandler="refreshHandler"></journeyAdsList>
    </div> 
  </div>
  
  <Folder
    :folder-id="folderObj?.id"
    :folder-name="folderObj?.name"
    :parent-id="folderObj.parentId"
    :folder-type="folderObj?.type"
    v-if="folderObj.id > -1"
    @close="() => (folderObj.id = -1)"
    @success="refreshHandler()"
  ></Folder>

  <TreeFile v-if="isTreeFile" 
  :details="journeyAdsDetails"
  :selected-datas="datas.selectedDatas" 
  :set-file-list="datas.setFileList"
  :file-type="queryObj.FileType"
  :file-id="queryObj.FileId"
  :msg="queryObj"
  @close="() => {journeyAdsDetails = '';isTreeFile=false}" 
  @success="success()"></TreeFile>
  
</template>
<script setup lang="ts">
import { ref, reactive, watch, inject, onMounted, PropType } from "vue";
import { ElMessage } from "element-plus";
import { ArrowLeft,CopyDocument } from "@element-plus/icons-vue";
import FolderService from "@/services/FolderService";
import { injectKeyTemplate } from "@/types/injectKey";
import { useSellTemplateStore, useScreenStore } from "@/store";
import Folder from "./components/Folder.vue";
import TreeFile from "./components/TreeFile.vue";
import breadPeeling from "./components/breadPeeling.vue";
import { ApiResult } from "@/configs/axios";
import journeyAdsList from "./components/journeyAdsList.vue";
import { openNewBlank } from "@/utils/common";

const SalesEditorStore = useSellTemplateStore();
const marketStore = useScreenStore();
const props = defineProps({
  currentMenu: {
    type: Number,
    default: 3,
  },
  position:{
    type:Object as PropType<{FileId:number,FileType:1|2,Position:{FileId:number,FileName:string}[]}|null>,
    default:null
  }
});

const journeyAdsDetails = ref('');
const isTreeFile = ref(false)
const Navigations = ref([] as Array<any>);
const dataList = ref([] as Array<any>);
const searchData = ref({} as any);
searchData.value = inject(injectKeyTemplate);
const RefreshLoading = ref(false)
const currentRootDom = ref()
const datas = reactive({
  selectedDatas: [] as Array,
  selectAll: false as any,
  fileList: [] as any,
  setFileList: [] as any,
});
const folderObj = ref<{
  id: number;
  name: string;
  parentId: number;
  type: number;
}>({ id: -1, name: "", parentId: 0, number: 1 });

const emit = defineEmits<{
  (event: 'destroy-position'): void
}>()
const queryObj = reactive({
  pageIndex: 1,
  pageSize: 50,
  pageCount: 0, //总页数
  FileType: props.currentMenu==3?1:2,
  FileId: 0,
  OrderByType: 2,//1 升序 2倒序
});

const loading = ref(false as any);
const SellTemplateRef = ref<any>();

// 已选数据
const UpdateData = (obj:any) =>{
  if(obj){
    if(obj.list) dataList.value = obj.list
    if(obj.selectedDatas) datas.selectedDatas = obj.selectedDatas
  }
}

const success = () => {
  isTreeFile.value = false;
  datas.selectedDatas = [];
  for (let index = 0; index < dataList.value.length; index++) {
    const element = dataList.value[index]
    element.singleChoice = false;
  }
  refreshHandler()
}

// 导航
const BackInquire = () => {
  let Navigation = Navigations.value[Navigations.value.length-2]
  if(Navigation&&Navigation.FileId){
    breadPeelingInquire(Navigation.FileId,Navigations.value.length-2)
  }else breadPeelingInquire(0,0)
}

const breadPeelingInquire = (FileId:number,index:number)=> {
  datas.selectedDatas = [];
  Navigations.value.splice(index+1, Navigations.value.length-1)
  queryObj.FileId = FileId
  refreshHandler()
}

const openMarketHandler = (type:string='') =>{
    openNewBlank(`/market/create${type}`)
}

// 移动到文件夹
const MoveFile = () => {
  datas.setFileList = []
  for(let i=0;i<dataList.value.length;i++){
    for(let j=0;j<datas.selectedDatas.length;j++){
      if(dataList.value[i].FileId==datas.selectedDatas[j]){
        datas.setFileList.push(
          {
            FileId: dataList.value[i].FileId,
            FileType: dataList.value[i].FileType,
            ParentFileId: dataList.value[i].ParentFileId
          }
        )
      }
    }
  }
  isTreeFile.value = true
}

const querySearchHandler = async () => {
  if(loading.value) return
  loading.value = true;
  try {
    if (queryObj.pageIndex == 1) dataList.value = [];
    let pageRes = await FolderService.GetMyTripFolderPage(queryObj);
    if (pageRes.data.resultCode == ApiResult.SUCCESS) {
      let arrList = function (list) {
        list.forEach((x) => {
          x.show = false;
          x.singleChoice = false;
          x.Id = ''
          x.showSelect = false
          x.Highlight = false
          if(props.position&&x.FileId==props.position.FileId&&x.FileType==props.position.FileType) x.Highlight = true
        });
      };
      arrList(pageRes.data.data.pageData);
      datas.selectedDatas = Array.from(new Set(datas.selectedDatas))
      dataList.value = dataList.value.concat(pageRes.data.data.pageData);
      queryObj.pageCount = pageRes.data.data.pageCount;
      if(props.position) emit('destroy-position')
    }
    loading.value = false;
    RefreshLoading.value = false;
  } catch (error) {
    ElMessage.error({
        message:'数据加载异常，请刷新页面'
    })
    loading.value = false;
    RefreshLoading.value = false;
  }
};

const refreshHandler = (obj:any) => {
  currentRootDom.value.click()
  if(obj){
    if(obj.FileId) {
      queryObj.FileId = obj.FileId
      datas.selectedDatas = []
    }
    if(obj.OrderByType) queryObj.OrderByType = obj.OrderByType
    if(obj.FileName==''||obj.FileName) queryObj.FileName = obj.FileName
    if(obj.Navigations) Navigations.value = obj.Navigations
  }
  RefreshLoading.value = true;
  queryObj.pageIndex = obj&&obj.pageIndex?obj.pageIndex:1;
  querySearchHandler();
};
const operaFolder = (id: number, name: string) => {
  folderObj.value.id = id;
  folderObj.value.name = name;
  folderObj.value.type = queryObj.FileType;
  folderObj.value.parentId = queryObj.FileId
};
const checkPositionHandler = (n:any)=>{
  if(n){
    if(n.Position && n.Position.length>0){
      Navigations.value=n.Position
      queryObj.FileId = n.Position[n.Position.length-1].FileId
      queryObj.FileType = 0
    }else{
      Navigations.value=[]
      queryObj.FileId = 0
      queryObj.FileType = n.FileType
    }
  }
}

watch(
  () => props.currentMenu,
  (n, o) => {
    datas.selectedDatas = [];
    queryObj.FileType = n==3?1:2;
    queryObj.FileId = 0;
    refreshHandler();
  }
);

watch(() => queryObj.FileId,(n, o) => {
    if(!n) Navigations.value = []
  }
);
watch(() => props.position,(n,o)=>{
  if(n){
    checkPositionHandler(n)
    refreshHandler()
  }
},{
  deep:true
})

onMounted(() => {});
checkPositionHandler(props.position)
querySearchHandler();

</script>
<style lang="scss" scoped>
  .journeyAdsScrollbar {
      ::v-deep(.el-table__inner-wrapper::before){
        width: 0px;
        height: 0px;
      }
  }
  ::v-deep(.el-scrollbar__view){
      height: 100%;
  }
</style>
