<template>
    <div class="CloudDisk-form row">
        <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 type="primary" @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" :key="index" @click.stop="Search(item)"
                :class="[queryObj.CloudGroupId==item.Id?'active':'']">
                    <span class="block">{{item.GName}}</span>
                    <div class="row">
                        <template v-if="item.Id">
                            <el-dropdown class="q-pl-lg" trigger="hover">
                                <div class="CloudDisk-L-Title-M row items-center flex-center">
                                    <el-icon size="16" :color="GroupId==item.Id?'#3556F9':'#b1b7cf'"><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 v-else></div>
                       <span v-if="item.RecordNum>0">{{item.RecordNum?item.RecordNum:''}}
                        <!-- <template v-if="!item.RecordNum">&nbsp;</template> -->
                       </span> 
                    </div>
                    
                </div>
            </div>
        </div>
        <div class="CloudDisk-R grow">
            <div class="row CloudDisk-R-inquire">
                <!-- <el-input v-model="queryObj.FileName" 
                placeholder="请输入图片名称搜索" clearable @keyup.enter="Search"
                @input="SearchImg" @change="SearchImg">
                </el-input> -->
                <el-input v-model="queryObj.FileName" placeholder="请输入图片名称搜索" clearable @keyup.enter="Search"
                @input="SearchImg">
                    <template #append>
                        <el-button type="primary" style="color: white;" @click="Search">搜索</el-button>
                    </template>
                </el-input>
            </div>
            <div ref="imgDiskRef" style="height:  420px;padding-top: 20px;">
                <div class="CloudDisk-R-Center row" v-loading="loading">
                    <FileInput @change="files => insertImageElement(files)">
                       <div class="CloudDisk-R-Box">
                        <div class="CloudDisk-R-Plus column items-center cusor-pointer">
                            <el-icon class="el-input__icon" size="30px" title="">
                                <Plus/>
                            </el-icon>
                            <span>添加图片</span>
                        </div>
                        </div> 
                    </FileInput>
                    
                    <template v-for="(item,index) in dataList">
                        <div class="CloudDisk-R-Box cursor-pointer" 
                        :class="[ImgId==item.DetailsId?'active':'active2']" @click="setImg(item)">
                            <div class="CloudDisk-R-Img">
                                <el-image :src="item.FilePath" style="width: 100%; height: 100%;"
                                fit="cover"/>
                                <!-- <el-image
                                    style="width: 80px; height: 80px"
                                    :src="item.FilePath"
                                    :zoom-rate="1.2"
                                    :max-scale="7"
                                    :min-scale="0.2"
                                    :preview-src-list="[item.FilePath]"
                                    :initial-index="4"
                                    fit="cover"
                                    /> -->
                                <!-- <span class="close-btn cursor-pointer column items-center flex-center"
                                @click.stop="deleteImg(item)">
                                    <IconClose :size="10"></IconClose>
                                </span> -->
                                <!-- <div class="CloudDiskIcon row flex-between">
                                    <div class="CloudDiskIconC CloudDiskIconCL">
                                        <div class="CloudDiskOpa CloudDiskOpaL"></div>
                                        <el-icon size="15px" theme="filled" class="CloudDiskAbsolute CloudDiskAbsoluteL cusor-pointer" @click.stop="deleteImg(item)">
                                            <Delete></Delete>
                                        </el-icon>
                                    </div>
                                    <div class="CloudDiskIconC CloudDiskIconCR">
                                        <div class="CloudDiskOpa CloudDiskOpaR"></div>
                                        <el-icon size="15px" theme="filled" class="CloudDiskAbsolute CloudDiskAbsoluteR cusor-pointer" @click.stop="ImgDetails(item,index)">
                                            <View></View>
                                        </el-icon>
                                    </div>
                                </div> -->
                            </div>
                            <span class="title block">
                                <el-tooltip effect="dark" :content="item.FileName" placement="bottom">
                                    {{item.FileName}}
                                </el-tooltip>
                            </span>
                            <div class="MoreClickBox">
                                <div class="MoreClick row items-center"><el-icon size="13" @click.stop="clickMore(index)"><MoreFilled /></el-icon></div>
                                <div class="MoreClickCenter column" v-if="ShowMessage&&currentMore==index">
                                        <div class="cloudDownName microsoft">
                                            <div class="col row user-nickname" style="color:#000;" v-if="editorTarget!=item.DetailsId"> 
                                                <span class="grow text-left">{{item.FileName}}</span>
                                                <IconPencli size="14" class="q-ml-md cusor-pointer editor-pencli" @click.stop="setNameHandler(item)"></IconPencli>
                                            </div>
                                            <div class="col row items-center" v-else>
                                                <el-input v-model="nickNam" placeholder="请输入用户昵称" size="small" class="col" />
                                                <el-button link size="small" class="q-ml-sm" type="primary" @click.stop="setCloudNameHandler(item)"
                                                :loading="editLoading">确认</el-button>
                                                <el-button link size="small" style="margin-left: 5px;" @click.stop="setNameHandler">取消</el-button>
                                            </div>
                                        </div>
                                        <div class="cloudDownText row flex-between">
                                            <span>类型</span>
                                            <span>图片</span>
                                        </div>
                                        <div class="cloudDownText row flex-between">
                                            <span>格式</span>
                                            <span>{{item.FileName.split('.')[1]}}</span>
                                        </div>
                                        <div class="cloudDownText row flex-between" v-if="item.WithHeight">
                                            <span>尺寸</span>
                                            <span>{{item.WithHeight}} px</span>
                                        </div>
                                        <div class="cloudDownText cloudDownTextLin row flex-between">
                                            <span>大小</span>
                                            <span>{{item.FileSize}} kb</span>
                                        </div>
                                        <div class="common q-py-md microsoft">
                                            <div class="row items-center cloudDownControls" @click.stop="goTidyUp(item)">
                                                <el-icon size="15px" theme="filled">
                                                    <Menu></Menu>
                                                </el-icon>
                                                <span class="q-pl-md">整理文件</span>
                                            </div>
                                            <div v-if="ImgId!=item.DetailsId" class="row items-center cloudDownControls" @click.stop="deleteImg(item)">
                                                <el-icon size="15px" theme="filled">
                                                    <Delete></Delete>
                                                </el-icon>
                                                <span class="q-pl-md">删除</span>
                                            </div>
                                            <div class="row items-center cloudDownControls" @click.stop="ImgDetails(item,index)">
                                                <el-icon size="15px" theme="filled">
                                                    <View></View>
                                                </el-icon>
                                                <span class="q-pl-md">查看</span>
                                            </div>
                                        </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </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>
    </div>
      <NewEditCloudDisk
      v-if="dialogFormVisible" 
      :dialogType="dialogType" 
      :addEditMsg="addEditMsg"
      @close="close"
      @success="dialogFormVisible=false,querySearchGroup()"></NewEditCloudDisk>

      <el-image-viewer 
      @close="() => { isViewerShow = false }" 
      v-if="isViewerShow" 
      :initial-index="currentImg"
      :url-list="srcList"></el-image-viewer>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, watch, onBeforeUnmount} from "vue";
