<template>
    <div class="column full-height" ref="currentRootDom">
      <div class="row items-center flex-between">
        <div class="text-dark text-weight-bolder">云盘空间</div>
        <div class="row flex-center CloudDisk-R-inquire">
          <el-input
          style="max-width:600px" v-model="queryObj.FileName" placeholder="请输入图片名称搜索" 
          class="q-pr-33 input-with-select" clearable
          @keyup.enter="refreshHandler" @input="SearchImg"
          >
            <template #prefix>
              <IconSearch class="cusor-pointer" @click.stop="refreshHandler"></IconSearch>
            </template>
            <template #append>
              <el-select v-model="queryObj.QCreateBy" 
              placeholder="检索上传人" 
              style="width: 100px"
              filterable
              remote
              reserve-keyword
              :remote-method="remoteMethod"
              :loading="CreateLoading"
              @change="ClearOption(),refreshHandler()"
              clearable>
              <el-option
                v-for="item in CreateList"
                :key="item.EmployeeId"
                :label="item.EmName"
                :value="item.EmployeeId"
              />
              </el-select>
            </template>
          </el-input>
        </div>
        <FileInput :multiple="true" @change="files => insertImageElement(files)">
          <el-button icon="Plus" class="ppt-button text-normal" type="primary">图片</el-button>
        </FileInput>
      </div>
      <div class="col full-width full-height q-mt-lg">
        <div class="CloudDisk-form row full-height">
          <div class="CloudDisk-L">
              <div class="row CloudDisk-L-inquire">
                  <el-input style="width: 123px;" v-model="GName" 
                  placeholder="搜索分组名称" clearable @keyup.enter="querySearchGroup"
                  @input="SearchGroup">
                  </el-input>
                  <el-button icon="Plus"  @click="addEditGroup">分组</el-button>
              </div>
              <div class="CloudDisk-L-Center fz14" v-loading="loadingGroup">
                  <div class="CloudDisk-L-Title row flex-between cusor-pointer"
                  v-for="(item,index) in GroupList"
                  :class="[queryObj.CloudGroupId==item.Id?'active':'']">
                      <span class="block grow" @click="refreshHandler(item)">{{item.GName}}</span>
                      <div class="row" :key="index">
                          <template v-if="item.Id">
                              <el-dropdown class="q-pl-lg CloudDisk-L-TitleR" trigger="click">
                                  <div class="CloudDisk-L-Title-M row items-center flex-center">
                                      <el-icon size="16"><MoreFilled /></el-icon>
                                  </div>
                                  <template #dropdown>
                                      <el-dropdown-menu class="q-pa-md">
                                          <el-dropdown-item @click.stop="EditGroup(item)">
                                              <el-button type="default" link icon="Edit" size="small">重命名</el-button>
                                          </el-dropdown-item>
                                          <el-dropdown-item v-if="!item.IsCanDelete" @click.stop="deleteGroup(item)">
                                              <el-button type="default" link icon="Delete" size="small">删除分组</el-button>
                                          </el-dropdown-item>
                                      </el-dropdown-menu>
                                  </template>
                              </el-dropdown>
                          </template>
                          <div class="CloudDisk-L-TitleR" @click="refreshHandler(item)" v-else></div>
                         <span class="CloudDisk-L-TitleR" @click="refreshHandler(item)" v-if="item.RecordNum>0">{{item.RecordNum?item.RecordNum:''}}
                         </span> 
                      </div>
                      
                  </div>
              </div>
          </div>
          <div class="CloudDisk-R grow">
            <div class="CloudDisk-R-header row flex-between items-center "
            :class="[queryObj.layout==3?'q-mb-lg':'q-mb-xs']">
              <div class="fz14 PingFangSC colorBA"></div>
              <div>
                  <el-dropdown trigger="click" @visible-change="changeDrop(1)"
                  :class="[currentSearchType==1?'DiskRHActive':'']">
                    <el-button color="#EFEFEF">
                        <span>格式</span> <el-icon color="#9DA2AA" class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <div class="q-py-lg q-px-lg">
                        <el-input
                        style="max-width:200px" v-model="queryObj.QFileName" placeholder="搜索" 
                        class="input-with-select" clearable
                        @input="SearchCloudInfo"
                        >
                          <template #prefix>
                            <IconSearch class="cusor-pointer" @click.stop="refreshHandler"></IconSearch>
                          </template>
                        </el-input>
                        <div class="row flex-between items-center q-pt-md" v-for="(item,index) in formatType">
                          <div class="grow">
                            <el-checkbox-group  v-model="queryObj.QFileType" @change="ClearOption(),refreshHandler()">
                              <el-checkbox style="width: 100%;"
                              :label="item.FileFormat"></el-checkbox>
                            </el-checkbox-group>
                          </div>
                          <span>{{item.RecordNum}}</span>
                        </div>
                      </div>
                    </template>
                  </el-dropdown>
                  
                  <el-dropdown trigger="click" @visible-change="changeDrop(2)"
                  :class="[currentSearchType==2?'DiskRHActive':'']" class="cusor-pointer">
                    <div style="position: relative;width: 95px;height: 34px;">
                      <el-button color="#EFEFEF" style="position:absolute;left: 0;right: 0;z-index: 2;">
                        <span class="cusor-pointer">添加时间</span> <el-icon color="#9DA2AA" class="el-icon--right"><arrow-down /></el-icon>
                      </el-button>
                      <div class="CloudDisk-R-Date">
                        <el-date-picker
                            class="CloudDisk-date"
                            style="width: 95px;"
                            v-model="dateArr"
                            type="daterange"
                            start-placeholder=""
                            end-placeholder=""
                            value-format="YY-MM-DD"
                            ref="dropdownDade"
                            @change="ClearOption(),getDate()"
                          />
                      </div>
                    </div>
                  </el-dropdown>
                  <el-dropdown trigger="click" @visible-change="changeDrop(3)"
                  @command="OpenDropdown"
                  :class="[currentSearchType==3?'DiskRHActive':'']"
                  ref="dropdownSort">
                    <el-button>
                      <el-icon color="#808791">
                        <IconSortOne></IconSortOne>
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <template v-for="(item,index) in sortType">
                          <el-dropdown-item :command="item.ID" class="row flex-between"
                          @click="ClearOption(),setDropdown(item,1)">
                            <span style="width: 80px;">{{item.Name}}</span>
                            <IconCheck class="q-pl-lg" v-if="item.check"></IconCheck>
                          </el-dropdown-item>
                        </template>
                        <template v-for="(item,index) in sortTypeUD">
                          <el-dropdown-item :command="item.ID" class="row flex-between"
                          :divided="index==0?true:false"
                          @click="ClearOption(),setDropdown(item,2)">
                            <span style="width: 80px;">{{item.Name}}</span>
                            <IconCheck class="q-pl-lg" v-show="item.check"></IconCheck>
                          </el-dropdown-item>
                        </template>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <el-dropdown trigger="click" @visible-change="changeDrop(4)"
                  :class="[currentSearchType==4?'DiskRHActive':'']"
                  ref="dropdownLayout">
                    <el-button>
                      <el-icon color="#808791">
                        <IconGridFour v-if="queryObj.layout==1"/>
                        <IconWaterfallsH v-if="queryObj.layout==2"/>
                        <IconListCheckbox v-if="queryObj.layout==3"/>
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <template v-for="(item,index) in layoutType">
                          <el-dropdown-item :command="item.ID" class="row flex-between"
                          @click="setDropdown(item,3)">
                            <div class="row items-center" style="width: 80px;">
                              <el-icon>
                                <IconGridFour v-if="item.ID==1"/>
                                <IconWaterfallsH v-if="item.ID==2"/>
                                <IconListCheckbox v-if="item.ID==3"/>
                              </el-icon>
                              <span>{{item.Name}}</span>
                            </div>
                            <IconCheck class="q-pl-lg" v-show="item.check"></IconCheck>
                          </el-dropdown-item>
                        </template>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
              </div>
            </div>
            <div ref="imgDiskRef" class="full-height" style="padding-top: 10px;overflow:auto;"
            :style="{'padding-bottom':queryObj.pageCount == queryObj.pageIndex && !loading?'60px':'130px'}"
            @mousedown="handleMouseDown">
              <div class="mask" v-if="queryObj.layout!=3" v-show="positionList.is_show_mask" :style="'width:' + mask_width + 'left:' + mask_left + 'height:' + mask_height + 'top:' + mask_top"></div>
              <cellList v-if="dataList.length>0&&queryObj.layout==1" :dataList="dataList" 
                  @refreshHandler="refreshHandler"
                  @CopyTo="CopyTo"
                  @MoveFile="MoveFile"
                  @getImg="getImg"
                  @deleteImg="deleteImg"
                  @MultipleChoice="MultipleChoice"
                  :Parent="datas"
                  ></cellList>
              <waterfallFlowList v-if="dataList.length>0&&queryObj.layout==2" :dataList="dataList" 
                  @refreshHandler="refreshHandler"
                  @CopyTo="CopyTo"
                  @MoveFile="MoveFile"
                  @getImg="getImg"
                  @deleteImg="deleteImg"
                  @MultipleChoice="MultipleChoice"
                  :Parent="datas"
                  ></waterfallFlowList>
              <list v-if="dataList.length>0&&queryObj.layout==3" :dataList="dataList"
                  @refreshHandler="refreshHandler"
                  @CopyTo="CopyTo"
                  @MoveFile="MoveFile"
                  @getImg="getImg"
                  @deleteImg="deleteImg"
                  @MultipleChoice="MultipleChoice"
                  @BatchRemove="BatchRemove"
                  @BatchCopyTo="BatchCopyTo"
                  @BatchMoveFile="BatchMoveFile"
                  :Parent="datas"
                  :params="queryObj"
                  ></list>
                <div v-if='queryObj.pageCount == queryObj.pageIndex && !loading' class="text-center q-pt-lg"></div>
                <template v-else>
                  <div style="height:40px;" class="no-bg" background="transparent" v-loading="loading"  element-loading-text="正在加载中"></div>
                </template>
                <div v-if="(!dataList || dataList.length==0) && !loading">
                  <el-empty class="q-ma-xl" description="暂无数据" />
                </div>
            </div>
            <!-- <div v-if="queryObj.pageCount>1" class="q-mt-md" style="display: flex;justify-content: center;">
                <el-pagination
                v-model:current-page="queryObj.pageIndex"
                :page-size="queryObj.pageSize"
                small-padding
                layout="prev, pager, next"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                />
            </div> -->
             <div v-if="queryObj.layout!=3&&datas.ControlsShow" class="CloudDisk-RBF animate__animated animate__fadeInUp">
              <div class="CloudDisk-RBFCenter microsoft">
                <div class="row flex-center">
                  <div class="CloudDisk-RBFbj rounded row items-center">
                    <div class="row items-center nowrap shrink">
                      <el-checkbox class="fz14" label="全选" v-model="datas.selectAll" 
                      :indeterminate="datas.indeterminate" style="position: relative;top: 1px;"
                      @change="setSelecAll" :disabled="dataList.length==0"/>
                      <span class="fz14 q-pl-md color959AA3 row nowrap"><span>已选择</span> <span class="q-pl-xs">{{datas.SelectedDatas.length}}</span></span>
                    </div>
                    <div class="q-px-lg">
                      <div style="border-right: 1px solid #BABABA;height: 13px;">&nbsp;</div>
                    </div>
                    <el-button icon="CopyDocument" size="small" @click="BatchCopyTo()" :disabled="dataList.length==0">复制到</el-button>
                    <el-button icon="Expand" size="small" @click="BatchMoveFile()" :disabled="dataList.length==0">移动到</el-button>
                    <el-button icon="Delete" size="small" @click="BatchRemove()" :disabled="dataList.length==0">删除</el-button>
                    <span class="close-btn cursor-pointer column items-center flex-center q-pl-md" @click="datas.ControlsShow=false">
                      <IconClose :size="14"></IconClose>
                    </span>
                  </div>
                  
                </div>
              </div>
             </div>
          </div>
      </div>
      </div> 
    </div>
    <!-- 编辑分组 -->
      <NewEditCloudDisk
      v-if="dialogFormVisible" 
      :dialogType="dialogType" 
      :addEditMsg="addEditMsg"
      @close="close"
      @success="close(),dialogFormVisible=false,querySearchGroup()"></NewEditCloudDisk>
      <!-- 复制移动 -->
      <copyMove
      v-if="dialogCMVisible" 
      :dialogType="dialogType" 
      :DetailsId="addEditMsg.Id"
      :GroupId="GroupId"
      :GroupList="GroupAll"
      @close="close"
      @success="successCM"></copyMove>
    <!-- 预览图 -->
    <el-image-viewer 
      @close="() => { isViewerShow = false }" 
      v-if="isViewerShow" 
      :initial-index="currentImg"
      :url-list="srcList"></el-image-viewer>
      
