<template>
    <div class="UploadPicture-from">
        <div class="UploadPicture-fromB rounded"
        :class="[winHeight<800?'marginTop':'']">
            <div>
                <div class="text-title">选择、上传图片</div>
            </div>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="我的空间" name="2">
                    <!-- <FileInput @change="files => insertImageElement(files)">
                        <div class="upload-box">
                            <img v-if="imgPath" :src="imgPath" style="height: 200px;"/>
                            <div v-else>
                                <el-icon size="80" color="#a8abb2" class="el-icon--upload">
                                    <upload-filled/> 
                                </el-icon>
                                <p><em>点击上传图片</em></p>
                            </div>
                        </div>
                    </FileInput> -->
                    <CloudDisk :show="showVisible" :active="activeName" @getImg="getImg"></CloudDisk>
                </el-tab-pane>
                <el-tab-pane label="平台资料库" name="1">
                    <template v-if="userInfo.iv||userInfo.it">
                        <el-row>
                            <el-col :span="6">
                                <el-select v-model="datas.queryMsg.Type" class="m-2" 
                                @change="SearchHandler()">
                                <el-option
                                    v-for="item in typeLists"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                                </el-select>
                            </el-col>
                            <el-col :span="18" class="spiderRes">
                                <el-input class="input-with-select q-pl-lg" v-model="datas.queryMsg.Name" placeholder="输入关键字快速查找" clearable @keyup.enter="SearchHandler">
                                    <template #append>
                                        <el-button type="primary" style="color: white;" @click="SearchHandler">搜索</el-button>
                                    </template>
                                </el-input>
                                <!-- <el-input v-model="datas.queryMsg.Name" placeholder="输入关键字快速查找" clearable class="input-with-select q-pl-lg" @change="SearchHandler()"></el-input> -->
                            </el-col>
                        </el-row>
                        <div class="row UploadPicture-box q-pt-lg" v-loading="datas.loading">
                            <div v-for="(item,index) in datas.imgList" class="UploadPicture-list" :key="item.ID">
                                <div class="UploadPicture-listBox">
                                    <img :src="item.Path" class="" @click="getImgs(item,index)"/>
                                    <div class="UploadPicture-Hover" v-if="item.show">
                                        <div>
                                            <el-icon :size="20"><CircleCheckFilled/></el-icon>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="q-mt-md" style="display: flex;justify-content: center;">
                            <el-pagination
                            v-model:current-page="datas.queryMsg.pageIndex"
                            :page-size="datas.queryMsg.pageSize"
                            small-padding
                            layout="prev, pager, next"
                            :total="datas.queryMsg.total"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            />
                        </div>
                    </template>
                    <div class="flex-center column items-center q-py-lg" v-else>
                        <BuyProduct></BuyProduct>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="第三方资源" name="4">
                    <SpiderResource @change="(payload:string)=> spiderImgUrl=payload" v-if="userInfo.iv||userInfo.it"></SpiderResource>
                    <div class="flex-center column items-center q-py-lg" v-else>
                        <BuyProduct></BuyProduct>
                    </div>
                </el-tab-pane>
                
                <el-tab-pane label="图片地址" name="3">
                    <div class="row wrap q-mt-md">
                        <el-input v-model="imgUrl" placeholder="输入图片的地址" class="input-with-select"></el-input>
                    </div>
                </el-tab-pane>
            </el-tabs>
            <div class="q-mt-lg row items-center">
                <div class="col">
                    
                </div>
                <div>
                    <el-button class="q-ml-lg" @click="close()">取消</el-button>
                    <el-button  type="primary" class="q-ml-lg" @click="setImgs()">确定</el-button>
                </div>
            </div>
        </div>
        
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, inject, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { type UploadProps, type UploadUserFile,type UploadInstance, ElMessage, ElLoading } from 'element-plus'
import useCreateElement from '@/hooks/useCreateElement'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
import { getImageDataURL } from '@/utils/image'
import { useMainStore, useSlidesStore, useScreenStore, useUserStore } from '@/store'
import { injectKeyDataSource, injectKeyTemplate } from '@/types/injectKey'
import ConfigService from '@/services/ConfigService'
import { VIEWPORT_SIZE, VIEWPORT_VER_SIZE } from '@/configs/canvas'
import FileService from '@/services/FileService'
import SpiderResource from '@/views/Editor/CanvasTool/SpiderResource.vue'
import type { PPTImageElement, SlideBackground } from '@/types/slides'
import FileInput from '@/components/FileInput.vue'
import BuyProduct from '@/components/User/BuyProduct.vue'
import CloudDisk from '@/components/CloudDisk/index.vue'

