<template>
    <!-- htmlcs-disable -->
    <view class="image-collect c-row">
        <!-- 预览 -->
        <view
            v-for="(image, index) in images"
            :key="image.uploadId"
            :style="[{
                'width': imgWidth ? imgWidth + 'rem' : '',
                'margin-left': index % lineNum > 0 ? '.08rem' : '',
            }]"
            :class="['image-collect-span', !imgWidth && 'c-span' + imgspan]"
        >
            <!-- loading -->
            <view v-if="image.loading" class="box">
                <view class="image-collect-loading">&#xe611;</view>
            </view>
            <view v-else class="box">
                <view
                    class="m-icon m-icon-shanchu image-collect-remove"
                    :style="delStyle"
                    @tap="handleRemoveImage(index)"
                />
                <view
                    v-if="image.type === 'video'"
                    class="image-collect-play"
                    @tap="handleImageClick(image)"
                >
                    <c-icon
                        name="play"
                        font-size="36px"
                        :style="{
                            'margin-left': '4px',
                        }"
                    />
                </view>
                <view class="box-inner image-collect-image WA_LOG_OTHER">
                    <c-image
                        has-compress
                        :src="image.icon"
                        :data-index="index"
                        width="100%"
                        height="100%"
                        :hack-white-stroke="false"
                        :is-round="false"
                        radius="0.06rem"
                        @tap="handleImageClick(image)"
                    />
                </view>
            </view>
        </view>

        <!-- 添加图片 -->
        <view
            v-if="images.length < limit"
            :style="[{
                'width': imgWidth ? imgWidth + 'rem' : '',
                'margin-left': images.length % lineNum > 0 ? '.08rem' : '0',
            }]"
            :class="['image-collect-span', !imgWidth && 'c-span' + imgspan]"
        >
            <view
                class="box"
                @tap="showChooseType"
            >
                <view
                    class="box-inner add-wrap"
                    :style="addStyle"
                >
                    <view class="add-img-icon">
                        <img class="add-img-icon__img" src="https://med-fe.cdn.bcebos.com/gy/pic.png">
                        <view class="c-font-normal">
                            {{ images.length }}/{{ limit }}
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view
            v-if="tip"
            :style="tipStyle"
            class="upload-tip"
        >{{ tip }}</view>
        <c-popup
            :show="popupShow"
            :z-index="'921'"
            :show-close="false"
            min-height="20%"
            @close="closeChooseType"
        >
            <view class="choose-type">
                <view
                    v-for="(act,i) in types"
                    :key="i"
                    class="choose-type-item"
                    @tap="chooseType(act)"
                >
                    {{ act.text }}
                </view>
            </view>
        </c-popup>
    </view>
<!-- htmlcs-enable -->
</template>

<script>
/**
* @file 图+视频+拍照+录像上传
* @author hanwensheng
*/
import {upload} from '../../utils/upload';
import {send} from '../../utils/log';
import * as Conf from '../../utils/conf';
import CPopup from '@baidu/med-ui/components/Popup/Popup';
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import CImage from './image';
import {previewVideo} from '../../utils/core';