</template>
  <script setup lang="ts">
  import { ref, reactive, watch, provide, inject, onMounted, PropType, nextTick, computed } from "vue";
  import type { ElMessage,ElImage,DropdownInstance,ElLoading } from "element-plus";
  import { ArrowLeft,CopyDocument } from "@element-plus/icons-vue";
  import CloudDiskService from "@/services/CloudDiskService";
  import { injectKeyTemplate } from "@/types/injectKey";
  import { useSellTemplateStore, useScreenStore, useUserStore } from "@/store";
  import { storeToRefs } from 'pinia'
  import { ApiResult } from "@/configs/axios";
  import NewEditCloudDisk from '@/components/CloudDisk/NewEdit'
  import copyMove from '@/components/CloudDisk/copyMove'
  import { noDataImg } from "@/utils/common";
  import { useRouter } from "vue-router";
  import AliyunUpload from '@/utils/upload/aliyun'
  import { getLastMonthDate } from "@/utils/time";

  import cellList from './cellList'
  import waterfallFlowList from './waterfallFlowList'
  import list from './list'

  const { token, userInfo } = storeToRefs(useUserStore())
  const router = useRouter()
  const currentRoute = router.currentRoute.value
  const parmas = ref({} as any)
  parmas.value = currentRoute.params
  const props = defineProps({
    isPersonage: '' as any,
  })
  const RefreshLoading = ref(false)
  let time = getLastMonthDate()
  const queryObj = reactive({
    pageIndex: 1,
    pageSize: 100,
    CloudGroupId: '',
    FileName: '',
    total: 0,
    layout: 1,//布局
    QFileType: [],//格式
    QStartTime: '',
    QEndTime: '',
    QOrderFiled: 1,//排序字段(1-创建时间，2-文件大小 3文件名称
    QOrderBy: 2,//1-升序，2-倒序
    QCreateBy: '',//上传人员
    QFileName: '',
  })
  
  const dateArr = ref([] as any)
  if(props.isPersonage) queryObj.CloudGroupId = parmas.value.id
  const loading = ref(false as any)
  const dataList = ref([] as Array<any>);
  const currentRootDom = ref()
  const GName= ref('')
  const addEditMsg = reactive({
      Id: '',
      GName: '',
      SortNum: null,
  })
  const dialogFormVisible = ref(false)
  const dialogType = ref(0)
  const loadingGroup = ref(false)
  const GroupList = ref([] as any)
  const GroupAll = ref([] as any)
  const imgDiskRef = ref<any>()
  const editorTarget = ref('')
  const nickNam = ref(''||  Number)
  const GroupId = ref(''|Number)
  const dialogCMVisible = ref(false)
  const editLoading = ref(false)
  
  const currentImg = ref(-1)
  const srcList = ref([] as Array<any>)
  const isViewerShow = ref(false);

  const currentSearchType = ref(0)

  const dropdownSort = ref<DropdownInstance>()
  const dropdownLayout = ref<DropdownInstance>()
  const dropdownDade = ref()

  const sortType = ref([
    {Name: '添加时间',ID:1,check:true},
    {Name: '文件大小',ID:2,check:false},
    {Name: '文件名称',ID:3,check:false},
  ])
  const sortTypeUD = ref([
    {Name: '升序',ID:1,check:false},
    {Name: '降序',ID:2,check:true},
  ])
  const layoutType =  ref([
    {Name: '宫格',ID:1,check:false},
    {Name: '瀑布流',ID:2,check:false},
    {Name: '列表',ID:3,check:false},
  ])

  const datas = reactive({
    selectAll: false,
    SelectedDatas: [] as Array,
    ControlsShow: true,// 批量操作显示
    indeterminate: false,// 未全选状态
    IdList: [] as any,
  })

  const formatType = ref([] as any)
  const formatTypeAll = ref([] as any)

  const CreateLoading = ref(false)
  const CreateList = ref([] as any)

  layoutType.value.forEach(x=>{
    if(x.ID==queryObj.layout) x.check = true
  })
  const loadingInstance = ref<any>(null)

  const positionList = reactive({
      is_show_mask: false,
      box_screen_left: 0,
      box_screen_top: 0,
      start_x: 0,
      start_y: 0,
      end_x: 0,
      end_y: 0
  })
  //分别计算遮罩层的位置，大小
  const  mask_width = computed(()=> {
      return `${Math.abs(positionList.end_x - positionList.start_x)}px;`;
  })
  const  mask_height = computed(()=> {
      return `${Math.abs(positionList.end_y - positionList.start_y)}px;`;
  })
  const mask_left = computed(() =>{
      return `${Math.min(positionList.start_x, positionList.end_x) - positionList.box_screen_left}px;`;
  })
  const mask_top = computed(()=> {
      return `${Math.min(positionList.start_y, positionList.end_y) - positionList.box_screen_top}px;`;
  })

  //鼠标按下事件
  const handleMouseDown = (event)=> {
      if(queryObj.layout==3) return
      positionList.is_show_mask = true;
      positionList.start_x = event.clientX;
      positionList.start_y = event.clientY;
      positionList.end_x = event.clientX;
      positionList.end_y = event.clientY;
      document.body.addEventListener("mousemove", handleMouseMove); //监听鼠标移动事件
      document.body.addEventListener("mouseup", handleMouseUp); //监听鼠标抬起事件
      if (event.button === 0) {
          event.preventDefault();
      }
  }

  const handleMouseMove = (event) => {
      positionList.end_x = event.clientX;
      positionList.end_y = event.clientY;
  }

  const handleMouseUp = () => {
      document.body.removeEventListener("mousemove", handleMouseMove);
      document.body.removeEventListener("mouseup", handleMouseUp);
      positionList.is_show_mask = false;
      handleDomSelect();
      resSetXY();
  }
  const handleDomSelect = () => {
      const dom_mask = window.document.querySelector(".mask");
      //getClientRects()每一个盒子的边界矩形的矩形集合
      const rect_select = dom_mask.getClientRects()[0];
      // console.log(rect_select);
      const add_list = [];
      const del_list = [];
      document.querySelectorAll(".CloudDisk-R-Box").forEach((node, index) => {
          const rects = node.getClientRects()[0];
          if (collide(rects, rect_select) === true) {
              if (datas.SelectedDatas.includes(dataList.value[index])) {
                  dataList.value[index].check = !dataList.value[index].check
                  del_list.push(dataList.value[index]);
              } else {
                  dataList.value[index].check = !dataList.value[index].check
                  add_list.push(dataList.value[index]);
              }
          }
      });
      datas.SelectedDatas = datas.SelectedDatas.concat(add_list).filter((item) => !del_list.includes(item));
      newDatasSelected()
  }
  //比较checkbox盒子边界和遮罩层边界最大最小值
  const collide = (rect1, rect2) => {
      const maxX = Math.max(rect1.x + rect1.width, rect2.x + rect2.width);
      const maxY = Math.max(rect1.y + rect1.height, rect2.y + rect2.height);
      const minX = Math.min(rect1.x, rect2.x);
      const minY = Math.min(rect1.y, rect2.y);
      return maxX - minX <= rect1.width + rect2.width && maxY - minY <= rect1.height + rect2.height;
  }

  //清除
  const resSetXY = () => {
      positionList.start_x = 0;
      positionList.start_y = 0;
      positionList.end_x = 0;
      positionList.end_y = 0;
  }

  const remoteMethod = async (query: string) => {
    if (query) {
      CreateLoading.value = true
      const response = await CloudDiskService.GetEmpByEmpNameKey(query);
      if (response.data.resultCode==ApiResult.SUCCESS) {
        CreateList.value = response.data.data
      }
      CreateLoading.value = false
    } else {
      
    }
  }

  const SearchCloudInfo = () => {
    if(queryObj.QFileName) formatType.value = formatTypeAll.value.filter((item) => {
          return item.FileFormat&&item.FileFormat.toLowerCase().includes(queryObj.QFileName.toLowerCase())
        })
    else formatType.value = formatTypeAll.value
  }

  const getCloudInfo = async () => {
    let QUserType = 0
    if(props.isPersonage) QUserType = 2
    const response = await CloudDiskService.GetPPTistCloudInfoFileFormatCount(QUserType);
    if (response.data.resultCode==ApiResult.SUCCESS) {
      formatType.value = response.data.data.filter(x=> {return x.FileFormat})
      formatTypeAll.value = response.data.data.filter(x=> {return x.FileFormat})
    }
  }

  const ClearOption = () =>{
    datas.IdList = []
    datas.SelectedDatas = []
    datas.selectAll = false
    datas.indeterminate = false
  }

  const successCM = (type:any) =>{
    if(type){
      ClearOption()
    }
    close()
    dialogCMVisible.value = false
    querySearchGroup()
    refreshHandler()
  }
  const BatchCopyTo = () => {
    if(datas.IdList.length==0) return ElMessage.warning({
            showClose: true,
            message: `请勾选需要复制的图`,
        })
    addEditMsg.Id = datas.IdList
    GroupId.value = ''
    dialogType.value = 1
    dialogCMVisible.value = true
  }

  const BatchMoveFile = () => {
    if(datas.IdList.length==0) return ElMessage.warning({
            showClose: true,
            message: `请勾选需要移动的图`,
        })
    addEditMsg.Id = datas.IdList
    GroupId.value = ''
    dialogType.value = 2
    dialogCMVisible.value = true
  }

  const BatchRemove = () => {
    if(datas.IdList.length==0) return ElMessage.warning({
            showClose: true,
            message: `请勾选需要删除的图`,
        })
    let text = ''
    let mobel = ''
    let material = ''
    let mobelTisp = '模板图会影响模板正常使用，将无法恢复'
    let findCanDelete = datas.SelectedDatas.find(y=> y.IsCanDelete)
    let findObj = datas.SelectedDatas.find(y=> !y.IsCanDelete)
    if(findCanDelete) mobel = `模板图`
    if(findObj) material = '素材图'
    text = `删除${mobel&&material?''+mobel+'、':mobel&&!material?mobelTisp:''}${material}${mobel&&material?'，删除'+mobelTisp:''}，是否确定?`
    ElMessageBox.confirm(
        `${text}`,
        '提示',
        {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        }
    ).then(async () => {
        try {
          loading.value = true
            let dataRes = await CloudDiskService.BatchRemoveCloudInfo(datas.IdList)
            if (dataRes.data.resultCode==ApiResult.SUCCESS) {
              ClearOption()
              querySearchGroup()
              refreshHandler()
            }
          loading.value = false
        } catch (error) {}
    }).catch(() => {})
  }

  const newDatasSelected = () =>{
    if(datas.SelectedDatas.length==0) {
      for(let i=0;i<dataList.value.length;i++){
        dataList.value[i].check = false
      }
      datas.selectAll = false
      datas.indeterminate = false
    }else if(datas.SelectedDatas.length>0){
      if(dataList.value.length==datas.SelectedDatas.length){
        for(let i=0;i<dataList.value.length;i++){
          dataList.value[i].check = true
        }
        datas.selectAll = true
        datas.indeterminate = false
      }else if(dataList.value.length>datas.SelectedDatas.length){
        for(let i=0;i<dataList.value.length;i++){
          let x = dataList.value[i]
          let findObj = datas.SelectedDatas.find(y=> y.DetailsId==x.DetailsId)
          if(findObj) dataList.value[i].check = true
        }
        datas.indeterminate = true
      }
    }
  }

  const MultipleChoice = (row:Array) =>{
    datas.SelectedDatas = row
    if(datas.SelectedDatas.length>0) datas.ControlsShow = true
    newDatasSelected()
  }

  const setSelecAll = () => {
    if(datas.selectAll){
      datas.SelectedDatas = []
      for(let i=0;i<dataList.value.length;i++){
        dataList.value[i].check = true
        datas.SelectedDatas.push(dataList.value[i])
      }
      datas.indeterminate = false
    }else if(datas.indeterminate){
      datas.SelectedDatas.forEach(x=>{
        dataList.value.forEach(y=>{
          if(x.DetailsId==y.DetailsId) y.check = true
        })
      })
    }else{
      for(let i=0;i<dataList.value.length;i++){
        dataList.value[i].check = false
      }
      datas.SelectedDatas = []
      datas.indeterminate = false
    }
    if(datas.SelectedDatas.length>0) datas.IdList = datas.SelectedDatas.map(x=>{ return x.DetailsId})
  }

  const getDate = () => {
    if(dateArr.value&&dateArr.value.length>0){
      queryObj.QStartTime = dateArr.value[0]
      queryObj.QEndTime = dateArr.value[1]
    }else{
      queryObj.QStartTime = ''
      queryObj.QEndTime = ''
    }
    refreshHandler()
  }
  const OpenDropdown = () =>{
    if(currentSearchType.value==3)dropdownSort.value.handleOpen()
  }
  const setDropdown = (item:any,type:Number) =>{
    if(type==1||type==2){
      if(type==1){
        item.check = !item.check
        sortType.value.forEach(x=>{
          if(x.ID!=item.ID) x.check = false
        })
        queryObj.QOrderFiled = item.ID
      }else{
        item.check = !item.check
        sortTypeUD.value.forEach(x=>{
          if(x.ID!=item.ID) x.check = false
        })
        queryObj.QOrderBy = item.ID
      }
      refreshHandler()
    }
    
    if(type==3){
      const loadingObj = ElLoading.service({
        text:'正在切换',
        lock:true
      })
      item.check = !item.check
      queryObj.layout = item.ID
      layoutType.value.forEach(x=>{
          if(x.ID!=item.ID) x.check = false
      })
      let time = 300
      if(dataList.value.length>50) time = 3000
      setTimeout(()=>{
        loadingObj.close()
      },time)
      resSetXY()
    }
    
  }
  const changeDrop = (type:Number) =>{
    if(currentSearchType.value==type) currentSearchType.value = 0
    else currentSearchType.value = type
    if(currentSearchType.value==2) dropdownDade.value.handleOpen()
  }
  const getImg = (item:any,index:Number) => {
    currentImg.value = index
    isViewerShow.value = true
  }

  const CopyTo = (row:any) =>{
    addEditMsg.Id = row.DetailsId
    GroupId.value = row.CloudGroupId
    dialogType.value = 1
    dialogCMVisible.value = true
  }
  const MoveFile = (row:any) =>{
    addEditMsg.Id = row.DetailsId
    GroupId.value = row.CloudGroupId
    dialogType.value = 2
    dialogCMVisible.value = true
  }
  const setCloudNameHandler = async (target:any)=>{
    if(editLoading.value || nickNam.value=='' || !nickNam.value) return
    editLoading.value = true
    let params = {
      Id: target.DetailsId,
      FileName: nickNam.value
    }
    let dataRes = await CloudDiskService.UpdateCloudInfoName(params)
    if (dataRes.data.resultCode==ApiResult.SUCCESS) {
      refreshHandler()
    }
    editLoading.value = false
  }
  const setNameHandler = (target:any) =>{
    if(target){
      editorTarget.value = target.DetailsId
      nickNam.value = target.FileName
    }else{
      editorTarget.value = ''
      nickNam.value = ''
    }
  }
  // 删除