const showVisible = ref(true)
const activeName = ref("2")
const imgVisibleStore = useScreenStore()

const imageFile = ref({})
const imgOnline = ref('')
const imgPath = ref('')
const imgUrl = ref('')
const spiderImgUrl = ref('')
const upload = ref<UploadInstance>()

const { userInfo } =storeToRefs(useUserStore())

if(!userInfo.value.iv && !userInfo.value.it) activeName.value="2"
const imgType = ref(0) // 1 插入图片  2替换图片
imgType.value = inject('imgType')
const propsDatas = ref<any>({})
const typeLists = ref([
    {label: '不限',value:0},
    {label: '酒店',value:1},
    {label: '餐厅',value:2},
    {label: '景点',value:3},
  ])
const datas = reactive({
  DataSource:{},
  loading: false,
  imgList: [],
  queryMsg:{
    pageSize: 16,
    pageIndex: 1,
    total: 0,
    Type: 0, //1-酒店,2-餐厅,3-景点,4-票务,5-车辆,6-领队,7-购物店
    Name: "", //资源图片名称
    SourceId: 0 //资源编号
  }
})
datas.DataSource = inject(injectKeyDataSource)
// if(datas.DataSource.pageType==2) datas.queryMsg.Type = 1
// else if(datas.DataSource.pageType==3) datas.queryMsg.Type = 3
// else if(datas.DataSource.pageType==4) datas.queryMsg.Type = 2
const mainStore = useMainStore()

const { createImageElement } = useCreateElement()
const { addHistorySnapshot } = useHistorySnapshot()
const slidesStore = useSlidesStore()
const { slides, currentSlide, slideIndex, layoutSlides } = storeToRefs(slidesStore)
const { handleElement, handleElementId } = storeToRefs(mainStore)
const handleImageElement = handleElement as Ref<PPTImageElement>
const { imgPoolVisible } = storeToRefs(useScreenStore())

const searchData = ref({} as any)
searchData.value = inject(injectKeyTemplate)

const winHeight = ref(0)
winHeight.value = window.innerHeight

watch(() => imgPoolVisible.value, () => {
    if(imgPoolVisible.value) showVisible.value = true
})

const handleSizeChange = (val: number) => {
}
const handleCurrentChange = (val: number) => {
    datas.queryMsg.pageIndex = val
    getImgList()
}

const getImg = (url:String) => {
    imgPath.value = url
    propsDatas.value = { src: url }
}

const insertImageElement = (files: FileList) => {
  const imageFile = files[0]
  if (!imageFile) return
  getImageDataURL(imageFile).then(dataURL => {
    imgPath.value = dataURL,
    propsDatas.value = { src: dataURL }
  })
}

const setImgs = async () => {
    let text = '请选择图片'
    let url = imgOnline.value
    let downloadInfo:any = {}
    if(activeName.value=='1') propsDatas.value = { src: imgOnline.value } 
    else if(activeName.value=='2') {
        text = '请选择图片'
        url = imgPath.value
    } else if(activeName.value=='3') {
        text = '请输入图片url地址'
        url = imgUrl.value
        propsDatas.value = { src: imgUrl.value } 
    } else if(activeName.value=='4') {
        text = '请选择你需要的图片'
        url = spiderImgUrl.value
        propsDatas.value = { src: spiderImgUrl.value } 
    }
    if(!url){
        return ElMessage({
            showClose: true,
            message: text,
            type: 'warning',
        })
    }
    if(activeName.value=='1'||activeName.value=='3' || activeName.value == '4'){
        const downLoading = ElLoading.service({
            lock:true,
            text:'正在导入图片'
        })
        try {
            downloadInfo = await FileService.convertNetworkToBase64Async(url)
            //url =  downloadInfo.url
            propsDatas.value.src = url
        } catch (error) {}
        if(downloadInfo.url == ''){
            ElMessage({
                showClose: true,
                message: '图片导入失败，请重试',
                type: 'error',
            })
            return
        }
        downLoading.close()
        
    }
    if(imgType.value==1){
        createImageElement(url,searchData.value.TemplateType)
        close()
    }
    if(imgType.value==2){
        if(activeName.value=='1'||activeName.value=='3' || activeName.value == '4'){
            let tempSize = downloadInfo
            //if(activeName.value != '4') tempSize = await FileService.getImageSizeWithoutDownloading(propsDatas.value.src)
            setPropsDatas(tempSize)
        } else{
            const image = new Image()
            new Promise((resolve, reject) => {
                image.onload = () => {
                    resolve({ width: image.width, height: image.height });
                    URL.revokeObjectURL(propsDatas.value.src);
                };
                image.onerror = reject;
                image.src = propsDatas.value.src;
            });
            setPropsDatas(image)
        }
    }
    
}