import CloudDiskService from '@/services/CloudDiskService'
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import { Plus, Top, Bottom, Delete, Edit, View  } from "@element-plus/icons-vue";
import FileInput from '@/components/FileInput.vue'
import { getImageDataURL } from '@/utils/image'
import AliyunUpload from '@/utils/upload/aliyun'
import { useUserStore } from "@/store";
import { storeToRefs } from 'pinia'
import { ApiResult } from "@/configs/axios";
import NewEditCloudDisk from './NewEdit'
import { openNewBlank } from '@/utils/common';

const { token, userInfo } = storeToRefs(useUserStore())

const dialogFormVisible = ref(false)
const dialogType = ref(0)
const queryObj = reactive({
    pageIndex: 1,
    pageSize: 11,
    CloudGroupId: '',
    FileName: '',
    total: 0
})
const total = ref(0)
const ImgId= ref('')
const GName= ref('')
const addEditMsg = reactive({
    Id: '',
    GName: '',
    SortNum: null,
})
const GroupId = ref(''|Number)
const imgDiskRef = ref<any>()
const dataList = ref([] as any)
const loading = ref(false)
const loadingGroup = ref(false)
const GroupList = ref([] as any)
const srcList = ref([] as any)

const props = defineProps({
    active: '' as any,
    show: false as Boolean
})

