<template>
    <div>
        <div class="layout-cont-btn" >
            <van-pull-refresh v-model="refreshing" @refresh="_refresh">
                <van-list
                        v-model="loading"
                        :finished="finished"
                        finished-text="没有更多了"
                        @load="_load">
                    <van-swipe-cell v-for="item in resultList" :key="item.name">
                        <div class="result-item" @click="_download(item)">
                            <div>附件名称：{{item.fileName +'.'+item.type }}</div>
                        </div>
                        <template #right>
                            <van-button square type="danger" text="删除" class="swipe-cell-btn"
                                        @click="_del(item.id)"></van-button>
                        </template>
                    </van-swipe-cell>
                </van-list>
            </van-pull-refresh>
        </div>
        <div class="bottom-btn" >
            <!--<van-button type="info" block @click="_goto('/sampling_list/file_upload')">添加附件</van-button>-->
            <van-button type="info" square block @click="_goto('/sampling_list/file_upload')">添加附件</van-button>
            <van-button type="primary" square block @click="_uploadImg">添加图片</van-button>
        </div>
        <van-image-preview v-model="showImg" :images="imgList">
            <!--<template #:index>第{{ index }}页</template>-->
        </van-image-preview>
    </div>
</template>

<script>
    import {samplingSummaryAttachment} from '../../../api'

    export default {
        data() {
            return {
                resultList: [],
                page: 1,
                rows: 20,
                summaryId: '',
                imgList: [''],
                loading: false,//加载中...
                finished: false,//没有更多数据
                refreshing: false,//刷新中...
                //文件id
                fileId: '',
                //上传图片路径：
                action: '',
                showImg: false
            }
        },
        mounted() {
            this.summaryId = this.$route.query.summaryId;
            this.action = this.$global.baseURL + '/drs/v1/sampling_summary_attachment/' + this.summaryId;
            this._getData();
        },
        methods: {
            _refresh() {
                this.page = 1
                this._getData()
            },
            _searchParams() {
                let data = {
                    page: this.page,
                    rows: this.rows,
                    summaryId: this.summaryId
                };
                return this.$serializeForm(data)
            },
            _getData: async function () {
                let result = await samplingSummaryAttachment.page(this._searchParams())
                this.resultList = [...(this.page === 1 ? [] : this.resultList), ...result.records]
                this.refreshing = false
                this.loading = false
                if (this.resultList.length === result.total) {
                    this.finished = true
                }
            },
            _load() {
                this.page = this.page + 1;
                this._getData()
            },
            //路由跳转
            _goto(next) {
                let data = {summaryId: this.summaryId};
                this.$router.push({path: next, query: data})
            },
            _del: async function (id) {
                let result = await samplingSummaryAttachment.deleteByIds({id: id})
                if (result) {
                    this.$toast('删除成功！')
                    this._refresh()
                }
            },
            //下载附件
            _download(data) {
                if (data.type.toLowerCase() === 'jpg' || data.type.toLowerCase() === 'png') {
                    this.showImg = true
                    //预览图片
                    this.imgList[0] = this.$global.baseURL + '/drs/v1/sampling_summary_attachment/view?id=' + '&objectKey=' + data.objectKey;
                    console.log(this.imgList[0])
                } else {
                    //下载文件
                    this.$router.push({
                        path: '/sampling_list/file_download',
                        query: {fileName: data.fileName, id: data.id, ctime: data.ctime}
                    })
                }
            },
            /****************************************上传图片*************************************************/
            _uploadImg() {
                plus.nativeUI.actionSheet({
                    title: "选择图片",
                    cancel: "取消",
                    buttons: [{title: "拍照"}, {title: "相册"}]
                }, (e) => {
                    let index = e.index;
                    switch (index) {
                        case 1:
                            //拍照上传
                            this._camera();
                            break;
                        case 2:
                            //从相册选择上传
                            this._pickPhoto();
                            break
                    }
                });
            },
            //拍照上传
            _camera() {
                plus.camera.getCamera().captureImage((e) => {
                    plus.io.resolveLocalFileSystemURL(e, (entry) => {
                        var url = entry.toLocalURL();
                        var name = url.substr(e.lastIndexOf('/') + 1);

                        //压缩
                        plus.zip.compressImage({
                            src: url,
                            dst: '_doc/' + name,
                            overwrite: true,
                            quality: 30,
                        }, (zip) => {
                            let files = [{key: 'imgUpload', path: zip.target}];
                            this._submitImg(files);
                        }, (error) => {
                            console.log('压缩失败', error)
                        });
                    }, (e) => {
                        console.log("读取拍照文件错误：" + e.message);
                    });
                }, (s) => {
                    console.log("error" + s);
                }, {});
            },
            //从相册选择上传
            _pickPhoto() {
                //多选
                plus.gallery.pick((e) => {
                    let files = [];
                    let url = '';
                    let name = '';
                    for (let i in e.files) {
                        url = e.files[i];
                        name = url.substr(url.lastIndexOf('/') + 1);
                        //压缩取得缩略图
                        plus.zip.compressImage({
                            src: url,
                            dst: '_doc/' + name,
                            overwrite: true,
                            quality: 30,
                        }, (zip) => {
                            files = [{key: 'imgUpload' + i, path: zip.target}];
                            this._submitImg(files);
                        }, (error) => {
                            console.log('压缩失败', error)
                        });

                    }
                }, (e) => {
                    console.log('打开相册失败', e)
                }, {filter: 'image', multiple: true, system: false});
            },
            //上传
            _submitImg(files) {
                // let action =this.$global.baseURL + '/env/v1/sample_attachment/' + '1299251712557694978';
                var task = plus.uploader.createUpload(this.action,
                    {method: "POST"},
                    (t, status) => { //上传完成
                        console.log(JSON.stringify(t), JSON.stringify(status))
                        this._getData();
                    }
                );
                //单图片上传
                let imgData = files[0];
                task.addFile(imgData.path, {key: imgData.key});
                task.setRequestHeader('accessToken', localStorage.getItem('accessToken'));
                task.start();
            },
            /****************************************上传图片*************************************************/
        }
    }
</script>
