<template>
    <div class="column full-height" ref="currentRootDom">

        <div class="row items-center flex-between">
          <div class="text-dark text-weight-bolder">LOGO设置</div>
          <div class="row flex-center CloudDisk-R-inquire">
            
          </div>
          <!-- <FileInput @change="files => insertImageElement(files)">
            <el-button icon="Plus" class="ppt-button text-normal" type="primary">上传LOGO</el-button>
          </FileInput> -->
        </div>
        <div class="borders-light q-pa-lg rounded q-mt-xl row" style="width:600px;">
            <div class="col">
                <div class="text-dark text-weight-bold">行程LOGO设置</div>
                <div class="text-grey-8 f14 q-mt-md">LOGO开启后，系统将会根据尺寸自动替换行程模版中的Logo图片</div>
            </div>
            <div>
                <el-button type="info" class="ppt-button text-weight-bolder"
                    @click="showFormHandler">编辑LOGO</el-button>
                <div class="text-small q-mt-sm text-right"
                    :class="{ 'text-negative': !userInfo.IsEnableLogo || userInfo.IsEnableLogo == 0, 'text-secony': userInfo.IsEnableLogo && userInfo.IsEnableLogo == 1 }">当前{{
                        (!userInfo.IsEnableLogo || userInfo.IsEnableLogo == 0) ? '未启用' : '已启用' }}LOGO</div>
            </div>
        </div>
    </div>
    <el-dialog v-model="FormVisible" 
    style="width:560px;" :show-close="false"
     :close-on-click-modal="false" :close-on-press-escape="false">
        <template #header>
            <div class="row items-center">
                <div class="text-dark col" style="font-size: 18px;">LOGO信息设置</div>
                <div>
                    <span class="text-small q-mr-md">启用</span>
                    <el-switch v-model="IsEnable" class="short-switch"
                    :active-value="Number(1)"
                    :inactive-value="Number(0)"/>
                </div>
            </div>
            <div class="tip q-pt-md" style="color: #8c85e6;">
                注意：请按照显示的尺寸大小进行上传LOGO
            </div>
        </template>
        <div class="column" v-loading="loading">
            <div class="fz16" style="/*color: #564bec;*/">浅色LOGO</div>
            <div class="CloudDisk-R-Center row flex-between">
                <template v-for="(item,index) in acquiesceIMG">
                    <div v-if="item.FileType==1" style="position: relative;">
                        <div class="MoreClick row items-center cursor-pointer" @click.stop="showMore(index)"><el-icon size="13"><MoreFilled /></el-icon></div>
                        <div class="cloudDownText row flex-between" v-if="item.width">
                            <span>{{item.width}}*{{item.height}} px</span>
                        </div>
                        <div class="CloudDisk-R-Box cursor-pointer" style="background: #f1f2f4;">
                            <div v-if="!IsEnable" class="CloudDisk-R-Img row items-center flex-center">
                                <el-image :src="item.logo" style="width: auto; height: auto;"
                                fit="cover"/>
                            </div>
                            <FileInput v-else @change="files => insertImageElement(files,index)">
                                <div class="CloudDisk-R-Img row items-center flex-center">
                                    <el-image v-if="item.FilePath" :src="item.FilePath" style="width: auto; height: auto;"
                                    fit="cover"/>
                                    <el-button v-else icon="Top" link></el-button>
                                </div>
                            </FileInput>
                        </div>
                        <div class="MoreClickCenter" v-show="ShowMessage&&currentMore==index">
                            <div class="q-pa-xs microsoft">
                                <div class="row items-center cloudDownControls" @click="seeLogo(index)">
                                    <el-icon size="14px" theme="filled">
                                        <View></View>
                                    </el-icon>
                                    <span class="q-pl-md">默认LOGO</span>
                                </div>
                                <FileInput v-if="IsEnable" @change="files => insertImageElement(files,index)">
                                    <div class="row items-center cloudDownControls">
                                        <el-icon size="14px" theme="filled">
                                            <Upload v-if="!item.FilePath"></Upload>
                                            <EditPen v-else></EditPen>
                                        </el-icon>
                                        <span class="q-pl-md">企业LOGO</span>
                                    </div>
                                </FileInput>
                                <div v-if="item.FilePath" class="row items-center cloudDownControls" @click="seeLogo(index,1)">
                                    <el-icon size="14px" theme="filled">
                                        <View></View>
                                    </el-icon>
                                    <span class="q-pl-md">企业LOGO</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            <div class="fz16 q-pt-lg" style="/*color: #564bec;*/">深色LOGO</div>
            <div class="CloudDisk-R-Center row flex-between">
                <template v-for="(item,index) in acquiesceIMG">
                    <div v-if="item.FileType==2" style="position: relative;">
                        <div class="MoreClick row items-center cursor-pointer" style="background: #f1f2f4;" @click.stop="showMore(index)"><el-icon size="13"><MoreFilled /></el-icon></div>
                        <div class="cloudDownText row flex-between" v-if="item.width">
                            <span>{{item.width}}*{{item.height}} px</span>
                        </div>
                        <div class="CloudDisk-R-Box cursor-pointer">
                            <div v-if="!IsEnable" class="CloudDisk-R-Img row items-center flex-center">
                                <el-image :src="item.logo" style="width: auto; height: auto;"
                                fit="cover"/>
                            </div>
                            <FileInput v-else @change="files => insertImageElement(files,index)">
                                <div class="CloudDisk-R-Img row items-center flex-center">
                                    <el-image v-if="item.FilePath" :src="item.FilePath" style="width: auto; height: auto;"
                                    fit="cover"/>
                                    <el-button v-else icon="Top" link></el-button>
                                </div>
                            </FileInput>
                        </div>
                        <div class="MoreClickCenter" v-show="ShowMessage&&currentMore==index">
                            <div class="q-pa-xs microsoft">
                                <div class="row items-center cloudDownControls" @click="seeLogo(index)">
                                    <el-icon size="14px" theme="filled">
                                        <View></View>
                                    </el-icon>
                                    <span class="q-pl-md">默认LOGO</span>
                                </div>
                                <FileInput v-if="IsEnable" @change="files => insertImageElement(files,index)">
                                    <div class="row items-center cloudDownControls">
                                        <el-icon size="14px" theme="filled">
                                            <Upload v-if="!item.FilePath"></Upload>
                                            <EditPen v-else></EditPen>
                                        </el-icon>
                                        <span class="q-pl-md">企业LOGO</span>
                                    </div>
                                </FileInput>
                                <div v-if="item.FilePath" class="row items-center cloudDownControls" @click="seeLogo(index,1)">
                                    <el-icon size="14px" theme="filled">
                                        <View></View>
                                    </el-icon>
                                    <span class="q-pl-md">企业LOGO</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
        <template #footer>
            <el-button size="large" class="ppt-button" @click="()=>FormVisible=false">关闭设置</el-button>
            <el-button size="large" type="primary" class="ppt-button" @click="saveLogo()">保存设置</el-button>
        </template>
    </el-dialog>

    <el-image-viewer 
      @close="() => { isViewerShow = false }" 
      v-if="isViewerShow" 
      :initial-index="currentImg"
      :url-list="srcList"></el-image-viewer>

    <div v-if="isShowModal" class="modal-wrap">
        <div class="modal-mask"></div>
        <div class="modal-scroll-view">
            <div class="modal">
                <div class="row items-center">
                    <div class="text-dark col" style="font-size: 18px;">图片裁剪</div>
                    <div>
                        <el-button class="btn" @click="isShowModal = false">
                            取消
                        </el-button>
                        <el-button type="primary" class="ppt-button" @click="getResult">
                            裁剪
                        </el-button>
                    </div>
                </div>
                <div class="tip q-pt-md" style="color: #8c85e6;">
                    提示：滚动鼠标中键可以放大缩小图片
                </div>
                <div class="modal-content q-pt-lg">
                    <VuePictureCropper
                    :boxStyle="{
                        width: '100%',
                        height: '100%',
                        backgroundColor: '#f8f8f8',
                        margin: 'auto',
                    }"
                    :img="pic"
                    :fixedNumber="[opt.width,opt.height]"
                    :options="{
                        viewMode: 1,
                        dragMode: 'move',
                        cropBoxResizable: false,
                    }"
                    :presetMode="{
                        mode: 'fixedSize',
                        width: opt.width,
                        height: opt.height,
                    }"
                    @ready="ready"
                    />
                </div>
            </div>
            
        </div>
    </div>

    