const GroupObj = ref({} as any)
const currentImg = ref(-1)
const isViewerShow = ref(false);
const nickNam = ref(''||  Number)
const editorTarget = ref('')
const editLoading = ref(false)
const ShowMessage = ref(false)
const currentMore = ref(0)

const emit = defineEmits<{
  (event: 'setImg'): void,
  (event: 'getImg'): void,
}>()

watch(() => props.active, () => {
    if(props.active!=2) ImgId.value = ''
})
watch(() => props.show, () => {
    if(!props.show) ImgId.value = ''
})

const goTidyUp = (row:any) => {
    openNewBlank(`/u/cloudDiskSpace`)
}

const clickMore = (index:Number) => {
    ShowMessage.value = true
    currentMore.value = index
    setNameHandler()
}

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) {
        querySearchHandler()
        editorTarget.value = ''
        nickNam.value = ''
    }
    editLoading.value = false
  }
const setNameHandler = (target:any) =>{
    if(target){
        editorTarget.value = target.DetailsId
        nickNam.value = target.FileName
    }else{
        editorTarget.value = ''
        nickNam.value = ''
    }
}

const ImgDetails = (item:any,index:Number) =>{
    currentImg.value = index
    isViewerShow.value = true
}
const setImg = (item:any) => {
    ImgId.value = item.DetailsId
    // setImgDefinition(item.DetailsId)
    emit('getImg',item.FilePath)
}

const insertImageElement = async (files: FileList) => {
    let name = files[0].name.split('.')
    const loadingObj = ElLoading.service({
        text:'正在上传图',
        lock:true
    })
    const hash = await calculateFileHash(files[0])
    if(hash!='') {
        await checkedUploadFileExsit(files[0],hash)
    }else{
        await uoloadFileToService(files[0]) 
    }
    loadingObj.close()
}
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
        Search()
    } 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()
        Search()
    }
}

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 deleteImg = (item:any) => {
    let text
    if(item.IsCanDelete) text = '删除此图会影响模板正常使用，将无法恢复，是否确定?'
    else text = '此操作将删除该图，是否确定?'
  ElMessageBox.confirm(
      `${text}`,
      '提示',
      {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      }
  ).then(async () => {
      try {
        loading.value = true
        const dataRes = await CloudDiskService.RemovePPTCloudInfo(item.DetailsId)
        loading.value = false
        if (dataRes.data.resultCode==ApiResult.SUCCESS) {
            querySearchHandler()
        }
      } catch (error) {}
  }).catch(() => {})
  
}


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

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

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 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 = await CloudDiskService.GetPPTCloudList(GName.value);
        if (datasRes.data.resultCode==ApiResult.SUCCESS) {
            GroupList.value = datasRes.data.data.list
            GroupList.value.unshift({
                Id: '',
                GName: '全部',
                RecordNum: datasRes.data.data.TotalNum
            })
        }
        loadingGroup.value = false
    } catch (error) {
        loadingGroup.value = false
    }
    
}
const SearchImg = () =>{
    if(queryObj.FileName=='') Search()
}
const Search = (item:any=null) =>{
    if(item) {
        queryObj.CloudGroupId = item.Id
        GroupObj.value = item
    }
    queryObj.pageIndex = 1
    querySearchHandler()
}

const querySearchHandler = async () =>{
    if(loading.value) return
    loading.value = true
    try {
        // if(queryObj.pageIndex == 1) dataList.value =[]
        const response = await CloudDiskService.GetPPTCloudInfoPage(queryObj);
        if (response.data.resultCode==ApiResult.SUCCESS) {
            let arrList = function(list){
                list.forEach(x=>{
                    x.checked = false
                })
            }
            arrList(response.data.data.pageData)
            dataList.value = response.data.data.pageData //dataList.value.concat(response.data.data.pageData);
            queryObj.pageCount = response.data.data.pageCount;
            srcList.value = dataList.value.map(x=>x.FilePath)
            total.value = response.data.data.count;
        }
        setTimeout(()=>{
            loading.value = false
        },300)
    } catch (error) {
        loading.value = false
    }
}

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()
        }
    }
    
}

