<template>
    <van-pull-refresh
        class="home"
        :class="[`home-${theme}`]"
        success-text="加载成功"
        success-duration="500"
        v-model="isLoading"
        :head-height="80"
        @refresh="onRefresh"
        pageType="light"
    >
        <van-sticky ref="top" v-if="theme === 'theme6'">
            <div class="padding-safe-top">
                <div class="top">
                    <div class="search" @click="$router.push('/' + $route.params.companyId + '/productSearch')">
                        <img src="@assets/icon-sosuo.png" alt="" />
                        <span>搜索你要的精彩</span>
                    </div>
                </div>
            </div>
        </van-sticky>
        <img src="@assets/png-shouye-guang.png" alt="" v-if="theme === 'theme2'" class="theme2-bg" />
        <img src="@assets/theme3-bg.png" alt="" v-if="theme === 'theme3'" class="theme3-bg" />
        <div class="filter-bg" :style="{ backgroundImage: `url(${bgImg})` }"></div>

        <div class="home-title" v-if="theme === 'theme6'">数字艺术品</div>

        <div class="welcom3" v-if="theme === 'theme3'">
            <van-image
                width="38"
                height="38"
                :radius="38"
                :src="companyInfo.logo || require('@assets/img_default_photo.png')"
            ></van-image>
            <div class="text1" :class="{ text3: isLogin }">{{ companyInfo.name }}</div>
        </div>
        <div class="welcom" v-else-if="theme === 'theme1' || theme === 'theme2'">
            <div class="left">
                <div class="text1">WELCOME</div>
                <div class="text2" :class="{ text3: isLogin }">{{ companyInfo.name }}</div>
            </div>
            <van-image
                width="38"
                height="38"
                :radius="38"
                :src="companyInfo.logo || require('@assets/img_default_photo.png')"
            ></van-image>
        </div>
        <template v-if="theme === 'theme1' || theme === 'theme2' || theme === 'theme3'">
            <swiper
                pagination
                @slideChange="changeMySwiper"
                :space-between="theme === 'theme2' || theme === 'theme3' ? 8 : 16"
                class="mySwiper"
                :class="[`swiper-${theme}`]"
                :autoplay="{ delay: 5000, disableOnInteraction: false }"
                v-if="banners.length > 0"
                slidesPerView="auto"
                centeredSlides
            >
                <swiper-slide v-for="item in banners" :key="item.id">
                    <banner-small :info="item"></banner-small>
                </swiper-slide>
            </swiper>
        </template>
        <div class="large-logo" v-else>
            <van-image
                width="100%"
                height="100%"
                radius="12"
                fit="cover"
                :src="companyInfo.logo || require('@assets/img_default_photo.png')"
            ></van-image>

            <div class="company-descript" v-if="theme === 'theme7'">
                <div class="text1">{{ companyInfo.description }}</div>
                <div class="text2">{{ companyInfo.name }}欢迎您</div>
            </div>
        </div>

        <div class="news-notice" v-if="theme === 'theme6' || theme === 'theme7'">
            <van-notice-bar :text="newsInfo.title" @click="goNews">
                <template #left-icon>
                    <!-- <svg-icon iconClass="redian" class="bar-icon"></svg-icon> -->
                    <img v-if="theme === 'theme6'" src="@assets/home_icon_redian.png" alt="" class="bar-icon" />
                    <img v-else src="@assets/home_icon_redian2.png" alt="" class="bar-icon" />
                </template>

                <template #right-icon>
                    <img src="@assets/icon_bar.png" class="right-bar" alt="" />
                </template>
            </van-notice-bar>
        </div>

        <template v-else>
            <div class="home-title" @click="goNews">
                <span>新闻公告</span>

                <div class="title-more">
                    <span>更多</span>
                    <van-icon name="icon-icon_inter" class-prefix="font_family" />
                </div>
            </div>

            <div class="newsList">
                <news-large v-for="(item, index) in news" :key="index" v-model:info="news[index].obj"></news-large>
            </div>
        </template>

        <div class="home-title" v-if="theme !== 'theme6'">数字艺术品</div>

        <!-- <div class="tabs" v-if="!empty">
            <div class="tab" :class="{ active: active === 0 }" @click="active = 0">数字藏品</div>
            <div class="tab" :class="{ active: active === 1 }" @click="active = 1">产品新闻端</div>
        </div> -->
        <div class="listSwiper">
            <template v-for="(item, index) in products" :key="index">
                <product-small
                    v-if="theme === 'theme6'"
                    v-model:info="products[index].obj"
                    :type="item.type"
                ></product-small>
                <product-large v-else v-model:info="products[index].obj" :type="item.type"></product-large>
            </template>
        </div>
    </van-pull-refresh>
    <van-dialog v-model:show="riskShow" theme="round-button" className="risk">
        <div class="risk-box">
            <img src="@assets/png-bg.png" class="risk-bg" alt="" />
            <div class="risk-content">
                <div class="text1">官方公告</div>
                <div class="text2">ANNOUNCEMENT</div>
                <div class="text3">
                    RAEX绿洲宇宙的探索者：法律许可范围内，最终解释权归RAEX绿洲宇宙平台所有，RAEX绿洲宇宙平台有权对宣传内容进行修改、调整，敬请留意最新宣传资料或公告通知。华储艺术品中心（深圳）有限公司进行拍卖的数字艺术品及RAEX绿洲宇宙平台发售的数字艺术品仅具备收藏欣赏、版权价值。RAEX绿洲宇宙发售的数字艺术品首发价格为官方指导价，版权市场拍卖价格均为数字艺术品持有者自行决定，平台不干涉拍卖价格，对发行的艺术品二手市场价格不构成任何指导建议。平台严禁未满22周岁以及超过55周岁的用户注册平台账号及使用相关功能，请各位探索者理性消费，仔细阅读相关权益，切勿盲从、轻信他人谣言，杜绝恶意炒作，远离一切非法行为，切实维护自身财产安全，共同营造健康数字艺术品生态。
                </div>
            </div>
        </div>
        <template #footer>
            <div class="risk-footer">
                <van-button block color="#E85C58" @click="riskShow = false">我已知晓</van-button>
            </div>
        </template>
    </van-dialog>
