<template>
    <view>
        <u-popup v-model="allShow" mode="bottom" border-radius="20" @close="cancel">
            <view class="main text-center font-30 color-11 text-bold">
                <view v-for="(item,index) in list" :key="index" class="select-item" :class="[index+1!=list.length?'border':'']" @tap="sheetClick(item.type)">
                    {{item.text}}
                </view>
                <view style="background:#F5F6F7;height:15rpx;width:100%;"></view>
                <view class="cancel-item" @tap="cancel">取消</view>
            </view>
        </u-popup>


    </view>
</template>

<script>
export default {
    data() {
        return {
            list: [
                //选项数组
                { text: "图片", type: "image" },
                { text: "视频", type: "video" },
            ],
            last: false, //是否是最后一次选择
            crop: {}, //剪裁
            uploadFileType: "", //上传类型
            sourceType: "", //拍摄/相册
            popupShow: true,
            allShow: false,


        };
    },
    props: {
        //是否显示
        show: {
            type: Boolean,
            default: false,
        },
        //是否剪裁
        isCrop: {
            type: Boolean,
            default: false,
        },
        //是否头像
        isHeader: {
            type: Boolean,
            default: false,
        },
        //上传数量
        length: {
            type: Number,
            default: 6,
        },
        chooseUploadFileType: {
            type: String,
            default: "",
        },
        //是否只能拍照
        isCamera: {
            type: Boolean,
            default: false,
        },

        //是否人脸接口
        isFace: {
            type: Boolean,
            default: false,
        },
    },
    watch: {
        popupShow() {
            this.allShow = this.popupShow && this.show && !this.isCamera;
        },
        show() {
            this.allShow = this.popupShow && this.show && !this.isCamera;
        },
        isCamera() {
            this.allShow = this.popupShow && this.show && !this.isCamera;
            if (this.isCamera) {
                this.sourceType = "camera";
                this.uploadFileAll();
            }
        },
    },
    created() {
        if (this.chooseUploadFileType != "") {
            this.uploadFileType = this.chooseUploadFileType;
            this.last = true;
            this.list = [
                { text: "从手机相册选择", type: "album" },
                { text: "拍摄", type: "camera" },
            ];
        }
    },
    methods: {
      
        cancel() {
            if (this.chooseUploadFileType == "") {
                this.last = false;
                this.list = [
                    { text: "图片", type: "image" },
                    { text: "视频", type: "video" },
                ];
            }
            this.$emit("cancelSheet");
        },
        sheetClick(type) {
            if (this.last) {
                this.sourceType = type;
                this.uploadFileAll();
            } else if (!this.last) {
                this.uploadFileType = type;
            }
            this.last = true;
            this.list = [
                { text: "从手机相册选择", type: "album" },
                { text: "拍摄", type: "camera" },
            ];
        },
        //上传文件
        uploadFileAll() {
            if (this.uploadFileType == "image") {
                this.chooseImages();
            } else if (this.uploadFileType == "video") {
                this.chooseVideo();
            }
        },
        //上传图片
        chooseImages() {
            let _this = this;
            if (
                _this.sourceType == "camera" &&
                _this.isCrop &&
                !_this.isHeader &&
                !_this.isFace
            ) {
                _this.crop = { width: 750, height: 550 };
            } else if (_this.isCrop && _this.length == 1) {
                if (_this.isHeader) {
                    _this.crop = { width: 140, height: 140 };
                } else if (_this.isFace) {
                    _this.crop = { width: 710, height: 640 };
                }
            } else {
                _this.crop = {};
            }
            uni.chooseImage({
                count: _this.length, //默认6
                sourceType: [_this.sourceType], //从相册选择/拍摄
                crop: _this.crop,
                success: (res) => {
                    let igmFile = res.tempFilePaths;
                    igmFile.map((item) => {
                        _this.uploadFile(item);
                    });
                    _this.cancel();
                },
                fail(err) {
                    if (_this.isCamera) {
                        _this.$emit("cancelSheet");
                    }
                    // console.log('选择图片文件失败或取消')
                    // _this.cancel();
                    // console.log(JSON.stringify(err))
                },
            });
        },

        //上传视频
        chooseVideo() {
            // console.log('选择视频')
            let _this = this;
            uni.chooseVideo({
                maxDuration: 15,
                count: 1,
                sourceType: [_this.sourceType],
                duration: 15,
                compressed: true,
                success: (responent) => {
                    // console.log(responent)
                    if (responent.duration <= 16) {
                        // console.log(responent)
                        let videoFile = responent.tempFilePath;
                        _this.uploadFile(videoFile);
                        _this.cancel();
                    } else {
                        uni.showToast({
                            title: "视频最多时长15s",
                            duration: 1500,
                            mask: false,
                            icon: "none",
                        });
                    }
                },
                fail(err) {
                    // console.log('选择视频文件失败或取消')
                    // _this.cancel();
                    // console.log(JSON.stringify(err))
                },
            });
        },
        //压缩后上传
        async uploadFile(upfile) {
            let zip = "";
            let uploadUrl = "";  //上传接口地址
            uni.showLoading({
                mask: true,
                title: "上传中...",
            });

            if (this.uploadFileType == "image") {
                uploadUrl = `${this.$u.http.config.baseUrl}/common/uploadImage`;
                // #ifdef APP-PLUS
                // console.log("App压缩");
                zip = await this.compress(upfile);
                // #endif
            } else if (this.uploadFileType == "video") {
                uploadUrl = `${this.$u.http.config.baseUrl}/common/uploadImage`;
                // #ifdef APP-PLUS
                // console.log("App压缩");
                zip = await this.videoCompress(upfile); // await--上传图片之前先压缩，否则上传会比压缩先执行
                // #endif
            }

            let filePath = "";
            // #ifdef H5
            // console.log("h5");
            filePath = upfile;
            // #endif

            // #ifdef APP-PLUS
            // console.log("App");
            filePath = zip;

            // #endif

            // console.log(zip)
            // console.log(upfile)
            //开始上传，此处可先注释看压缩效果
            uni.uploadFile({
                // 需要上传的地址
                url: uploadUrl,
                // filePath: zip,
                // filePath: upfile,
                filePath: filePath,
                name: "file",
                success: (res) => {
                    // console.log(res)
                  debugger

                  let Urls = JSON.parse(res.data);
                    // console.log(Urls);

                  if (Urls.code == 200) {
                        // console.log(Urls);
                        if (this.uploadFileType == "image") {
                            this.$emit("addProperties", Urls.url);
                        } else if (this.uploadFileType == "video") {
                            let obj = {
                                faceUrl: Urls.url,
                                url: Urls.url,
                            };
                            this.$emit("addProperties", obj);
                        }
                        uni.hideLoading();
                    } else {
                        uni.hideLoading();
                        uni.showToast({
                            title: Urls.msg,
                            duration: 1500,
                            mask: false,
                            icon: "none",
                        });
                    }
                },
                fail: (err) => {
                    uni.hideLoading();
                    uni.showToast({
                        title: "上传失败",
                        duration: 1500,
                        mask: false,
                        icon: "none",
                    });
                },
            });
        },

        //压缩图片
        compress(img) {
            // console.log('开始压缩图片');
            let that = this;
            return new Promise((res) => {
                plus.io.resolveLocalFileSystemURL(
                    img,
                    (entry) => {
                        //通过URL参数获取目录对象或文件对象
                        entry.file((file) => {
                            // 可通过entry对象操作图片
                            // console.log( "压缩前图片信息:" + JSON.stringify(file) ); //压缩前图片信息
                            // if (file.size > 10485760) { 大于10Mb
                            plus.zip.compressImage(
                                {
                                    src: img, //src: 压缩原始图片的路径
                                    dst: img
                                        .replace(".png", "fl.png")
                                        .replace(".PNG", "fl.PNG")
                                        .replace(".jpg", "fl.jpg")
                                        .replace(".JPG", "fl.JPG"),
                                    // width: '50%',      //dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个区分一下
                                    // height: '50%',     //width,height: (String 类型 )缩放图片的宽度,高度
                                    quality: 30, //quality: (Number 类型 )压缩图片的质量
                                    overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
                                    format: "jpg", //format: (String 类型 )压缩转换后的图片格式
                                },
                                (event) => {
                                    // console.log( "压缩后图片信息:" + JSON.stringify(event) ); // 压缩后图片信息
                                    this.imageInfo = event;
                                    let newImg = event.target;
                                    if (event.size < 10485760) {
                                        res(newImg);
                                    } else {
                                        //如果大于1mb
                                        uni.showToast({
                                            title: "图片过大",
                                            duration: 1500,
                                            mask: false,
                                            icon: "none",
                                        });
                                        uni.hideLoading();
                                    }
                                    //返回新的图片地址，在uploadFile之前接收
                                },
                                function (err) {
                                    // console.log('Resolve file URL failed: ' + err.message);
                                    uni.showToast({
                                        title: err.message,
                                        duration: 1500,
                                        mask: false,
                                        icon: "none",
                                    });
                                    uni.hideLoading();
                                    // that.cancel();
                                }
                            );
                            // } else {
                            //   console.log('不用压缩')
                            //     res(img);
                            // }
                        });
                    },
                    (e) => {
                        // 返回错误信息
                        // console.log('Resolve file URL failed: ' + e.message);
                        uni.showToast({
                            title: e.message,
                            duration: 1500,
                            mask: false,
                            icon: "none",
                        });
                        uni.hideLoading();
                        // that.cancel();
                    }
                );
            });
        },

        //压缩视频
        videoCompress(video) {
            // console.log('开始压缩视频');
            let that = this;
            return new Promise((res) => {
                plus.io.resolveLocalFileSystemURL(
                    video,
                    (entry) => {
                        entry.file((file) => {
                            // console.log( "压缩前视频信息:" + JSON.stringify(file) );
                            // if(file.size > 10485760) { //h5+ app压缩
                            plus.zip.compressVideo(
                                {
                                    src: video,
                                    overwrite: true,
                                    filename: "_doc/",
                                },
                                (event) => {
                                    // console.log( "压缩后视频信息:" + JSON.stringify(event) );
                                    let newVideo = event.tempFilePath;
                                    res(newVideo);
                                },
                                function (err) {
                                    uni.showToast({
                                        title: "压缩视频失败",
                                        duration: 1500,
                                        mask: false,
                                        icon: "none",
                                    });
                                    // console.log('压缩视频失败',err)
                                    that.cancel();
                                }
                            );
                            // }else{
                            //     console.log('不用压缩')
                            //     res(video);
                            // }
                        });
                    },
                    (e) => {
                        // 返回错误信息
                        // console.log("Resolve file URL failed: " + e.message);
                        uni.showToast({
                            title: "获取文件失败",
                            duration: 1500,
                            mask: false,
                            icon: "none",
                        });
                        uni.hideLoading();
                        // that.cancel();
                    }
                );
            });
        },
    },
};
</script>

<style lang="less" scoped>
/deep/ .u-drawer__scroll-view {
    // padding-bottom: 28rpx;
}
.select-item {
    height: 120rpx;
    line-height: 120rpx;
}
.cancel-item {
    height: 110rpx;
    line-height: 110rpx;
    width: 640rpx;
    margin-left: 55rpx;
    // background: #f4f4f4;
    // border-radius: 50rpx;
}
.border {
    border-bottom: 2rpx solid #f4f4f4;
}
</style>