const handleSizeChange = (val: number) => {
}
const handleCurrentChange = (val: number) => {
    queryObj.pageIndex = val
    querySearchHandler()
}
// 清晰度处理
const setImgDefinition = async (DetailsId:any) =>{
    try {
        const response = await CloudDiskService.ImgDefinition(DetailsId);
        if (response.data.resultCode==ApiResult.SUCCESS) {
            
        }
    }catch(err){}
}
querySearchGroup()
querySearchHandler()
onMounted(()=>{
    // imgDiskRef.value.addEventListener("scroll", scrollingHandler);
})
onMounted( () => {
    document.addEventListener('click', (e) => {
        if (ShowMessage.value&&!editorTarget.value) {
            ShowMessage.value = false
            setNameHandler()
        }
    });
})
onBeforeUnmount(() => {
    document.removeEventListener('click', () => {});
})
</script>
<style lang="scss" scoped>
.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 .el-button{
    /* height: 36px; */
    margin-left: 20px;
}
.CloudDisk-L-Title:first-child{
}
.CloudDisk-L-Title{
    padding: 11px 10px;
    font-weight: 400;
    font-family: PingFang SC;
    border-radius: 8px;
    margin-bottom: 3px;
}
.CloudDisk-L-Title span:first-child{
    width: 108px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.CloudDisk-L-Title span:last-child{
    color: #BBC7C3;
}
.CloudDisk-L-Title-M{
    width: 24px;
    height: 24px;
    border-radius: 4px;
    margin-right: 6px;
}
.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{
    /* padding: 22px 0 0 0; */
}
.CloudDisk-R-inquire{
    padding-left: 24px;
}
.CloudDisk-R-inquire .el-input{
    width: 100%;
    /* height: 36px; */
}
.CloudDisk-R-Center{
    flex-wrap: wrap;
}
.CloudDisk-R-Plus{
    width: 80px;
    height: 80px;
    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-R-Box{
    width: 80px;
    margin-left: 24px;
    margin-bottom: 24px;
    position: relative;
}
.CloudDisk-R-Img{
    width: 80px;
    height: 80px;
    margin-bottom: 9px;
    border-radius: 8px;
    overflow: hidden;
    border:2px solid transparent;
    position: relative;
}

.CloudDisk-R-Img .el-image{
    width: 76px;
    
}
.title{
    width: 80px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #000000;
}
.CloudDisk-L-Center{
    max-height: 420px;
    overflow-y: scroll;
}
.CloudDisk-R-Box.active .CloudDisk-R-Img{
    width: 80px;
    height: 80px;
    background: #8790F3;
    box-shadow: 0px 0px 13px 0px #0D3EBC;
    border-radius: 8px;
    border-color:#3556F9;
}
.CloudDisk-R-Box .close-btn{
    position: absolute;
    top: -10px;
    right: 0px;
    width: 20px;
    height: 20px;
    line-height: 15px;
    background: #fff;
    border:1px solid #AFAFAF;
    text-align: center;
    color:#AFAFAF;
    border-radius: 50%;
    z-index: 3;
    display: none;
}
.CloudDisk-R-Box.active2:hover .close-btn{
    display: block;
}

.MoreClickBox{
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 2;
    background: #fff;
    border-radius: 10px;
    text-align: center;
    padding: 0 3px;
}
.MoreClick .el-icon{
    color: #b1b7cf ;
}
.MoreClickBox:hover {
    background: #8790F3;
}
.MoreClick:hover .el-icon{
    color: #fff;
}
.MoreClickCenter{
    position: absolute;
    top: 22px;
    right: -20px;
    background: #fff;
    border-radius: 3px;
    box-shadow: 2px 2px 10px 2px #EEE;
}
.MoreClickCenter::after{
    content: '';
    width: 0;
    height: 0;
    position: absolute;
    right: 25px;
    top: -8px;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #FFF;
}
.cloudDownName{
  min-width: 200px;
  padding: 10px 20px 15px 20px;
  font-size: 14px;
  color: #000;
}
.cloudDownText{
  padding: 0 20px 10px 20px;
  font-size: 14px;
}
.cloudDownTextLin{
  border-bottom: 1px solid #F0F0F0;
}
.cloudDownControls{
    padding: 10px 10px;
}
.cloudDownControls:hover{
    background: #dedcff;
    color: $el-color-primary;
}
</style>