const setPropsDatas = (image:any) => {
    let width = 0
    let height =  0
    //按照宽度进行缩放
    let ratio = image.width / handleImageElement.value.width
    width = handleImageElement.value.width
    height = image.height / ratio

    if(height<handleImageElement.value.height){
        ratio = height /  handleImageElement.value.height
        height =  handleImageElement.value.height
        width = width / ratio
        propsDatas.value.left = handleImageElement.value.left - (Math.ceil((width - handleImageElement.value.width)/2))
    }else{
        propsDatas.value.top = handleImageElement.value.top - (Math.ceil((height - handleImageElement.value.height)/2))
    }
    propsDatas.value.height = height
    propsDatas.value.width = width
    
    propsDatas.value.fixedRatio = true
    slidesStore.updateElement({ id: handleElementId.value, props:propsDatas.value })
    addHistorySnapshot()
    close()
}


const getImgs = (item:any,index:number) => {
    datas.imgList.forEach(x=>{x.show=false})
    item.show = true
    imgOnline.value = item.Path
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
    if(activeName.value!='1'){
        imgOnline.value = ''
        datas.imgList.forEach(x=>{x.show=false})
    }else if(activeName.value!='2'){
        imgPath.value = ''
        imageFile.value = {}
    }else if(activeName.value!='3'){
        imgUrl.value = ''
    }else if(activeName.value!='4'){
        spiderImgUrl.value = ''
    }
}

const close = () =>{
    showVisible.value = false
    imgVisibleStore.setImgPoolVisible(false)
    imgVisibleStore.setImgReplaceVisible(false)
}
const SearchHandler = async () => {
    datas.imgList = []
    datas.queryMsg.pageIndex = 1
    await getImgList()
}
const getImgList = async () =>{
    if(!userInfo.value.iv && !userInfo.value.it) return
    datas.loading = true
    try {
      let datasRes = await ConfigService.GetPicList(datas.queryMsg);
      if (datasRes.data.resultCode == 1) {
        let data = datasRes.data.data.pageData
        let arrData = function(list){
            list.forEach(item => {
                item.show = false
            });
        }
        arrData(data)
        datas.imgList = data
        datas.queryMsg.total = datasRes.data.data.count;
      }
      datas.loading = false
  } catch (error) {
    datas.loading = false
  }
}


getImgList()
</script>
<style lang="scss" scoped>
.spiderRes::v-deep(.el-button){
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
.UploadPicture-from{
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 2000;
    background: rgba(23,23,23,.5);
}
.UploadPicture-fromB{
    width: 687px;
    margin: 150px auto 0;
    background: #fff;
    padding: 20px;
}
.UploadPicture-fromB.marginTop{
    margin: 2.5vw auto 0;
}
.col #tippy-30{
    z-index: 99999 !important;
}
.upload-box{
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    padding: 40px 10px;
    cursor: pointer;
}
.UploadPicture-box{
    flex-wrap: wrap;
    margin-left: -10px;
}
.UploadPicture-list{
    width: calc(25% - 10px) !important;
    margin-bottom: 10px;
    margin-left: 10px;
}
.UploadPicture-listBox{
    width: 150px;
    height: 0;
    position: relative;
    padding-bottom: 64.96%;
}
.UploadPicture-list img{
    width: 100%;
    height: 100%;
    border-radius: 5px;
    position: absolute;
    object-fit: cover;
    cursor: pointer;
}
.UploadPicture-Hover{
    z-index: 1;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(23,23,23,0.5);
    display: none;
    transition: opacity 0.5s ease;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: $themeHoverColor;
}
</style>