<template>
    <div class="UploadPicture-from">
        <div class="UploadPicture-fromB rounded">
            <div>
                <div class="text-title">选择、上传图片</div>
            </div>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="ERP资料库" name="1">
                    <el-row class="q-mb-md">
                        <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">
                            <el-input v-model="datas.queryMsg.Name" 
                            placeholder="输入关键字快速查找" clearable
                            class="input-with-select q-pl-lg" @keyup.enter="SearchHandler()">
                                <template #append>
                                    <el-button type="primary" @click="SearchHandler">搜索</el-button>
                                </template>
                            </el-input>
                        </el-col>
                    </el-row>
                    <div class="row UploadPicture-box" v-loading="datas.loading">
                        <div v-for="(item,index) in datas.imgList" class="UploadPicture-list">
                            <div class="UploadPicture-listBox">
                                <img :src="item.Path" class="rounded" @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="currentPage"
                        :page-size="datas.queryMsg.pageSize"
                        :small="small"
                        :disabled="disabled"
                        :background="background"
                        layout="prev, pager, next"
                        :total="datas.queryMsg.total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        />
                    </div>
                    
                </el-tab-pane>
                <el-tab-pane label="第三方资源" name="4">
                    <SpiderResource @change="(payload:string)=> spiderImgUrl=payload"></SpiderResource>
                </el-tab-pane>
                <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>
                </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 } 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 } from '@/store'
import { injectKeyDataSource } 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'
const showVisible = ref(true)
const activeName = ref("1")
const imgVisibleStore = useScreenStore()

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

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,
    currentPage: 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 handleSizeChange = (val: number) => {
}
const handleCurrentChange = (val: number) => {
    datas.queryMsg.pageIndex = val
    getImgList()
}

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=='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)
        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 () =>{
    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>
.UploadPicture-from{
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: rgba(23,23,23,.5);
}
.UploadPicture-fromB{
    width: 680px;
    margin: 150px auto 0;
    background: #fff;
    padding: 20px;
}
.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;
}
.UploadPicture-list{
    width: 150px;
    margin: 5px;
}
.UploadPicture-listBox{
    width: 150px;
    height: 0;
    position: relative;
    padding-bottom: 56.25%;
}
.UploadPicture-list img{
    width: 100%;
    height: 100%;
    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>