<template>
    <div class="up-load-file-for-jianda">
        <div class="my-up-load-file-main">
            <!--    enter button    -->
            <el-tooltip content="注：最多可以上传两个文件"
                        placement="top"
                        popper-class="c-aliUpload-tooltip"><i
                    class="aliUpload-note-word"></i></el-tooltip>
            <el-upload
                    class="upload-demo"
                    action=""
                    :show-file-list="false"
                    :http-request="importFun"
            >
                <el-button size="small" @click="beforeUpload('input')" type="text">上传文件</el-button>
            </el-upload>
            <el-button @click="handleOpenDialog" type="text">扫码上传</el-button>
            <!--    file lists    -->
            <template v-if="fileLists.length">
                <span
                        class="file-lists_span fsize-m6"
                        v-for="(item, index) in fileLists"
                        :key="item.url">
                    <span v-if="!item.isImage">附件{{index+1}}</span>
                    <span v-if="item.isImage">
                        <img :src="item.url" width="20" height="20">
                    </span>

                    <span style="cursor: pointer;" @click="ConfirmDelete(item)">
                        <i class="el-icon-close"></i>
                    </span>
                </span>
            </template>
        </div>
        <!--    dialog    -->
        <el-dialog
                title="扫码上传图片"
                :visible.sync="dialogImageVisible"
                width="30%"
                center
                :close-on-click-modal="false"
                @close="handleImageClose">
            <div class="dialog-content">
                <div class="my-box">
                    <!--        倒计时            -->
                    <p>请在1分钟内手机扫码上传图片：{{countdown}}秒</p>
                    <p>
                        <vue-qrcode :value=QRCodeUrl :options="{ color: { dark: '#0275D8' }  }"></vue-qrcode>
                    </p>
                </div>
            </div>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>

        <MtaStDialog
                  :dVisible.sync="mtaDeleteVisible"
                  dType="warning"
                  :modalAppendToBody="false"
                  dMessage="选中的数据将彻底删除"
                  @comfirmCallback="doDelete"
        ></MtaStDialog>

    </div>
</template>