const deleteImg = (item:any) => {
    let text
    if(item.IsCanDelete) text = '删除此图会影响模板正常使用，将无法恢复，是否确定?'
    else text = '此操作将删除该图，是否确定?'
  ElMessageBox.confirm(
      `${text}`,
      '提示',
      {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      }
  ).then(async () => {
      try {
        loading.value = true
        let dataRes = await CloudDiskService.RemovePPTCloudInfo(item.DetailsId)
        loading.value = false
        if (dataRes.data.resultCode==ApiResult.SUCCESS) {
          refreshHandler()
        }
        
      } catch (error) {}
  }).catch(() => {})
  
}


const addEditGroup = () =>{
    dialogFormVisible.value = true
    dialogType.value = 1
}

const close = () =>{
    addEditMsg.Id = ''
    addEditMsg.GName = ''
    addEditMsg.SortNum = null
    dialogFormVisible.value = false
    dialogCMVisible.value = false
    GroupId.value = ''
    dialogType.value = 0
}

const EditGroup = (item:any) =>{
    let data = JSON.parse(JSON.stringify(item))
    addEditMsg.Id = data.Id
    addEditMsg.GName = data.GName
    addEditMsg.SortNum = data.SortNum
    dialogFormVisible.value = true
    dialogType.value = 2
}