</template>
  
<script lang="ts" setup>
    import { ApiResult } from "@/configs/axios";
    import { USER_DEFAULT_HEADER } from "@/configs/customer";
    import UploadService from '@/services/UploadService'
    import FileService from '@/services/FileService'
    import LOGOService from "@/services/LOGOService";
    import AliyunUpload from '@/utils/upload/aliyun'
    import { fileToDataURL } from '@/utils/psdParser/compressor'
    import { useUserStore } from "@/store";
    import { ElLoading, ElMessage } from "element-plus";
    import { storeToRefs } from "pinia";
    import { ref, reactive, watch, onMounted, onBeforeUnmount } from "vue";
    import { useRouter } from "vue-router";
    import InviteMember from '@/views/components/Team/InviteMember.vue'
    import { dataURLtoFile } from "@/utils/common";
    import VuePictureCropper, { cropper } from 'vue-picture-cropper'
    import FileInput from '@/components/FileInput.vue'

    
    
    const userGroup = ref<{id:number,name:string}[]>([
        {id:0,name:'全部角色'},
        {id:1,name:'管理员'},
        {id:2,name:'成员'},
    ])
    const userStore = useUserStore()
    const { token, userInfo } = storeToRefs(userStore)
    const data = ref<any[]>([])
    const loading = ref(false)
    const dataList = ref([] as any)
    const imgList = ref([] as any)
    const srcList = ref([] as any)
    const acquiesceLogo = ref([
        'https://im.oytour.com/pptist/static/logo1.png',
        'https://im.oytour.com/pptist/static/logo2.png',
        'https://im.oytour.com/pptist/static/logo3.png',
        'https://im.oytour.com/pptist/static/logo4.png',
        'https://im.oytour.com/pptist/static/logo5.png',
        'https://im.oytour.com/pptist/static/logo6.png',
    ])

    const acquiesceIMG = ref([] as any)

    const currentImg = ref(0 as number)
    const FormVisible = ref(false as boolean)
    const isViewerShow = ref(false as boolean)
    const currentData = ref(0 as number)
    const pic = ref<string>('')
    const result = reactive({
        dataURL: '',
        blobURL: '',
    })
    const isShowModal = ref(false)
    const opt = reactive({
        width: '',
        height: '',
        minWidth: '',
        minHeight: '',
        maxWidth: '',
        minHeight: '',
    })
    const fileName = ref('')
    const loadingInstance = ref<any>(null)
    const IsEnable = ref(0 as any)
    if(userInfo.value.IsEnableLogo==1) IsEnable.value = userInfo.value.IsEnableLogo
    const parameters = ref<any>([])
    const ShowMessage = ref(false)
    const currentMore = ref(0)


    const showMore = (index:Number) => {
        ShowMessage.value = true
        currentMore.value = index
    }
    const seeLogo = (index:number,type:any) => {
        currentImg.value = index
        srcList.value = type?imgList.value:acquiesceLogo.value
        isViewerShow.value = true
    }
    const getSize = async () => {
        loading.value = true
        for(let i=0;i<6;i++){
            let x = acquiesceLogo.value[i]
            let newSize = await FileService.getImageSizeWithoutDownloading(x)
            if(newSize&&newSize.width){
                acquiesceIMG.value.push({
                    id: i,
                    logo: x,
                    FilePath: '',
                    width: newSize.width,
                    height: newSize.height,
                    FileSize: newSize.width+'*'+newSize.height,
                    TId: '',
                    FileType: i>2?2:1
                })
            }
        }
        getLOGO()
    }
    const showFormHandler = () => {
        FormVisible.value = true
        // getSize()
    }
    const enableLogo = async () =>{
        const response = await LOGOService.EnableGroupLogo(IsEnable.value)
        if(response.data.resultCode == ApiResult.SUCCESS){
            userInfo.value.IsEnableLogo = response.data.data.IsEnableLogo
        }
    }
    const saveLogo = async () =>{
        // if(!IsEnable.value) {
        //     return ElMessage.error({message:`请启用LOGO，并完善LOGO图`})
        //     ElMessageBox.confirm(
        //         `此操作将不会保存新增、修改的企业LOGO，是否确定?`,
        //         '提示',
        //         {
        //             confirmButtonText: '确定',
        //             cancelButtonText: '取消',
        //             type: 'warning',
        //         }
        //     ).then(async () => {
        //         await enableLogo()
        //     }).catch(() => {})
        // }
        for(let i=0;i<acquiesceIMG.value.length;i++){
            let x = acquiesceIMG.value[i]
            if(!x.FilePath) {
                return ElMessage.error({message:`请完善所有尺寸的LOGO`})
            }
        }

        loadingInstance.value = ElLoading.service({
            text:'收集需要处理的图片'
        })
        for(let i=0;i<acquiesceIMG.value.length;i++){
            let x = acquiesceIMG.value[i]
            await uoloadFileToService(x.FilePath,i)
        }
        loadingInstance.value.close()
        loadingInstance.value = null

        for(let i=0;i<acquiesceIMG.value.length;i++){
            let x = acquiesceIMG.value[i]
            let item = {
                FileSize: x.FileSize,
                FilePath: x.FilePath,
                FileType: x.FileType,
                TId: x.TId,
            }
            parameters.value.push(item)
        }
        const response = await LOGOService.SetBatchGroupLogo(parameters.value)
        if(response.data.resultCode == ApiResult.SUCCESS){
            if(userInfo.value.IsEnableLogo!=IsEnable.value) enableLogo()
            parameters.value = []
            imgList.value = []
            FormVisible.value = false
            getLOGO(1)
        }
    }
    const getResult = async ()=> {
        if (!cropper) return
        const loadingObj = ElLoading.service({
            text:'正在上传图',
            lock:true
        })
        const base64 = cropper.getDataURL()
        const blob: Blob | null = await cropper.getBlob()
        if (!blob) return
        
        const file = await cropper.getFile({
            fileName: fileName.value,
        })

        //   console.log({ base64, blob, file })
        result.dataURL = base64
        result.blobURL = URL.createObjectURL(blob)
        acquiesceIMG.value[currentData.value].FilePath = base64
        imgList.value[currentData.value] = base64
        isShowModal.value = false
        loadingObj.close()
    }
    const clear = () => {
      if (!cropper) return
      cropper.clear()
    }
    const reset = () => {
      if (!cropper) return
      cropper.reset()
    }
    const ready = () => {
      console.log('Cropper is ready.')
    }
    const insertImageElement = async (files: FileList,index:number) => {
        let fileType = files[0].name.split('.')
        fileName.value = fileType[0]+`${fileType[1]?fileType[1]:'.png'}`
        currentData.value = index
        pic.value = URL.createObjectURL(files[0])
        opt.width = acquiesceIMG.value[index].width
        opt.height = acquiesceIMG.value[index].height
        let x = acquiesceIMG.value[index]
        let newSize = await FileService.convertNetworkToBase64Async(pic.value)//getImageSizeWithoutDownloading
        let scale = parseInt(newSize.width/newSize.height)
        if(newSize&&newSize.width&&(newSize.width<x.width&&newSize.height<x.height)){
            return ElMessage.error({message:`请选择${x.FileSize}、或大于${x.FileSize}的图`})
        }
        isShowModal.value = true
    }
    const uoloadFileToService = async (base64:any,index:number)=>{
        if(base64.indexOf('data:image/png;base64')==-1) return
        let basestr = base64.split(',')
        let parms = {
            isppt: '1',
            uid: token.value,
            gid: '',
            basestr: basestr[1],
            surl: ""
        }
        let filePath=`firmLogoImg/${new Date().getTime()+index+fileName.value}`;
        let url  = await AliyunUpload.UploadCloudDiskBase64(filePath, parms);
        if(url) {
            loadingInstance.value.text = `当前图片处理进度：${index+1} / ${acquiesceIMG.value.length}`
            acquiesceIMG.value[index].FilePath = url
            imgList.value[index] = url
        }
    }
    const getLOGO = async (type:any)=>{
        if(type==1) loading.value = true
        const response = await LOGOService.GetPPTistGroupLogoList()
        if(response.data.resultCode == ApiResult.SUCCESS){
            dataList.value = response.data.data
            imgList.value = dataList.value.map(x=>{return x.FilePath})
            if(dataList.value.length>0){
               assembleData()
               userInfo.value.GroupLogoList =  response.data.data 
            }
            loading.value = false
        }else {
            loading.value = false
        }
        
    }

    const assembleData = () => {
        for(let i=0;i<acquiesceIMG.value.length;i++){
            let z = acquiesceIMG.value[i]
            let filter =  dataList.value.filter(x=>x.FileSize==z.FileSize&&x.FileType==z.FileType) 
            if(filter&&filter.length>0) {
                acquiesceIMG.value[i].FilePath = filter[0].FilePath
                acquiesceIMG.value[i].TId = filter[0].TId
            }
        }
    }
    getSize()
    onMounted( () => {
        document.addEventListener('click', (e) => {
            if (ShowMessage.value) {
                ShowMessage.value = false
            }
        });
    })
    onBeforeUnmount(() => {
        document.removeEventListener('click', () => {});
    })
  </script>
  
