<template>
    <div class="files">
        <el-drawer v-model="drawer" direction="rtl" append-to-body style="min-width: 500px;">
            <template #header>
                <h4>上传图片</h4>
            </template>
            <template #default>
                <div>
                    <el-upload v-model:file-list="fileList" multiple 
                        action="#" 
                        list-type="picture-card"
                        :on-change="beforeUpload"
                        :auto-upload="false"
                        :on-preview="handlePictureCardPreview">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" style="width: 100%;height: auto;"/>
                    </el-dialog>
                </div>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawer = false">取消</el-button>
                    <el-button type="primary" @click="confirmClick">立即提交</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref,reactive} from "vue";
import * as qiniu from 'qiniu-js';
import { upFileToken,medicineimgedit } from "@/api";
import type { UploadProps, UploadUserFile } from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const fileList:any = ref<UploadUserFile[]>([])//上传的图片列表

const beforeUpload = async(file:any) => {  
    console.log('上传',file)
    var strtype:any = file.name.substring(file.name.lastIndexOf('.') + 1); //获取后缀 png jpg
    const token:any = await upFileTokenApi(strtype)
    handleUpload(file,token.data);
}
//获取token
const upFileTokenApi = async (strtype:any)=>{
    return await upFileToken({T_suffix: strtype})
}
/**
 * 上传七牛云
 */
const handleUpload = (file:any,qiniuToken:any)=> {  
    
    var config = {
        useCdnDomain: false, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
        region: qiniu.region.z2,
        domain: "https://qiniu.region.z2", //配置好的七牛云域名  如   https://cdn.qniyun.com/
        chunkSize: 1000, //每个分片的大小，单位mb，默认值3
        forceDirect: false //直传还是断点续传方式，true为直传
    };
    var putExtra:any = {
        params: {},
        mimeType: [] || null
    };
    var key = file.name || null
    const observable = qiniu.upload(objectToBinary(file), key, qiniuToken);  

    // const observable = qiniu.upload(file, key, qiniuToken, putExtra, config);  
    observable.subscribe({  
      next(res:any) {  
        // 上传进度信息  
        console.log(res);  
      },  
      error(err:any) {  
        // 上传错误信息  
        console.log(`上传错误信息: ${err}`);  
      },  
      complete(res:any) {  
        // 上传完成信息  
        const j = fileList.value.findIndex((item:any)=>{return item.name == file.name})
        fileList.value[j] = { name: file.name, url: res.key }
        // 更新你的文件列表或进行其他操作  
      },  
    });  
  }

  
const objectToBinary = (obj:any)=> {
    // 将对象转换为JSON字符串
    const jsonStr = JSON.stringify(obj);
    // 将字符串转换为二进制数据
    const binaryStr = unescape(encodeURIComponent(jsonStr));
    // 创建Blob对象
    const blob = new Blob([binaryStr], { type: 'application/octet-stream' });
    // 创建File对象
    const file = new File([blob], "filename.bin", {
        type: 'application/octet-stream',
    });
    return file;
}
 
// 示例用法
const obj = { key: "value" };
const file = objectToBinary(obj);
console.log(file);



/**
 * 查看图片
 */
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const drawer = ref(false)

//请求参数
const initParam:any = reactive({
    "id": "",//生产企业
    "img": "",//图片地址逗号分隔
})

const confirmClick = () => {
    let arr = [...fileList.value]
    let array:any = []
    arr.forEach((item)=>{
        array.push(item.url)
    })
    initParam.img = array.join(',')
    setMedicineeditApi()
}

const emit:any = defineEmits(['upTable'])
const setMedicineeditApi = async()=>{
    const reslut:any = await medicineimgedit(initParam)
    if(reslut.code==200){
        emit('upTable', '');
        drawer.value = false
    }
}
const showDrawer = () => {
    drawer.value = true
}


//暴露方法
defineExpose({
    showDrawer,initParam
})
</script>
<style lang="scss">
/* @import url(); 引入css类 */
</style>