</template>

<script>
import product from '../mixins/product';
import { Swiper, SwiperSlide } from 'swiper/vue';

import 'swiper/swiper.min.css';
import 'swiper/swiper-bundle.min.css';

import SwiperCore, { Pagination, Autoplay } from 'swiper';

// install Swiper modules
SwiperCore.use([Pagination, Autoplay]);

import banner from '../mixins/banner';
import ProductLarge from '../components/product/productLarge.vue';
import NewsLarge from '../components/product/NewsLarge.vue';
import ProductSmall from '../components/product/productSmall.vue';
import BannerSmall from '../components/product/BannerSmall.vue';
import { mapState } from 'vuex';

export default {
    name: 'home',
    inject: ['bar', 'setKeeps', 'scrollWrapper', 'changeScroll'],
    mixins: [banner, product],
    components: {
        Swiper,
        SwiperSlide,
        ProductLarge,
        ProductSmall,
        BannerSmall,
        NewsLarge
    },
    computed: {
        ...mapState(['userInfo', 'theme', 'companyId', 'companyInfo']),
        isNewCollections() {
            let products = [...this.products];
            let flag = false;
            products.forEach(item => {
                if (item.createdAt) {
                    if (this.dayjs().isBefore(this.dayjs(item.createdAt, 'YYYY-MM-DD HH:mm:ss').add(6, 'hours'))) {
                        flag = true;
                    }
                }
            });
            return flag;
        },
        isNewNews() {
            let news = [...this.news];
            let flag = false;
            news.forEach(item => {
                if (item.createdAt) {
                    if (this.dayjs().isBefore(this.dayjs(item.createdAt, 'YYYY-MM-DD HH:mm:ss').add(6, 'hours'))) {
                        flag = true;
                    }
                }
            });
            return flag;
        },
        newsInfo() {
            if (this.news.length > 0) {
                return [...this.news][0].obj;
            }
            return {};
        }
    },
    data() {
        return {
            banners: [],
            products: [],
            active: 0,
            news: [],
            loading: false,
            finished: false,
            page: 0,
            empty: false,
            bgImg: '',
            swiperRef: null,
            scrollTop: 0,
            riskShow: false,
            activeIndex: 0
        };
    },
    mounted() {
        if (this.$route.params.companyId) {
            this.$store.dispatch('getCompanyInfo', this.$route.params.companyId);
        }
        if (window.cordova && StatusBar && StatusBar.isVisible) {
            StatusBar.styleDefault();
        }
        this.getInit();
        setTimeout(() => {
            this.showTips();
        }, 500);

        this.$nextTick(() => {
            this.$el.parentNode.childNodes[1].className = this.$el.parentNode.childNodes[1].className.replace(
                / bgBack/,
                ''
            );
        });
        // this.$http.get('sysConfig/get/home_bg').then(res => {
        //     this.bgImg = res.value || '';
        // });
    },
    methods: {
        goNews() {
            this.$router.push({
                name: 'newsList'
            });
        },
        changeSwiper() {
            console.log(this.swiperRef.activeIndex);
            this.active = this.swiperRef.activeIndex;
        },
        changeMySwiper(swiper) {
            this.activeIndex = swiper.activeIndex;
        },
        showTips() {
            let inApp = /#cordova#/i.test(navigator.userAgent);
            let inIos = /iPhone|iPad|iPod/i.test(navigator.userAgent);
            if (inApp && '1' !== window.localStorage.getItem('AppTips')) {
                (inIos
                    ? Promise.resolve()
                    : this.$dialog
                          .confirm({
                              title: 'RAEX宇宙服务协议和隐私政策',
                              message: `在您使用我的各项服务之前，请务必审慎阅读、充分理解<a href="javascript:void(0)" onclick="goFetch('/agreement?page=service')" >《用户隐私协议》</a>、<a href="javascript:void(0)" onclick="goFetch('/agreement')" >《隐私政策》</a>的条款。并且我们会申请获取您的设备信息，以向您提供安全风控服务。同时您应特别注意前述协议中免除或者限制我们责任的条款、对您权利进行限制的条款。如您已详细阅读并同意RAEX宇宙用户协议、隐私政策，请点击【同意并继续】开始使用我们的服务。`,
                              confirmButtonText: '同意并继续',
                              cancelButtonText: '不同意',
                              allowHtml: true
                          })
                          .then(() => {
                              return this.$dialog.confirm({
                                  title: '温馨提示',
                                  message:
                                      '收集个人信息为我们向您提供服务所必须哦。我们仅会将您的个人信息用于为您提供服务，若不同意此协议，我们将无法为您提供服务并退出应用。',
                                  confirmButtonText: '同意',
                                  cancelButtonText: '不同意'
                              });
                          })
                )
                    .then(() => {
                        window.localStorage.setItem('AppTips', '1');
                        this.showRisk();
                        try {
                            window.cordova.plugins.UmengPlugin.initPush(deviceToken => {
                                console.log('deviceToken=' + deviceToken);
                            });
                        } catch (e) {}
                    })
                    .catch(() => {
                        navigator.app.exitApp();
                    });
            } else if (!window.localStorage.getItem('AppTips') && !inIos && inApp) {
                this.$dialog
                    .confirm({
                        title: 'RAEX宇宙服务协议和隐私政策',
                        message: `在您使用我的各项服务之前，请务必审慎阅读、充分理解<a href="javascript:void(0)" onclick="goFetch('/agreement?page=service')" >《用户隐私协议》</a>、<a href="javascript:void(0)" onclick="goFetch('/agreement')" >《隐私政策》</a>的条款。并且我们会申请获取您的设备信息，以向您提供安全风控服务。同时您应特别注意前述协议中免除或者限制我们责任的条款、对您权利进行限制的条款。如您已详细阅读并同意RAEX宇宙用户协议、隐私政策，请点击【同意并继续】开始使用我们的服务。`,
                        confirmButtonText: '同意并继续',
                        cancelButtonText: '不同意',
                        allowHtml: true
                    })
                    .then(() => {
                        return this.$dialog.confirm({
                            title: '温馨提示',
                            message:
                                '收集个人信息为我们向您提供服务所必须哦。我们仅会将您的个人信息用于为您提供服务，若不同意此协议，我们将无法为您提供服务并退出应用。',
                            confirmButtonText: '同意',
                            cancelButtonText: '不同意'
                        });
                    })
                    .then(() => {
                        window.localStorage.setItem('AppTips', '1');
                        this.showRisk();
                        try {
                            window.cordova.plugins.UmengPlugin.initPush(deviceToken => {
                                console.log('deviceToken=' + deviceToken);
                            });
                        } catch (e) {}
                    })
                    .catch(() => {
                        navigator.app.exitApp();
                    });
            } else {
                this.showRisk();
            }
        },
        showRisk() {
            // let show = window.sessionStorage.getItem('riskShow')
            //     ? JSON.parse(window.sessionStorage.getItem('riskShow'))
            //     : false;
            // if (!show) {
            //     this.riskShow = true;
            //     window.sessionStorage.setItem('riskShow', JSON.stringify(true));
            // }
        },
        getInit() {
            this.$toast.loading({
                message: '加载中...',
                forbidClick: true
            });
            return Promise.all([
                this.getBanner(),
                this.getProduct().then(res => {
                    this.products = res.filter(item => {
                        return item.type === 'collection';
                    });
                    this.news = res
                        .filter(item => {
                            return item.type === 'news';
                        })
                        .slice(0, 3);
                })
            ]).then(() => {
                this.$toast.clear();
                return Promise.resolve();
            });
            // this.getNews();
        },
        getProduct() {
            let form = {};
            if (this.companyId) {
                form.companyId = this.companyId;
            }
            return this.$http.get('/collection/recommend', form).then(res => {
                return Promise.resolve(res);
            });
        },
        getBanner() {
            return this.$http
                .post(
                    '/banner/all',
                    {
                        query: {
                            type: 'HOME',
                            del: false,
                            companyId: this.companyId
                        },
                        sort: 'sort,asc;createdAt,desc'
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.banners = res.content;
                    if (this.swiperRef) {
                        this.swiperRef.update();
                    }
                    return Promise.resolve();
                });
        },
        getList() {
            if (this.page === 0) {
                this.list = [];
            }
            this.$http
                .post(
                    '/collection/all',
                    {
                        page: 0,
                        size: 20,
                        query: {
                            onShelf: true,
                            del: false
                        },
                        sort: 'createdAt,desc'
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.list = [...this.list, ...res.content];
                    if (!this.finished) {
                        this.page = this.page + 1;
                    }
                });
        },
        getMiner() {
            this.$http
                .post(
                    '/user/all',
                    {
                        page: 0,
                        query: { minter: true },
                        size: 5,
                        sort: 'sales,desc'
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.miners = res.content;
                    // console.log(this.miners);
                });
        },
        getNews() {
            if (this.page === 0) {
                this.news = [];
            }
            this.loading = true;
            this.finished = false;
            this.empty = false;
            this.$http
                .post(
                    '/news/all',
                    {
                        page: this.page,
                        size: 20,
                        query: {
                            del: false
                        },
                        sort: 'sort,asc;createdAt,desc'
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.news = [...this.news, ...res.content];
                    this.empty = res.empty;
                    this.loading = false;
                    this.finished = res.last;
                    if (!this.finished) {
                        this.page = this.page + 1;
                    }
                });
        },
        setSwiperRef(ref) {
            this.swiperRef = ref;
        },
        onRefresh() {
            this.getInit().then(() => {
                this.isLoading = false;
            });
            // setTimeout(() => {

            // }, 1000);
        },
        changeActive(active) {
            this.active = active;
            this.swiperRef.slideTo(active, 300);
        }
    },
    activated() {
        this.$nextTick(() => {
            if (window.cordova && StatusBar && StatusBar.isVisible) {
                StatusBar.styleDefault();
            }
            this.$nextTick(() => {
                this.$el.parentNode.childNodes[1].className = this.$el.parentNode.childNodes[1].className.replace(
                    / bgBack/,
                    ''
                );
            });
            this.changeScroll(this.scrollTop || 0);
        });
    },
    beforeRouteLeave(to, from, next) {
        this.$el.parentNode.childNodes[1].className =
            this.$el.parentNode.childNodes[1].className.replace(/ bgBack/, '') + ' bgBack';
        if (!to.meta.menuPage && to.path !== '/agreement') {
            this.scrollTop = this.scrollWrapper.scrollTop;
            this.setKeeps(['index', 'home']);
        } else {
            this.scrollTop = 0;
            this.setKeeps(['index', 'home'], false);
        }
        next();
    }
};
</script>