const insertImageElement = async (files: FileList) => {
    loadingInstance.value = ElLoading.service({
        text:'收集需要处理的图片'
    })
    for(let i=0;i<files.length;i++){
      loadingInstance.value.text = `当前图片处理进度：${i+1} / ${files.length}`
      let name = files[0].name.split('.')
      const hash = await calculateFileHash(files[i])
      if(hash!='') {
          await checkedUploadFileExsit(files[i],hash)
      }else{
          await uoloadFileToService(files[i]) 
      }
    }
    loadingInstance.value.close()
    loadingInstance.value = null
    
}
const checkedUploadFileExsit = async (file:File,hash:any)=>{
    let parms = {
        fname: file.name,
        gid: queryObj.CloudGroupId,
        hi: hash
    }
    const dataRes = await CloudDiskService.CheckCloudInfo(parms)
    if (dataRes.data.resultCode==ApiResult.SUCCESS) {
        queryObj.CloudGroupId = ''
        queryObj.FileName = dataRes.data.data.SourceFileName
        refreshHandler()
    } else {
        if(dataRes.data.message=='不存在此文件!') await uoloadFileToService(file)  
    }
}
const uoloadFileToService = async (file:File)=>{
    let parms = {
        isppt: '1',
        uid: token.value,
        gid: queryObj.CloudGroupId
    }
    let filePath="tripImg/";
    let url  = await AliyunUpload.UploadCloudDisk(file, filePath, parms);
    if(url) {
        querySearchGroup()
        refreshHandler()
    }
}

