<!--
 * @Description : 产品目录清单 -- 新增SPU -- SPU信息 -- 图片上传
 * @Author      : jinxin
 * @Date        : 2022-10-16 20:18:07
-->

<template>
    <el-upload ref="upload" 
        v-model:file-list="data.defaultImg"
        :action="data.upLoadUrl"
        :data="data.upLoadQuery"
        :on-preview="handlerPreview"
        :before-upload="(file) => {
            return hanlderFileSWH(file)
        }"
        :on-success="(res,file,file_list)=>{
            return handlerSuccess(res,file,file_list)
        }"
        :on-remove="(file,file_list)=>{
            return handlerRemove(file,file_list)
        }"
        :on-exceed="(file,file_list)=>{
            return handlerExceed(file,file_list)
        }"
        :multiple="data.isMultiple"
        :limit="data.parentData.limit"
        auto-upload
        list-type="picture-card"
        accept=".jpg,.png">
        <!-- :on-change="handleEditChange" -->
        <!-- :disabled="data.isShowAddImg" -->
        <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog v-model="data.dialogVisible">
        <el-image width="100%" :src="data.dialogImg" alt></el-image>
    </el-dialog>
</template>
<script>
import { defineComponent,onMounted,reactive,getCurrentInstance, watch,ref } from "vue";
import { useStore } from 'vuex'
import { genFileId } from 'element-plus'
export default defineComponent({
    name:'ImgUpload',
    props:{
        queryPara:Object,
        getimglist:Array
    },
    emits:['update:queryPara','transmitImgParameter','removeImgParameter','update:getimglist'],
    setup(props,context){
        // 生命周期
        onMounted(()=>{})
        // 获取实例
        const { proxy } = getCurrentInstance()
        const store = useStore()
        const upload = ref(null)
        // 变量
        let data = reactive({
            upLoadUrl:process.env.VUE_APP_API_BASEURL + 'admin/v1/product/upload',
            upLoadQuery:{
                type: 'images',
                language_id: store.state.user.language.id || 1
            },
            dialogVisible:false,
            parentData:{},
            isMultiple:false,
            uploadFiles:[],
            isShowAddImg:false,
            defaultImg:[]
        })
        // 文件限制
        const hanlderFileSWH = (file) => {
            // 图片大小 < 1M
            let is2M = file.size / 1024 / 1024 < data.parentData.size
            if (!is2M) {
                proxy.$message.error({ message: `图片大小不可超过${data.parentData.size}M`})
                return false
            } 
            // 尺寸 w * h
            let w = data.parentData.width
            let h = data.parentData.height
            let isSize = new Promise(function(resolve, reject) {
                let _URL = window.URL || window.webkitURL
                let img = new Image()
                img.onload = () => {
                    let valid = img.width === w && img.height === h
                    valid ? resolve() : reject()
                }
                img.src = _URL.createObjectURL(file)
            }).then(() => {
                return file
            },() => {
                proxy.$message.error({ message: `图片尺寸限制为${w} x ${h}`})
                return Promise.reject()
            })
            return isSize
        }
        // 发生改变时
        const handleEditChange = (file,files) => {
            data.isShowAddImg = files.length >= 1
        }
        // 上传成功
        const handlerSuccess = (res, file, files) => {
            if(res.status == 200){
                // 获取数据后添加类型
                if(data.parentData.type == 'album'){
                    let imgrullist = {type:'album',list:[]}
                    files.forEach(el => {
                        if(el.response != undefined){
                            imgrullist.list.push(el.response.data[0].r_path)
                        }else{
                            if(el.url.indexOf('blob:') == -1){
                                let index = el.url.indexOf("com/")
                                let newUrl = el.url.substring(index,el.url.length)
                                newUrl = newUrl.substring(4,newUrl.length)
                                if(!imgrullist.list.includes(newUrl)){
                                    imgrullist.list.push(newUrl)
                                }
                            }
                        }
                    });
                    context.emit('transmitImgParameter',imgrullist)
                }else{
                    proxy.$message({type:'success',message:res.message})
                    data.uploadFiles = res.data
                    data.uploadFiles[0].type = data.parentData.type 
                    context.emit('transmitImgParameter',data.uploadFiles)
                }

            }else{
                proxy.$message({type:'error',message:res.message})
            }
        }
        // 移除图片
        const handlerRemove = (file, files) => {
            data.isShowAddImg = files.length >= 1
            if(files.length >= 1){
                if(data.parentData.type == 'album'){
                    let imgrullist = {type:'album',list:[]}
                    files.forEach(el => {
                        if(el.response != undefined){
                            imgrullist.list.push(el.response.data[0].r_path)
                        }else{
                            let index = el.url.indexOf("com/")
                            let newUrl = el.url.substring(index,el.url.length)
                            newUrl = newUrl.substring(4,newUrl.length)
                            if(!imgrullist.list.includes(newUrl)){
                                imgrullist.list.push(newUrl)
                            }
                        }
                    });
                    context.emit('removeImgParameter',imgrullist)
                }else{
                    context.emit('removeImgParameter',{type:data.parentData.type,url:file.response.data[0].r_path})
                }
            }
        }
        // 更换图片
        const handlerExceed = (files,file_list) => {
            
            file_list[0].raw = files[0]
            file_list[0].name = files[0].name
            upload.value.clearFiles()
            upload.value.handleStart(files[0])
        }
         // 显示大图
        const handlerPreview = (file) => {
            data.dialogVisible = true
            // console.log('file',file.url)
            data.dialogImg = file.url
        }
        // 监听
        watch(()=>props.queryPara,(newVal,oldVal)=>{
            data.parentData = JSON.parse(JSON.stringify(newVal))
            data.isMultiple = data.parentData.limit > 1 ? true : false
            // data.defaultImg = data.parentData.urls
        })
        watch(()=>props.getimglist,(v1,v2)=>{
            if(v1.length > 0 && v1[0].url){
                v1.forEach(el => {
                    el.url = el.url ? store.state.user.cdn + el.url : ''
                }); 
                data.defaultImg = v1
            }else{
                data.defaultImg = []
            }          
        })
        return {
            data,
            props,
            upload,
            handlerPreview,
            hanlderFileSWH,
            handlerSuccess,
            handlerRemove,
            handleEditChange,
            handlerExceed
        }
    }
})
</script>