<style lang="less" scoped>
.darkBg {
    background-color: var(--bg);
}
.theme2-bg {
    width: 221px;
    position: absolute;
    top: 0;
    left: 0;
    height: auto;
    z-index: -1;
}
.theme3-bg {
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    height: auto;
    z-index: -1;
}

.home {
    // background-color: @bg3;
    position: relative;
    z-index: 1;
    background-color: var(--bg2);
    padding-top: var(--safe-top);
}

::v-deep(.mySwiper) {
    // height: 255px;
    padding: 16px 0;
    // margin: 0 16px;
    box-sizing: border-box;
    // padding-bottom: 35px;

    .swiper-slide {
        height: 140px;
        padding: 0 16px;
        box-sizing: border-box;
    }

    .swiper-pagination {
        bottom: 30px;
    }

    .swiper-pagination-bullet {
        width: 5px;
        height: 5px;
        border-radius: 5px;
        background: @text3;
        margin: 0 4px;
        opacity: 1;
    }

    .swiper-pagination-bullet-active {
        background: var(--prim);
    }
}
::v-deep(.swiper-theme2),
::v-deep(.swiper-theme3) {
    .swiper-slide {
        width: calc(100vw - 32px);
        height: 414px;
        padding: 0 0;
        display: flex;
        align-items: center;
        .product {
            width: calc(100vw - 32px);
            height: 394px;
            transition: height ease-in-out 0.3s;
        }
        &.swiper-slide-active {
            .product {
                height: 414px;
            }
        }
    }
}

