<template>
    <view
        class="product-doc "
        :class="{ hasBottom: TipStatus }"
        :style="{ paddingBottom: isIphoneX && TipStatus ? '60rpx' : 0 }"
    >
        <view class="category">
            <view class="category-title">图片资料</view>
            <view class="content">
                <view class="cm-none" v-if="imageArchiveList.length === 0">暂无相关资料</view>
                <template v-else>
                    <view class="section" v-for="(item, index) in imageArchiveList" :key="index">
                        <view class="cm-title">{{ item.title }}</view>
                        <view class="cm-time">{{ $reg.formatDate('', item.addTime) }}</view>
                        <view class="cm-img-list cm-list">
                            <template v-if="item.imageList">
                                <image
                                    :src="image.url"
                                    @click="previewImage(i, item.imageList)"
                                    mode="aspectFill"
                                    v-for="(image, i) in imageFormat(item.imageList)"
                                    :key="i"
                                    :style="image.style"
                                ></image>
                            </template>
                            <template v-else>
                                <image
                                    :src="defaultImage"
                                    mode="aspectFill"
                                    v-for="i in item.imageNum"
                                    :key="i"
                                    @click="checkPermission"
                                ></image>
                            </template>
                        </view>
                    </view>
                </template>
            </view>
        </view>
        <view class="category">
            <view class="category-title">视频资料</view>
            <view class="content">
                <view class="cm-none" v-if="videoArchiveList.length === 0">暂无相关资料</view>
                <template v-else>
                    <view class="section" v-for="(item, index) in videoArchiveList" :key="index">
                        <view class="cm-title">{{ item.title }}</view>
                        <view class="cm-time">{{ $reg.formatDate('', item.addTime) }}</view>
                        <view class="cm-video-list">
                            <video
                                class="cm-video"
                                :id="'myVideo' + index"
                                :src="item.fileUrl"
                                :style="videoStyle['myVideo' + index]"
                                controls
                                show-fullscreen-btn
                                show-mute-btn
                                play-btn-position="center"
                                @play="handlePlayer('myVideo' + index)"
                                v-if="item.fileUrl"
                                @loadedmetadata="loadedmetadata"
                            ></video>
                            <view class="cm-video-section" v-else>
                                <image class="cm-video-cover" :src="videoCover"></image>
                                <text class="cm-player-btn" @click="checkPermission()"></text>
                            </view>
                        </view>
                    </view>
                </template>
            </view>
        </view>
        <view class="category cm-file">
            <view class="category-title">文件资料</view>
            <view class="content">
                <view class="cm-none" v-if="fileArchiveList.length === 0">暂无相关资料</view>
                <template v-else>
                    <view class="section" v-for="(item, index) in fileArchiveList" :key="index">
                        <image
                            src="https://static.caimei365.com/app/img/icon2/PDF-app.png"
                            v-if="/\.pdf/.test(item.fileName)"
                        ></image>
                        <image
                            src="https://static.caimei365.com/app/img/icon2/DOC-app.png"
                            v-else-if="/\.doc/.test(item.fileName)"
                        ></image>
                        <image src="https://static.caimei365.com/app/img/icon2/PPT-app.png" v-else></image>
                        <view class="cm-desc">
                            <view class="cm-title">{{ item.title }}</view>
                            <view class="cm-bottom">
                                <view class="cm-time">{{ $reg.formatDate('', item.addTime) }}</view>
                                <view class="cm-preview" @click="previewFile(item)">预览文件</view>
                            </view>
                        </view>
                    </view>
                </template>
            </view>
        </view>
        <view
            class="cm-login"
            :class="{ maxBottom: !bottom && isIphoneX }"
            :style="{ bottom: bottom }"
            v-if="TipStatus"
        >
            <text>{{ TipStatus.text }}</text>
            <view class="cm-btn" @click="nextAction(TipStatus.redirect)">{{ TipStatus.btn }}</view>
        </view>

        <tui-modal
            :show="showModal"
            :content="TipStatus.text"
            shape="circle"
            :button="modalButton"
            fadeIn
            @click="handleModalClick"
        ></tui-modal>
    </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
    props: {
        product: {
            type: Object,
            default: () => {}
        },
        archiveId: {
            type: Number,
            default: 0
        },
        bottom: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            userId: -1,
            prevVideoId: '',
            currentVideoId: '',
            videoContexts: [],
            modalButton: [
                {
                    text: '取消',
                    type: 'gray',
                    plain: true //是否空心
                },
                {
                    text: '确认',
                    customStyle: {
                        color: '#fff',
                        bgColor: 'linear-gradient(90deg, #F28F31 0%, #E15616 100%)'
                    },
                    plain: false
                }
            ],
            showModal: false,
            //用户信息相关
            permission: 5, //用户权限  0可查看，1未登录，2需升级会员机构，3需升级医美会员机构，4需要抵扣采美豆，5无权限查看
            imageArchiveList: [], // 图片资料列表
            videoArchiveList: [], // 视频资料列表
            fileArchiveList: [], // 文件资料列表
            defaultImage: 'https://static.caimei365.com/app/img/icon2/PC-default.png', // 默认图片
            videoCover: 'https://static.caimei365.com/app/img/icon2/video-cover.png', //默认视频封面
            videoStyle: {}
        }
    },
    computed: {
        ...mapState(['isIphoneX']),
        //资料查看状态提示
        TipStatus() {
            // 资料权限
            const statusText = [
                false, // 正常访问
                { text: '请登录后查看！', btn: '去登录', redirect: '/pages/login/login' },
                { text: '请升级成为会员机构后方可查看！', btn: '去升级', redirect: '/pages/login/apply' },
                { text: '请升级成为医美会员机构后方可查看！', btn: '去升级', redirect: '/pages/login/apply' },
                { text: '需抵扣100采美豆方可查看！', btn: '去查看', redirect: 10 },
                { text: '无权限查看！', btn: '确认' }
            ]
            // 0可查看，1未登录，2需升级会员机构，3需升级医美会员机构，4需要抵扣采美豆，5无权限查看
            return statusText[this.permission]
        }
    },
    watch: {
        TipStatus(val) {
            this.$emit('tipStatus', this.TipStatus)
        }
    },
    created() {
        this.userId = uni.getStorageSync('userInfo').userId || -1
        this.getDetail()
    },
    methods: {
        // 获取商品资料详情
        getDetail() {
            this.BeautyArchive.GetProdcutArchiveDetails({
                userId: this.userId,
                archiveId: this.archiveId
            }).then(res => {
                this.imageArchiveList = res.data.imageArchiveList
                this.videoArchiveList = res.data.videoArchiveList
                this.fileArchiveList = res.data.fileArchiveList
                this.permission = res.data.permission
            })
        },
        //采美豆抵扣
        searchArchiveByBean() {
            this.BeautyArchive.SearchArchiveByBeans({
                userId: this.userId,
                archiveId: this.archiveId
            })
                .then(res => {
                    uni.showToast({
                        duration: 1500,
                        title: res.msg
                    })
                    setTimeout(() => {
                        //刷新资料列表
                        this.getDetail()
                    }, 1500)
                })
                .catch(err => {
                    uni.showToast({
                        icon: 'none',
                        duration: 1500,
                        title: err.msg
                    })
                })
        },
        // 获取视频源信息
        loadedmetadata(e) {
            // 获取视频长宽
            const w = e.detail.width //视频真实宽度
            const h = e.detail.height //视频真实高度
            let rw = 0 //视频展示宽度
            let rh = 0 //视频展示宽度
            // 视频宽大于等于高时
            if (w >= h) {
                rw = 702
                rh = (rh * h) / w
            } else {
                rw = 400
                rh = (rw * h) / w
            }
            // 使用set向videoStyle添加样式信息
            this.$set(this.videoStyle, e.currentTarget.id, `width:${rw}rpx;height:${rh}rpx;`)
        },
        // 视频播放
        handlePlayer(id) {
            if (this.checkPermission()) {
                this.handleStop(id)
                return
            }
            if (this.prevVideoId === id) return
            // this.handleFullScreen(id) // 点击播放时全屏
            this.prevVideoId = this.currentVideoId
            // 暂停上一个播放器
            this.handelPause(this.prevVideoId)
            // 保存当前播放器id
            this.currentVideoId = id
        },
        // 开始播放
        handelPlay(id) {
            if (!id) return
            const vContext = uni.createVideoContext(id, this)
            vContext.play()
        },
        // 暂停播放
        handelPause(id) {
            if (!id) return
            const vContext = uni.createVideoContext(id, this)
            vContext.pause()
        },
        // 停止视频
        handleStop(id) {
            if (!id) return
            const vContext = uni.createVideoContext(id, this)
            vContext.stop()
        },
        // 进入全屏
        handleFullScreen(id) {
            if (!id) return
            const vContext = uni.createVideoContext(id, this)
            vContext.requestFullScreen()
        },
        // 预览图片
        previewImage(index, previewImageList) {
            if (this.checkPermission()) return
            const that = this
            uni.previewImage({
                current: index,
                indicator: 'number',
                urls: previewImageList,
                loop: true,
                success() {
                    that.$emit('previewImage', true)
                }
            })
        },
        //用户权限校验拦截
        checkPermission() {
            //permission:查看权限:0可查看，1未登录，2需升级会员机构，3需升级医美会员机构，4需要抵扣采美豆，5无权限查看
            const _self = this
            // 如果 TipStatus 返回false 就放行
            if (!_self.TipStatus) return 0
            this.modalButton[1].text = this.TipStatus.btn
            this.showModal = true
            return -1
        },
        // modal 按钮点击
        handleModalClick(e) {
            // 点击确认按钮
            if (e.index === 1) {
                this.showModal = false
                this.nextAction(this.TipStatus.redirect) //执行下一步
            } else {
                this.showModal = false
            }
        },
        //图片列表处理
        imageFormat(list) {
            const imageList = []
            if (list.length > 2) {
                list.forEach((item, index) => {
                    imageList.push({ url: item, style: '' })
                })
            }
            if (list.length === 1) {
                try {
                    const strArr = list[0]
                        .split('?')[1]
                        .replace(/\&|\=/g, '-')
                        .split('-')
                    const w = strArr[1] // 图片长
                    const h = strArr[3] // 图片高
                    let style = ''
                    if (w > h) {
                        style = `width:600rpx;height:${(600 / w) * h}rpx`
                    } else {
                        style = `height:600rpx;width:${(600 * w) / h}rpx`
                    }
                    imageList.push({ url: list[0], style: style })
                } catch (e) {
                    console.error(
                        '图片链接格式不正确，返回未处理图片，请设置正确的链接：http://image/text.png?width=xx&height=xx'
                    )
                    imageList.push({ url: list[0], style: '' })
                }
            }
            if (list.length === 2) {
                const style = 'width:300rpx;height:300rpx;'
                imageList.push({ url: list[0], style })
                imageList.push({ url: list[1], style })
            }
            return imageList
        },
        // 点击按钮后要做的事
        nextAction(redirect) {
            const _self = this
            if (typeof redirect == 'string') {
                // 跳转链接
                this.$api.navigateTo(redirect)
            }
            if (redirect === 10) {
                this.searchArchiveByBean()
            }
        },
        // 文件预览
        previewFile(file) {
            if (this.checkPermission()) return
            // 获取文件后缀
            // const index = file.fileName.lastIndexOf('.')
            // const suffix = file.fileName.substring(index)
            this.openDocument(file)
            // if (suffix === '.doc' || suffix === '.ppt' || suffix === '.pptx' || suffix === '.docx') {
            //     //先将链接缓存
            //     uni.setStorageSync('openLink', file.htmlUrl)
            //     this.openDocument(file.fileUrl)
            //     // this.$api.navigateTo('/pages/h5/article/path?key=openLink&type=1')
            // } else if (suffix === '.pdf') {
            //     //先将链接缓存
            //     uni.setStorageSync('openLink', file.fileUrl)
            //     this.$api.navigateTo('/pages/h5/article/path?key=openLink&type=2')
            // } else {
            //     // 不支持的文件
            //     return uni.showModal({
            //         content: `${suffix}类型文件暂不支持预览`,
            //         cancelColor: '#666',
            //         confirmColor: '#E15616'
            //     })
            // }
        },
        // 打开文档
        openDocument(file) {
            uni.showLoading({
                title:'加载中'
            })
            // 获取文件后缀
            const index = file.fileName.lastIndexOf('.')
            const suffix = file.fileName.substring(index + 1)
            // 下载文件
            uni.downloadFile({
                url: file.fileUrl,
                success(res) {
                    const filePath = res.tempFilePath
                    console.log(filePath) 
                    // 打开文件
                    uni.openDocument({
                        filePath: filePath,
                        fileType: suffix,
                        success(res) {
                            uni.showToast({
                                icon:'success',
                                title:'打开成功',
                                duration: 1200
                            })
                            uni.hideLoading()
                        },
                        fail(err) {
                            if(err.errMsg.indexOf('fail filetype not supported')){
                                uni.showModal({
                                    content: '不支持的文件预览',
                                    cancelColor: '#666',
                                    confirmColor: '#E15616'
                                })
                            }
                            uni.hideLoading()
                        }
                    })
                },
                fail(err){
                    uni.showToast({
                        title: JSON.stringify(err),
                        icon:'none',
                        duration: 5000
                    })
                    uni.hideLoading()
                },
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.product-doc {
    background: #f7f7f7;
}
.hasBottom {
    padding-bottom: 90rpx;
}
.cm-login {
    position: fixed;
    left: 24rpx;
    bottom: 115rpx; // 包含商品导航
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 32rpx;
    width: 702rpx;
    height: 90rpx;
    background: #ffe6dc;
    border-radius: 16px;
    box-sizing: border-box;
    z-index: 9;
    &.maxBottom {
        bottom: 175rpx;
    }
    text {
        font-size: 26rpx;
        color: #e15616;
    }
    .cm-btn {
        width: 136rpx;
        height: 48rpx;
        background: #e15616;
        border-radius: 28px;
        font-size: 26rpx;
        text-align: center;
        line-height: 48rpx;
        color: #ffffff;
    }
}
.category {
    padding: 0 24rpx;
    margin-bottom: 20rpx;
    background: #fff;
    .cm-video-section {
        position: relative;
        width: 702rpx;
        height: 402rpx;
        .cm-video-cover {
            width: 702rpx;
            height: 402rpx;
        }
        .cm-player-btn {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            z-index: 5;
            width: 56rpx;
            height: 56rpx;
            background: url(https://static.caimei365.com/app/img/icon2/H5-plalyer.png) center no-repeat;
            background-size: 56rpx 56rpx;
        }
    }
    .category-title {
        padding-top: 24rpx;
        padding-bottom: 8rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #333333;
        border-bottom: 1px solid #f0f0f0;
    }
    .cm-none {
        height: 37rpx;
        margin: 24rpx 0 0 0;
        padding-bottom: 48rpx;
        font-size: 26rpx;
        font-weight: 400;
        line-height: 37rpx;
        color: #333333;
    }
    &.cm-file {
        .section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            image {
                width: 88rpx;
                height: 88rpx;
            }
            .cm-title {
                height: 74rpx;
            }
            .cm-desc {
                width: 582rpx;
            }
            .cm-bottom {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16rpx 0 0;
                .cm-preview {
                    font-size: 26rpx;
                    font-weight: 400;
                    color: #e15616;
                }
                .cm-time {
                    padding: 0;
                }
            }
        }
    }
    .section {
        padding-bottom: 24rpx;
        border-bottom: 1px solid #f0f0f0;
        &:last-child {
            border-bottom: 0;
        }
        .cm-title {
            display: -webkit-box;
            max-height: 74rpx;
            margin-top: 24rpx;
            font-size: 26rpx;
            font-weight: 400;
            line-height: 1.5;
            color: #333333;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            word-break: break-all;
            text-align: justify;
        }
        .cm-time {
            padding: 8rpx 0;
            font-size: 22rpx;
            font-weight: 400;
            color: #b2b2b2;
        }
        .cm-img-list {
            display: flex;
            justify-content: flex-start;
            flex-wrap: wrap;
            &.cm-list {
                image {
                    width: 162rpx;
                    height: 162rpx;
                    margin: 18rpx 18rpx 0 0;
                    box-sizing: border-box;
                    border-radius: 6rpx;
                    border: 1px solid #e1e1e1;
                    &:nth-child(4n) {
                        margin-right: 0;
                    }
                }
            }
            &.cm-one {
                max-width: 400rpx;
                max-height: 400rpx;
                image {
                    box-sizing: border-box;
                    border-radius: 6rpx;
                    border: 1px solid #e1e1e1;
                }
            }
        }
        .cm-video-list {
            margin-top: 18rpx;
            // // width: 702rpx;
            // // height: 420rpx;
            // width: 544rpx;
            // height: 960rpx;
            // .cm-video {
            //     width: 100% !important;
            //     max-width: 100%;
            //     min-width: 100%;
            //     display: flex;
            //     // max-height: 420rpx;
            //     // width: 100%;
            //     height: 100%;
            //     background: #000;
            // }
        }
    }
}
</style>
