<template>
    <el-dialog v-loading="sliderLoading" v-model="visibleStatus" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false" style="max-width:650px;">
        <template #header>
            <div class="text-title">导入PSD设计文件</div>
        </template>
        <div v-if="!thumbnails || thumbnails.length==0">
            <el-upload
                v-loading="isResolving"
                ref="upload"
                class="upload-drop-box"
                :on-change="handleChange"
                action=""
                drag
                :limit="1"
                :on-exceed="handleExceed"
                :auto-upload="false"
                accept=".psd,image/vnd.adobe.photoshop"
                :show-file-list="false"
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                拖动文件到这里释放或<em>点击上传</em>
                </div>
                <template #tip>
                <div class="el-upload__tip">
                    当前仅支持PSD文件上传解析
                </div>
                </template>
            </el-upload>
            <div class="text-right q-mt-lg">
                <el-button @click="close" :disabled="isResolving">取消导入</el-button>
            </div>
        </div>
        
        <div v-else>
            <div class="text-small text-grey">已成功解析PSD文件，请核对下方图片是否正确：</div>
            <div class="row" style="flex-wrap:wrap">
                <img v-for="(x,i) in thumbnails" :key="i" style="height:auto;width:calc(25% - 10px);" class="q-mr-md rounded q-mt-md" :src="x" />
            </div>
            <div class="text-small text-grey q-mt-lg">请完善以下字体信息补充：</div>
            <div class="row items-center q-mt-md" v-for="(x,i) in fonts" :key="x">
                <div class="text-small col">字体名称：{{ x }}</div>
                <el-upload
                    v-loading="uploadingIndex==i"
                    :on-change="(uploadFile:any, uploadFiles:any)=> uploadFontHandler(uploadFile, uploadFiles,x)"
                    action=""
                    :limit="1"
                    v-if='uploadFinishFont?.indexOf(x)==-1'
                    :auto-upload="false"
                    accept=".ttf, .woff, .woff2"
                    :show-file-list="false"
                >
                    <template #trigger>
                        <el-button link>选择字体</el-button>
                    </template>
                </el-upload>
                <el-tag v-else type="success" effect="light"> 已上传 </el-tag>
                <el-button  v-if='uploadFinishFont?.indexOf(x)==-1' type="danger" class="q-ml-md" @click="removeFontHandler(x)" :icon="Delete" link></el-button>
            </div>
            <div class="q-mt-lg row items-center">
                <div class="col">
                    <el-button @click="resetPsdHandler">重新选择</el-button>
                </div>
                <div>
                    <el-button @click="close">取消导入</el-button>
                    <el-button type="primary" class="q-ml-lg" @click="resolveToSliderHandler">确认导入</el-button>
                </div>
            </div>
           
           
        </div>
    </el-dialog>
</template>
<script setup lang="ts">
import {ref,defineProps,watch} from 'vue'
import { UploadFilled,Delete } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile,UploadInstance } from 'element-plus'
import PSD from 'psd.js'
import {getFonts, toSlider, toThumbnails} from '@/utils/psdParser/index'
import { useSlidesStore } from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import AliyunUpload from '@/utils/upload/aliyun'
import { useFontStore } from '@/store'
import { CustomerFonts } from '@/store/font'

const props = defineProps({
    visible:{
        type:Boolean,
        required:true,
        default:true
    }
})
const emit = defineEmits<{
  (event: 'update:visible', payload: boolean): void
  (event: 'closed'): void
}>()

const visibleStatus = ref(props.visible)
const upload = ref<UploadInstance>()
const isResolving = ref(false)
const sliderLoading = ref(false)
const thumbnails = ref<Array<any>>([])
const sliders = ref<Array<any>>([])
const fonts = ref<any[]>()
const uploadingIndex = ref(-1)
const uploadFinishFont = ref<string[]>([])


const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    isResolving.value=true
    if(uploadFile){
        var url = URL.createObjectURL(uploadFile?.raw)
        try {
            PSD.fromURL(url).then(async (psd:any) => {
                thumbnails.value= await toThumbnails(psd)
                sliders.value = toSlider(psd)
                fonts.value = getFonts(psd)
                if(fonts.value){
                    fonts.value = fonts.value.filter(x=>useFontStore().getFonts.findIndex(y=>y.fontFamily==x)==-1)
                }
                //currentPSD.value = psd
                isResolving.value=false
            })
        } catch (error) {
            isResolving.value=false
        }
    }else{
        isResolving.value=false
    }
}
const uploadFontHandler = async (uploadFile:any, uploadFiles:any, fontName:string) => {
    uploadingIndex.value = fonts.value?.indexOf(fontName)??-1
    try {
        const url = await AliyunUpload.UploadAsync(uploadFile?.raw,"tripfont/"+uploadFile.name)
        if(url && url!=''){
            //添加字体
            uploadFinishFont.value.push(fontName)
            let data:CustomerFonts = {
                fontFamily:fontName,
                label:uploadFile.name.split('.')[0],
                fontUrl:url
            }
            const result = await useFontStore().uploadFontAsync(data)
            if(result){
                uploadFinishFont.value.push(fontName)
            }else{
                ElMessage({
                    message:'字体上传失败,请重试',
                    type:'error'
                })
            }
        }
    } catch (error) {
        console.log("上传异常",error)
    }
    uploadingIndex.value=-1
}
const removeFontHandler = (fontName:any)=>{
    ElMessageBox.confirm('删除后无法恢复，是否确定执行','提示',{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
        console.log('then',!fonts.value)
        if(fonts.value){
            console.log(fonts.value,fontName)
            fonts.value?.splice(fonts.value.indexOf(fontName),1)
        }
    })
    .catch((error) => { console.log("catch",error)})
}
const handleExceed: UploadProps['onExceed'] = (files) => {
    console.log('执行clear')
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    upload.value!.handleStart(file)
}
const resolveToSliderHandler = async()=>{
    if(uploadFinishFont.value?.length < (fonts.value?.length??0)){
        ElMessage({
            message:'请完善字体信息',
            type:'error'
        })
    }else{
        useSlidesStore().setSlides(sliders.value)
        useSlidesStore().updateSlideIndex(0)
        close()
    }
}
const resetPsdHandler = ()=>{
    thumbnails.value=[]
}
const close = () => {
  visibleStatus.value=false
  resetPsdHandler()
  emit('update:visible', false)
  emit('closed')
}
watch(() => props.visible, () => {
    visibleStatus.value = props.visible
})

</script>