::v-deep(.swiper-theme4),
::v-deep(.swiper-theme5) {
    padding: 20px 0 16px;
    .swiper-slide {
        height: 42.67vw;
    }
}

.large-logo {
    padding: 20px 16px 16px;
    height: 42.67vw;
    overflow: hidden;
}

.home-theme6 {
    .large-logo {
        padding: 4px 16px 16px;
        border-radius: 0px;
    }
}

.home-theme7 {
    position: relative;
    .large-logo {
        padding: 0 0 48px;
        height: 53vw;
    }

    .company-descript {
        background: var(--bg2);
        position: absolute;
        z-index: 2;
        top: 40vw;
        color: var(--text1);
        .flex-col();
        align-items: center;
        left: 16px;
        right: 16px;
        padding: 9px 0 22px;
        box-shadow: 0px 2px 8px 0px rgba(255, 255, 255, 0.1);
        .text1 {
            font-size: 20px;
            font-weight: bold;
            line-height: 28px;
            text-shadow: 0px 0px 4px rgba(0, 0, 0, 0.5);
        }

        .text2 {
            font-size: 12px;
            line-height: 17px;
            text-shadow: 0px 0px 4px rgba(0, 0, 0, 0.5);
            margin-top: 2px;
        }
    }
}

// .swiper-slide {
//     width: 255px;
// }