<style lang="scss" scoped>
.CloudDisk-R-Center{
    flex-wrap: wrap;
    padding-top: 10px;
}
.CloudDisk-R-Box{
    width: 147px;
    /* margin-bottom: 24px; */
    position: relative;
}
.CloudDisk-R-Box.active .CloudDisk-R-Img{
    width: 147px;
    height: 147px;
    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: 12px;
    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;
}
.CloudDisk-R-Img{
    width: 147px;
    height: 147px;
    /* margin-bottom: 9px; */
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0px 0px 13px 0px #eee;
    border-radius: 8px;
    border-color:#eee;
}

.CloudDisk-R-Img .el-image{
    width: 147px;
}
.title{
    width: 147px;
    line-height: 17px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #000000;
}
.cloudDownName{
  min-width: 147px;
  padding: 10px 20px 15px 20px;
  font-size: 14px;
  color: #000;
}
.cloudDownText{
  padding: 3px 10px;
  font-size: 14px;
  background: #eef3ff;
  position: absolute;
  z-index: 2;
  right: 0;
  top: 0;
  border-bottom-left-radius: 8px;
  color: #3556f9;
}
.cloudDownTextLin{
  border-bottom: 1px solid #F0F0F0;
}
.tip {
    font-size: 12px;
    color: #aaa;
}
.modal-wrap {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    z-index: 2999;
}
.modal-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(101, 108, 133, 0.8);
    z-index: 0;
}
.modal-scroll-view {
    position: absolute;
    left: 0;
    right: 0;
    z-index: 2;
}
.modal {
    width: 560px;
    background: #fff;
    border-radius: 6px;
    margin: 100px auto 200px;
    box-sizing: border-box;
    padding: 20px;
}
.modal-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
}
.MoreClick{
    position: absolute;
    left: 10px;
    top: 10px;
    z-index: 2;
    background: #fff;
    border-radius: 10px;
    text-align: center;
    padding: 0 3px;
}
.MoreClickCenter{
    position: absolute;
    top: 33px;
    left: -10px;
    background: #fff;
    border-radius: 3px;
    box-shadow: 2px 2px 10px 2px #EEE;
    z-index: 2;
    font-size: 12px;
}
.MoreClickCenter::after{
    content: '';
    width: 0;
    height: 0;
    position: absolute;
    left: 25px;
    top: -8px;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #FFF;
}
.cloudDownControls{
    padding: 5px 10px;
    cursor: pointer;
}
.cloudDownControls:hover{
    background: #dedcff;
    color: $el-color-primary;
}
  </style>