export default {
    config: {
        component: true
    },
    options: {
        addGlobalClass: true
    },
    components: {
        CPopup,
        CIcon,
        CImage
    },
    props: {
        // 上传图片地址
        url: {
            'type': String,
            'default': '/zhuanjia/med/api/uploadpic?vn=med'
        },
        // 上传视频地址
        videoUrl: {
            'type': String,
            'default': ''
        },
        // 上传图片提示
        tip: {
            'type': String,
            'default': '点击加号上传照片'
        },
        // 限制图片张数
        limit: {
            'type': Number,
            'default': 6 // 最多6张图片
        },
        multi: {// 一次选择多张
            'type': Boolean,
            'default': false
        },
        // input名称
        inputname: {
            type: [String, Number]
        },
        tipStyle: {
            type: Object
        },
        addStyle: {
            type: Object
        },
        delStyle: {
            type: Object
        },
        // 图片展示大小
        imgspan: {
            'type': Number,
            'default': 2// c-span2
        },
        // 图片默认值
        value: {
            'type': Array,
            'default': () => []
        },
        // 图片展示宽度
        imgWidth: {
            'type': Number
        },
        // 一行展示几个图片
        lineNum: {
            type: Number,
            default: 3
        },
        // 上传视频的最大秒数
        duration: {
            type: Number,
            default: 10
        },
        // 是否可以拍照
        takeImage: {
            type: Boolean,
            default: false
        },
        // 是否可以拍短视频
        takeVideo: {
            type: Boolean,
            default: false
        },
        // 是否可以在相册选择图片+视频
        chooseAlbum: {
            type: Boolean,
            default: false
        },
        // 请求host
        host: {
            type: String,
            default: '56'
        }
    },
    data() {
        return {
            // 已上传图片
            images: this.value,
            isShowScan: false,
            scan: '',
            popupShow: false,
        };
    },
    computed: {
        types() {
            let arr = [];
            const isSwan = process.env.MARS_ENV === 'swan';
            if (isSwan && this.takeImage) {
                arr.push({
                    text: '拍照',
                    value: 'takePhoto'
                });
            }
            if (isSwan && this.takeVideo) {
                arr.push({
                    text: '录制视频',
                    value: 'takeVideo'
                });
            }
            // if (isSwan && this.chooseAlbum){
            //     arr.push({
            //         text: '从手机相册中选择',
            //         value: 'chooseAlbum',
            //     });
            // }
            arr.push({
                text: '从手机相册中选择',
                value: '',
            });
            return arr;
        }
    },
    methods: {
        closeChooseType() {
            this.popupShow = false;
        },
        showChooseType() {
            const isSwan = process.env.MARS_ENV === 'swan';
            if (isSwan && this.types.length === 1) {
                this.chooseType(this.types[0]);
                return;
            }
            if (isSwan) {
                this.popupShow = true;
                return;
            }
            this.imgUpload();
        },
        chooseType(act) {
            if (!act) {
                return;
            }
            const value = act.value;
            switch (value) {
                case 'takePhoto': { // 拍照
                    this.imgUpload({
                        openType: 'takePhoto',
                        sourceType: ['camera'],
                        compress: true,
                    });
                    break;
                }
                case 'takeVideo': { // 录像
                    this.imgUpload({
                        openType: 'takeVideo',
                        sourceType: ['camera'],
                    });
                    break;
                }
                case 'chooseAlbum': { // 从相册选择（图+视频）
                    this.imgUpload({
                        openType: 'chooseAlbum',
                        sourceType: ['album', 'camera'],
                        compress: true,
                    });
                    break;
                }
                default: {
                    this.imgUpload();
                }
            }
            this.closeChooseType();
        },
        imgUpload(conf = {}) {
            if (this.images.length >= this.limit) {
                return;
            }
            let apiHost = this.host === 'go' ? Conf.goApiHost : Conf.apiHost;
            upload({
                url: apiHost + this.url,
                videoUrl: apiHost + this.videoUrl,
                name: 'picFile',
                videoName: 'videoFile',
                multi: this.multi,
                count: this.limit - this.images.length,
                duration: this.duration,
                compress: false,
                ...conf,
                onChoose: info => {
                    this.$emit('chooseImg', info);
                    this.$emit('beforeUpload');
                    this.$set(this, 'images', [...this.images, ...info]);
                    send({
                        type: 'b',
                        action: 'imageCollectUpload_chooseImg'
                    });
                },
                onPreview: info => {
                    this.$emit('previewImg', info);
                },
                onUploadSuccess: info => {
                    // console.log('info', info);
                    let resp = {...info.resp};
                    const index = this.images.findIndex(f => f.uploadId === resp.uploadId);
                    if (index > -1) {
                        let imgs = this.images || [];
                        imgs.splice(index, 1, resp);
                        // 超出最大长度进行截断
                        imgs = imgs.slice(0, this.limit);
                        this.$set(this, 'images', imgs);
                        this.$emit('change', {
                            images: this.images.filter(f => !f.loading),
                            inputname: this.inputname
                        });
                        send({
                            type: 'b',
                            action: 'imageCollectUpload_success'
                        });
                    }
                },
                onUploadError: err => {
                    this.$emit('error', err);
                    this.$api.showToast({
                        title: err.toast || '上传失败或图片过大，请重试~',
                        icon: 'none'
                    });
                    const file = err.file || {};
                    const index = this.images.findIndex(f => f.uploadId === file.uploadId);
                    if (index > -1) {
                        this.images.splice(index, 1);
                    }
                    send({
                        type: 'b',
                        action: 'imageCollectUpload_error'
                    });
                }
            });
            send({
                type: 'b',
                action: 'imageCollectUpload_upload'
            });
        },
        handleRemoveImage(index) {
            this.images.splice(index, 1);
            this.$emit('change', {images: this.images, inputname: this.inputname, behavior: 'remove'});
            send({
                type: 'b',
                action: 'imageCollectUpload_removeImg'
            });
        },
        handleImageClick(image) {
            if (image.type === 'video') {
                previewVideo(image.origin);
            } else {
                const images = this.images.filter(item => item.type !== 'video');
                let urls = images.map(item => item.origin);
                let current = image.origin;
                this.$api.previewImage({
                    current,
                    urls
                });
            }
            send({
                type: 'b',
                action: 'imageCollectUpload_previewImg'
            });
        },
    }
};
</script>
<style lang="less" scoped>
/* csshint-disable */
.image-collect {
    position: relative;
    -webkit-box-pack: start;
    -webkit-justify-content: flex-start;
    justify-content: flex-start;
    line-height: 0;
    font-size: 0;
    align-items: center;
    flex-wrap: wrap;

    &-span {
        -webkit-box-flex: 0;
        -webkit-flex: 0 0 auto;
        flex: 0 0 auto;
        margin-bottom: .08rem;
    }

    &-image {
        background-position: center center;
        background-size: cover;
        border-radius: .06rem;
    }

    .box {
        position: relative;
        width: 100%;
        padding-bottom: 100%;

        &-inner {
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
        }
    }
}