<script>
    import { getUploadImg }  from '@/api/AlCloud.js';
    import axios             from 'axios';
    import { getOpenSearch } from '@/api/base64.js';
    import VueQrcode         from '@chenfengyuan/vue-qrcode';

    export default {
        name:       'upLoadFileForJianda',
        components: {
            VueQrcode,
        },
        data() {
            return {
                dialogImageVisible: false,
                mtaDeleteVisible:   false,
                fileLists:          [],
                mySelectDelete:     null,
                QRCodeUrl:          '',
                key:                '',
                link:               '',
                countdown:          120, // 60秒倒计时
                timer1:             null,
                timer2:             null,
            };
        },
        props:      {
            option:      {
                type:    Object,
                default: () => ({}),
            },
            myfileLists: {
                type:    String | null,
            },
        },
        watch:      {
            myfileLists: {
                handler(a, b) {
                    let c = a || [];

                    if (typeof c === 'string') {
                        c = JSON.parse(c);
                    }

                    c.forEach(item => {
                        const isImage = this.checkIsImg(item);
                        this.fileLists.push({
                                                isImage: isImage,
                                                url:     item,
                                            });
                    });
                },
                immediate: true,
                deep:      true,
            },
        },
        methods:    {

            beforeUpload(data){
                window.onblur = null;
                this.$emit('clickUploadFile', data);
            },
            handleGetImageDataFun() {
                this.timer2 = setInterval(() => {
                    // 获取手机上传文件
                    // const loading = this.loading();
                    getOpenSearch({
                                      key: this.key,
                                  })
                    .then(res => {
                        const data = res.data.urlList || [];

                        if (!data.length) {
                            return;
                        }

                        this.handleComplateData2(data);
                        // this.$emit('accessory', this.fileLists);
                        // this.fileLists = [];
                        this.dialogImageVisible = false;
                        this.clearTimeFun();
                        // loading.close();
                    })
                    .catch(err => {
                        // this.$message.error('手机上传文件获取异常');
                        // loading.close();
                        console.log(err);
                    });
                }, 5000);
            },
            // 倒计时60秒
            setTime() {
                if (this.countdown === 0) {
                    this.dialogImageVisible = false;
                    this.countdown = 120;
                    this.clearTimeFun();
                } else {
                    this.countdown--;
                    this.timer1 = setTimeout(() => {
                        this.setTime();
                    }, 1000);
                }
            },
            clearTimeFun() {
                clearTimeout(this.timer1);
                clearInterval(this.timer2);
                this.timer1 = null;
                this.timer2 = null;
                this.countdown = 120;
            },
            doDelete() {
                this.handleDelete(this.mySelectDelete);
            },
            ConfirmDelete(data) {
                this.mySelectDelete = data;
                this.mtaDeleteVisible = true;
            },
            // 文件上传 函数
            importFun(params) {
                if(this.fileLists.length > 2 || this.fileLists.length === 2){
                    this.$message.error('最多可以上传两个文件');
                    return;
                }
                if (!params) {
                    return false;
                }
                const suffixList = params.file.name.split('.');
                const options = {
                    prefix: 'temp/',
                    suffix: suffixList[suffixList.length-1],
                };
                getUploadImg(options).then((res) => {
                    if (res.code === 0) {
                        // 二进制文件通过forData对象进行传递
                        const FormDataForAl = new FormData();
                        const multipartParams = Object.assign({}, res.data, {
                            Filename:              `images/${params.filename}`,
                            success_action_status: '200',
                        });
                        // 参数数据
                        FormDataForAl.append('key', multipartParams.key);
                        FormDataForAl.append('policy', multipartParams.policy);
                        FormDataForAl.append('signature', multipartParams.signature);
                        FormDataForAl.append('OSSAccessKeyId', multipartParams.accessid);
                        FormDataForAl.append('success_action_status', multipartParams.success_action_status);
                        // OSS要求, file放到最后
                        FormDataForAl.append('file', params.file);
                        const loading = this.loading();
                        axios.post(multipartParams.uploadUrl, FormDataForAl)
                             .then(alRes => {
                                 if (alRes.status === 200) {
                                     const fileUrl = `${multipartParams.downloadUrl}/${multipartParams.key}`;
                                     if (this.checkFileListslength()) {
                                         this.$message.success('附件上传成功');
                                         this.handleComplateData(fileUrl);
                                     } else {
                                         this.$message.error('附件最多上传2个');
                                     }
                                 }
                                 loading.close();
                             })
                             .catch(err => {
                                 loading.close();
                                 console.log(err);
                             });
                    }

                });
            },
            // 手机上传 图片处理
            handleComplateData2(fileUrls) {
                fileUrls.forEach(item => {
                    const isImage = this.checkIsImg(item);

                    this.fileLists.push({
                                            isImage: isImage,
                                            url:     item,
                                        });
                });

                this.backData();
            },
            // Pc文件上传
            handleComplateData(fileUrl) {
                const isImage = this.checkIsImg(fileUrl);

                this.fileLists.push({
                                        isImage: isImage,
                                        url:     fileUrl,
                                    });
                this.backData();
                // this.$emit('accessory', this.fileLists);
                // this.fileLists = [];
            },
            backData() {
                const c = this.fileLists.map(item => {
                    return item.url;
                });
                this.$emit('getFileLists', c);
                this.fileLists = [];
            },
            // 校验是否是图片
            checkIsImg(data) {
                if (typeof data !== 'string') {
                    throw new Error('校验是否是否图片参数错误');
                }
                const strArr = data.split('.');

                if (!strArr.length) {
                    throw new Error('文件地址数据缺少关键字: .');
                }

                const whiteList = ['jpg', 'png', 'jpeg', 'bmp'];
                return whiteList.some(item => item === strArr[strArr.length - 1]);
            },
            // 校验 file lists 数组是否大于2
            checkFileListslength() {
                return true;
            },
            handleDelete(data) {
                this.fileLists = this.fileLists.filter(item => item.url !== data.url);
                this.mySelectDelete = null;
                this.backData();
            },
            handleImageClose() {
                this.clearTimeFun();
            },
            handleOpenDialog() {
                this.dialogImageVisible = true;
                this.setTime();
                this.handleGetImageDataFun();
            },
            getQRCodeUrl(data) {
                if (data.length === 0) {
                    throw new Error('二维码唯一识别参数异常');
                }

                // console.log('queryArr:', data);
                // console.log('全局变量：', process.env.VUE_APP_BASE_API_TARGET);
                this.key = '';
                data.forEach(item => {
                    this.key += item;
                });
                // H5 接口地址
                //const myH5Url = process.env.VUE_APP_BASE_API_TARGET;
                const myH5Url = window.location.protocol + '//' + `${document.location.host}/` + process.env.VUE_APP_DIST_NAME + `/#/phoneFile`;
                this.QRCodeUrl = `${myH5Url}?key=${this.key}`;

            },
        },
        created() {
            const queryArr = Object.values(this.option);
            this.getQRCodeUrl(queryArr);
        },
    };
</script>
