<template>
    <div class="CloudDisk-form row">
        <div class="CloudDisk-L">
            <div class="row CloudDisk-L-inquire">
                <el-input v-model="GName" 
                placeholder="搜索分组名称" @keyup.enter="querySearchGroup"
                @input="SearchGroup">
                </el-input>
                <el-button type="primary" @click="addEditGroup">添加</el-button>
            </div>
            <div class="CloudDisk-L-Center fz14" v-loading="deleteLoading">
                <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="请输入图片名称搜索" @keyup.enter="Search"
                @input="SearchImg">
                </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>
                            <span class="title block">
                                <el-tooltip effect="dark" :content="item.FileName" placement="top">
                                    {{item.FileName}}
                                </el-tooltip>
                            </span>

                        </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
                small="small"
                layout="prev, pager, next"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                />
            </div>
           
        </div>
    </div>
    <el-dialog v-model="dialogFormVisible" 
    :title="dialogTitle" width="340" @close="close">
        <div>
            <el-input v-model="addEditMsg.GName" 
            placeholder="请输入分组名称">
            </el-input>
            <el-input class="q-pt-lg" type="Number" v-model="addEditMsg.SortNum" 
            placeholder="排序">
            </el-input>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="setGroup" :loading="setLoading">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
</template>
<script lang="ts" setup>
import { Plus, Top, Bottom, Delete, Edit  } from "@element-plus/icons-vue";
import { reactive, ref, onMounted, watch} from "vue";
import CloudDiskService from '@/services/CloudDiskService'
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
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";

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

const dialogFormVisible = ref(false)
const dialogTitle = ref('')
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 GroupList = ref([] as any)

const setLoading = ref(false)
const deleteLoading = ref(false)
const deleteImgLoading = ref<any>(null)
const props = defineProps({
    active: '' as any,
    show: false as Boolean
})

const GroupObj = ref({} as any)

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

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

const setImg = (item:any) => {
    ImgId.value = 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 || hash=='') {
        ElMessage.error({message:'文件校验失败，请重试'})
        loadingObj.close()
        return;
    }
    let parms = {
        fname: name[0],
        gid: queryObj.CloudGroupId,
        hi: hash
    }
    let dataRes = await CloudDiskService.CheckCloudInfo(parms)
    if (dataRes.data.resultCode==ApiResult.SUCCESS) {
        queryObj.CloudGroupId = ''
        queryObj.FileName = dataRes.data.data.SourceFileName
        Search()
    }else{
        //TODO: 实现校验HASH值是否存在，如果不存在，才调用下面的这个方法。
      if(dataRes.data.message=='不存在此文件!') await uoloadFileToService(files[0])  
    }
    // await uoloadFileToService(files[0])
    loadingObj.close()
}

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) 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;
            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 => reject(error));
        }else{
            reject('')
        }
        
    };
    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
          let dataRes = await CloudDiskService.RemovePPTCloudInfo(item.DetailsId)
          if (dataRes.data.resultCode==ApiResult.SUCCESS) {
                querySearchHandler()
          }
        loading.value = false
      } catch (error) {}
  }).catch(() => {})
  
}


const addEditGroup = () =>{
    dialogFormVisible.value = true
    dialogTitle.value = '添加分组名称'
}

const setGroup = async () =>{
    if(!addEditMsg.GName) return ElMessage.warning({
          showClose: true,
          message: `请输入分组名称`,
      })
    setLoading.value = true
    let pageRes = await CloudDiskService.SetPPTCloudGroup(addEditMsg);
    if (pageRes.data.resultCode==ApiResult.SUCCESS) {
        dialogFormVisible.value = false
        querySearchGroup()
    }
    setLoading.value = false
}

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

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
    dialogTitle.value ='编辑分组名称'
}

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

const SearchGroup = () => {
    if(GName.value=='') querySearchGroup()
}
const querySearchGroup = async () =>{
    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
            })
        }
    } catch (error) {
        
    }
}
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 () =>{
    loading.value = true
    try {
        // if(queryObj.pageIndex == 1) dataList.value =[]
        let pageRes = await CloudDiskService.GetPPTCloudInfoPage(queryObj);
        if (pageRes.data.resultCode==ApiResult.SUCCESS) {
            let arrList = function(list){
                list.forEach(x=>{
                    x.checked = false
                })
            }
            arrList(pageRes.data.data.pageData)
            dataList.value = pageRes.data.data.pageData //dataList.value.concat(pageRes.data.data.pageData);
            queryObj.pageCount = pageRes.data.data.pageCount;
            total.value = pageRes.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()
}

querySearchGroup()
querySearchHandler()
onMounted(()=>{
    // imgDiskRef.value.addEventListener("scroll", scrollingHandler);
})
</script>
<style lang="scss" scoped>
.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;
}

.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: -2px;
    width: 20px;
    height: 20px;
    background: #fff;
    border:1px solid #AFAFAF;
    text-align: center;
    color:#AFAFAF;
    border-radius: 50%;
    z-index: 3;
    opacity: 0;
}
.CloudDisk-R-Box.active2:hover .close-btn{
    opacity: 1;
}
</style>