.add-wrap {
    border: 1px dotted #fd503e;
    background: #fcfafa;
    border-radius: 6px;
}

.image-collect-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -.09rem;
    margin-top: -.09rem;
    display: inline-block;
    width: .18rem;
    height: .18rem;
    border: 3px solid #555;
    border-bottom-color: transparent;
    -webkit-border-radius: 50%;
    border-radius: 50%;
    -webkit-animation: loading;
    animation: loading;
    -webkit-animation-duration: 2s;
    animation-duration: 2s;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
    -webkit-animation-timing-function: ease-in-out;
    animation-timing-function: ease-in-out;
}

.add-img-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    line-height: normal;
    color: #999;
    text-align: center;

    &__img {
        width: .3rem;
    }
}

.image-collect-remove {
    position: absolute;
    font-size: .1rem;
    width: .22rem;
    height: .22rem;
    line-height: .22rem;
    text-align: center;
    top: -.05rem;
    right: -.08rem;
    z-index: 10;
    color: #fff;
    background: #000;
    border-radius: 100%;
}

.image-collect-play {
    position: absolute;
    font-size: .1rem;
    width: .5rem;
    height: .5rem;
    top: calc(50% - 0.25rem);
    left: calc(50% - 0.25rem);
    text-align: center;
    z-index: 10;
    color: #fff;
    background: rgba(128, 99, 99, 0.4);
    border-radius: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    line-height: 1;

    &__icon {
        font-size: 0.2rem;
    }
}

.choose-type {
    &-item {
        color: #666;
        padding: .29rem;
        text-align: center;
        border-bottom: 1px solid #eee;
        font-size: 0.17rem;

        &:last-of-type {
            border-bottom: none;
        }
    }
}

.upload-tip {
    margin-top: 0.02rem;
    font-size: .14rem;
    line-height: .23rem;
    color: #b8b8b8;
}

@-webkit-keyframes loading {
    from {
        transform: rotate(0);
        -webkit-transform: rotate(0);
    }

    to {
        transform: rotate(360deg);
        -webkit-transform: rotate(360deg);
    }
}

@keyframes loading {
    from {
        transform: rotate(0);
        -webkit-transform: rotate(0);
    }

    to {
        transform: rotate(360deg);
        -webkit-transform: rotate(360deg);
    }
}
</style>