.list {
    padding: 12px 0 100px;
}

.welcom {
    .flex();
    align-items: flex-end;
    padding: 12px 16px 0;
    .left {
        flex-grow: 1;
        .text1 {
            font-size: 12px;
            font-weight: bold;
            color: #939599;
            line-height: 24px;
        }
        .text2 {
            font-size: 20px;
            font-weight: bold;
            color: #ffffff;
            line-height: 20px;
            letter-spacing: 2px;

            &.text3 {
                letter-spacing: 0px;
                font-weight: normal;
                font-family: SourceHanSans-Medium;
            }
        }
    }
}
.welcom3 {
    .flex-col();
    align-items: center;
    padding: 21px 0 4px;
    .text1 {
        font-size: 20px;
        font-family: SourceHanSans-Medium;
        color: #ffffff;
        line-height: 30px;
        letter-spacing: 1px;
        margin-top: 11px;
        text-shadow: 1px 1px 4px #072756;
    }
}
.listSwiper {
    padding-bottom: 100px;
}
.tabs {
    .flex();
    font-size: 14px;
    color: fade(@text0, 60%);
    line-height: 24px;
    padding: 0 16px;

    .tab + .tab {
        margin-left: 20px;
    }

    .tab {
        position: relative;
        &.active {
            font-weight: bold;
            color: @text0;

            &::after {
                content: '';
                height: 2px;
                background-color: #fff;
                width: 18px;
                position: absolute;
                bottom: -2px;
                left: 50%;
                transform: translateX(-50%);
            }
        }
    }
}