const calculateFileHash = (file:File, algorithm = 'SHA-256') => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (event) => {
        if(event && event.target && event.target.result){
            const buffer:any = event.target.result;
            if(crypto && crypto.subtle && crypto.subtle.digest){
                crypto.subtle.digest(algorithm, buffer)
                .then(hashBuffer => {
                    const hashArray = Array.from(new Uint8Array(hashBuffer));
                    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
                    resolve(hashHex);
                })
                .catch(error => resolve(''));
            }else{
                resolve('')
            }
        }else{
            resolve('')
        }
        
    };
    reader.onerror = reject;
    reader.readAsArrayBuffer(file); // Read only the first 1MB of the file
  });
}


// 删除
const deleteGroup = async (item:any) => {
  ElMessageBox.confirm(
      `此操作将删除该分组，是否确定?`,
      '提示',
      {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      }
  ).then( async () => {
    loadingGroup.value = true
    try {
        let dataRes = await CloudDiskService.RemovePPTCloudGroup(item.Id)
        loadingGroup.value = false
        if (dataRes.data.resultCode == 1) {
            querySearchGroup()
        }
    } catch (error) {}
  }).catch(() => {})
  
}

const SearchGroup = () => {
    if(GName.value=='') querySearchGroup()
}
const querySearchGroup = async () =>{
    if(loadingGroup.value) return
    loadingGroup.value = true
    try {
        let datasRes
        if(props.isPersonage) datasRes = await CloudDiskService.GetPPTCloudList(GName.value);
        else datasRes = await CloudDiskService.GetPPTCloudLists(GName.value);
        if (datasRes.data.resultCode==ApiResult.SUCCESS) {
            GroupList.value = datasRes.data.data.list
            GroupList.value.unshift({
                Id: '',
                GName: '全部',
                RecordNum: datasRes.data.data.TotalNum
            })
            if(!GName.value) GroupAll.value = GroupList.value
        }
        loadingGroup.value = false
    } catch (error) {
        loadingGroup.value = false
    }
    
}