.list-top {
    .flex();
    justify-content: center;
    .text1 {
        font-size: 16px;
        color: @text3;
        line-height: 24px;
        padding: 8px 40px 16px;

        &.active {
            color: #000000;
            font-weight: bold;
            position: relative;

            &::after {
                content: '';
                position: absolute;
                width: 24px;
                height: 2px;
                background: #3ab200;
                border-radius: 1px;
                bottom: 10px;
                left: 50%;
                transform: translateX(-50%);
            }
        }
    }
}

.risk-box {
    position: relative;
    img {
        width: 288px;
        height: 400px;
        display: block;
    }

    .risk-content {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        .flex-col();
        align-items: center;
        .text1 {
            font-size: 20px;
            font-family: ZhenyanGB-Regular, ZhenyanGB;
            color: #3e4293;
            line-height: 20px;
            padding: 22px 0 5px;
            position: relative;
            &::before {
                content: '';
                width: 38px;
                height: 1px;
                background: linear-gradient(-90deg, rgba(62, 66, 147, 0.3) 0%, rgba(62, 66, 147, 0.06) 100%);
                position: absolute;
                left: -50px;
                top: 32px;
            }
            &::after {
                content: '';
                width: 38px;
                height: 1px;
                background: linear-gradient(90deg, rgba(62, 66, 147, 0.3) 0%, rgba(62, 66, 147, 0.06) 100%);
                position: absolute;
                right: -50px;
                top: 32px;
            }
        }
        .text2 {
            font-size: 10px;
            color: rgba(62, 66, 147, 0.5);
            line-height: 14px;
        }
        .text3 {
            align-self: stretch;
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #1c1c1c;
            line-height: 24px;
            margin: 10px 24px;
            height: 254px;
            overflow: auto;
        }
    }
}

.risk-footer {
    padding: 16px 24px 12px;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 12px;
    .van-button {
        border-radius: 8px;
    }
}

.home-title {
    font-size: 18px;
    font-weight: bold;
    color: var(--text1);
    line-height: 24px;
    padding: 10px 16px 8px;
    .flex();

    span {
        flex-grow: 1;
    }

    .title-more {
        .flex();
        font-size: 12px;
        color: #939599;
        .font_family {
            font-weight: normal;
        }
    }
}
.newsList {
    padding-bottom: 8px;
}

/deep/.news-notice {
    padding: 0 16px 16px;
    .van-notice-bar {
        --van-notice-bar-background-color: var(--bglight);
        --van-notice-bar-text-color: var(--info);
        --van-notice-bar-padding: 0 10px;
        position: relative;
        .bar-icon {
            width: 55px;
            height: 16px;
            display: block;
            margin-right: 17px;
            color: var(--prim);
        }

        &::before {
            content: '';
            position: absolute;
            width: 1px;
            height: 10px;
            background: rgba(255, 255, 255, 0.2);
            left: 73px;
            top: 50%;
            transform: translateY(-50%);
        }

        .right-bar {
            width: 18px;
            height: 18px;
            margin-left: 10px;
        }
    }
}

.top {
    display: flex;
    padding: 9px 16px;
    background-color: var(--bg2);
    display: flex;
    align-items: center;

    .search {
        flex-grow: 1;
        background-color: var(--bglight);
        display: flex;
        align-items: center;
        padding: 4px 20px;
        border-radius: 21px;
        img {
            width: 16px;
            height: 16px;
            margin-right: 10px;
        }
        font-size: 14px;
        color: @text3;
        line-height: 24px;
    }
}
</style>