const SearchImg = () =>{
    if(queryObj.FileName=='') refreshHandler()
}
  const refreshHandler = (row:any) => {
    if(row&&(row.Id||row.Id=='')) {
      if(row.Id==queryObj.CloudGroupId) return
      queryObj.CloudGroupId = row.Id
      ClearOption()
    }
    RefreshLoading.value = true;
    queryObj.pageIndex = 1;
    srcList.value = []
    
    querySearchHandler();
  };

  const querySearchHandler = async () => {
    loading.value = true;
    try {
      if (queryObj.pageIndex == 1) dataList.value = [];
      let pageRes
      if(props.isPersonage) pageRes = await CloudDiskService.GetPPTCloudInfoPage(queryObj);
      else pageRes = await CloudDiskService.GetPPTCloudInfoPages(queryObj);
      if (pageRes.data.resultCode==ApiResult.SUCCESS) {
        let arrList = function (list) {
          list.forEach((x) => {
            x.check = false;
          });
        };
        arrList(pageRes.data.data.pageData);
        let imgs = pageRes.data.data.pageData.map(x=> x.FilePath)
        dataList.value = dataList.value.concat(pageRes.data.data.pageData);
        srcList.value = srcList.value.concat(imgs);
        queryObj.pageCount = pageRes.data.data.pageCount;
        
      }
      loading.value = false;
      RefreshLoading.value = false;
    } catch (error) {
      ElMessage.error({
        message:'数据加载异常，请刷新页面'
      })
      loading.value = false;
      RefreshLoading.value = false;
    }
    setSelecAll()
    newDatasSelected()
  };
  const scrollingHandler = () =>{
    if(imgDiskRef.value && !loading.value){
        let maxHeight = imgDiskRef.value.scrollHeight - imgDiskRef.value.offsetHeight
        let scrollTop = imgDiskRef.value.scrollTop
        if(maxHeight - scrollTop<=0 && queryObj.pageCount > queryObj.pageIndex) {
            queryObj.pageIndex++
            querySearchHandler()
        }
    }
    
}
querySearchGroup()
querySearchHandler()
getCloudInfo()
onMounted(()=>{
  imgDiskRef.value.addEventListener("scroll", scrollingHandler);
})
  watch(()=>datas.SelectedDatas,(n,o)=>{
    datas.IdList = []
    if(n.length>0) {
      datas.IdList = datas.SelectedDatas.map(x=>{ return x.DetailsId})
      datas.ControlsShow = true
    }
  })
  </script>
  <style lang="scss" scoped>
  .CloudDisk-R-Center{
    flex-wrap: wrap;
  }
    .CloudDisk-R-Date{
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      z-index: 0;
      opacity: 0;
    }
  .figureTBOX.active{
    color: #3556F9;
  }
  .CloudDisk-R-header {
    padding: 0 0 0 20px;
  }
  .CloudDisk-R-header::v-deep(.el-button){
    height: auto;
    padding: 10px;
    background-color: rgba(23,23,23,0);
    border: rgba(23,23,23,0);
  }
  .CloudDisk-R {
    overflow: hidden;
  }
  .CloudDisk-R-header .DiskRHActive::v-deep(.el-button){
    height: auto;
    padding: 10px;
    background-color: #E8E8E8;
    border: #E8E8E8;
  }
    .CloudDisk-R-inquire::v-deep(.el-button){
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    /* height: 36px; */
}
.CloudDisk-L{
    border-right: 1px solid #E9E9E9;
    padding: 0 20px 22px 0;
}
.CloudDisk-L-inquire{
    margin-bottom: 20px;
}
.CloudDisk-L-inquire .el-input{
    width: 112px;
    /* height: 36px; */
}
.CloudDisk-L-inquire::v-deep(.el-button){
    /* height: 36px; */
    margin-left: 20px;
}
.CloudDisk-L-Title:first-child{
}
.CloudDisk-L-Title{
    padding: 0 10px;
    font-weight: 400;
    font-family: PingFang SC;
    border-radius: 8px;
    margin-bottom: 3px;
}
.CloudDisk-L-Title span:first-child{
    width: 108px;
    padding: 11px 0;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.CloudDisk-L-Title span:last-child{
    color: #BBC7C3;
}
.CloudDisk-L-TitleR{
  padding: 11px 0;
}
.CloudDisk-L-Title-M{
    width: 24px;
    height: 24px;
    border-radius: 4px;
    margin-right: 6px;
    border: 0 !important;
}
.CloudDisk-L-Title-M:hover{
  background: #BED0FB;
  color: #fff;
}
.CloudDisk-L-Title.active{
    color: #3556F9 ;
    background: #EEF3FF;
}
.CloudDisk-L-Title.active .CloudDisk-L-Title-M{
    /* background: #BED0FB; */
}
.CloudDisk-L-Title:hover{
    background: #EEF3FF ;
}
.CloudDisk-L-Title:hover span:first-child{
    color: #3556F9 ;
}
.CloudDisk-R-inquire{
    padding-left: 24px;
    padding-right: 20px;
}
.CloudDisk-R-inquire .el-input{
    width: 30vw;
    padding-bottom: 10px;
    /* height: 36px; */
}

.CloudDisk-R-Plus{
    width: 85px;
    height: 85px;
    border-radius: 8px;
    border: 2px dashed #CECECE;
    color:#cecece;
}
.CloudDisk-R-Plus:hover{
    border-color: #000000;
    color:#000000;
}
.CloudDisk-R-Plus .el-icon{
    margin-top: 13px;
}
.CloudDisk-R-Plus span{
    /* font-family: PingFang SC; */
    font-weight: 400;
    font-size: 14px;
    /* color: #CECECE; */
}
.CloudDisk-L-Center{
    height: 95%;
    overflow-y: scroll;
}
.CloudDisk-RBF{
  position: fixed;
  bottom: 10px;
  /* 515px */
  left: 232px;
  right: 232px;
  z-index: 2;
}
.CloudDisk-RBFCenter{
  margin: auto;
}
.CloudDisk-RBFbj{
  background: #fff;
  box-shadow: 0px 0px 13px 0px #eee;
  border-color:#eee;
  padding: 5px 15px;
}
.CloudDisk-RBFbj .close-btn:hover{
  color: $themeColor;
}
.mask {
    position: absolute;
    background: #409eff;
    opacity: 0.4;
    z-index: 100;
}

  </style>
  