<template>
    <div class="Appindex">
        <!-- 顶部 -->
        <view class="head">
            <!-- 轮播图 -->
            <swiper-banner :radius="1" imgScale="5:2" :imgArr="BannerImg" :duration="1000" :interval="5000" :circular="true" :autoplay="true" @goList="goList" :indicator-dots="true" indicator-active-color="#12B280" indicator-color="rgba(255, 255, 255, .82)"></swiper-banner>
            <!-- 轮播图-end -->
            <!-- 公告 -->
            <view class="head_notice clearfix">
                <view class="notice_title" @click="goNoticeList">
                    <image class="gg_img" src="@/static/img/gg.png"></image>
                </view>
                <swiper class="notice_swiper" vertical autoplay circular :interval="5000" :duration="1000">
                    <swiper-item v-for="(item, index) in not_list" :key="index" @click="toDetail(item.article_id)">
                        <text class="not_list ellipsis">{{ item.title }}</text>
                        <text class="not_ico iconfont">&#xe62e;</text>
                    </swiper-item>
                </swiper>
            </view>
            <!-- 公告-end -->
            <!-- 专区入口 -->
            <div class="l_tabBar flex_r flex_jb">
                <div class="search-box flex_r flex_jb flex_ac">
                    <div class="district" @click="showAddress = !showAddress">
                        <span>{{ LocationCity }}</span>
                        <span class="iconfont">&#xe62f;</span>
                    </div>
                    <div class="search flex_r flex_jb flex_ac">
                        <span class="iconfont">&#xe661;</span>
                        <input v-model="searchKey" @confirm="toSearch" class="inp" placeholder="搜索你要的内容">
                        <span class="search_btn" @click="toSearch">搜索</span>
                    </div>
                    <!-- <div class="scan-ico iconfont">&#xe8cf;</div> -->
                </div>
                <div class="item" v-for="(i,s) in tabs" :key="s" @click="goto(i.url)">
                    <img :src="i.ico" alt="" class="ico">
                    <!-- <div class="tit">{{ i.tit }}</div> -->
                </div>
            </div>
            <!-- 专区-end -->
            <!-- 活动 -->
            <view class="activity" v-if="homeImg.length">
                <image class="act_img act_one_img" :src="homeImg[0].image" @click="toActivePage(homeImg[0])" mode=""></image>
                <view class="act_other">
                    <image class="act_img act_two_img" :src="homeImg[1].image" mode="" @click="toActivePage(homeImg[1])"></image>
                    <image class="act_img act_two_img" :src="homeImg[2].image" @click="toActivePage(homeImg[2])" mode=""></image>
                </view>
            </view>
            <!-- 活动-end -->
        </view>
        <view class="bou_head flex_r flex_ac flex_jc">
            <image class="bou_img" src="/static/sgin/left.png" mode=""></image>
            <view class="bou_title">今日推荐</view>
            <image class="bou_img" src="/static/sgin/right.png" mode=""></image>
        </view>
        <view class="list_bar">
            <view class="product-list">
                <view class="product" v-for="(i, s) in productList" :key="s" @click="NavToGoodsDetail(i.id, i.type)">
                    <view class="image-view">
                        <image class="product-image" :src="i.original_img"></image>
                    </view>
                    <view class="content-view">
                        <view :class="['product-title', 'ellipsis']">{{ i.goods_name }}</view>
                        <view class="product-price">
                            <template v-if="i.type == 1">
                                <text class="product-price-original">{{ i.total_amount }}</text>
                                <text class="product-price-msg">（含服务费{{$h.Mul(i.service,2)}}元）</text>
                            </template>
                            <text class="product-price-original" v-else>{{ i.price }}</text>
                            <text class="product-text" v-if="[3,4].includes(i.type)">赠<text class="corFE2C15">{{ i.give_cha_bao }}</text>茶宝</text>
                        </view>
                        <view class="product-txt" v-if="i.type == 4">
                            <text class="product-price-favour">{{i.market_price}}</text>
                            <text class="product-text">消费金抵</text>
                            <span class="corFE2C15">￥{{ Number(i.consume) }}</span>
                        </view>
                        <!-- <view class="product-txt" v-if="i.type == 1">赠送{{ i.give_integral + "批发券" }}</view> -->
                        <view class="product-txt" v-if="[3].includes(i.type)">限时赠送<text class="corFE2C15">{{ i.teac }}</text>TeaC</view>
                        <view class="product-txt fenxiang" v-if="[3].includes(i.type)">
                            <text class="iconfont red">&#xe62b;</text>
                            <text class="red">分享约获得 {{ i.first_teac }} {{i.type==3?'TeaC':'现金'}}</text>
                        </view>
                        <view v-if="[4].includes(i.type)" class="flex_r flex_ac">
                            <view class="product-txt">赠<text class="corFE2C15">{{ i.teac }}</text>TeaC</view>
                            <!-- <view class="product-txt fenxiang flex_r flex_ac" style="background-color: rgba(0, 0, 0, 0);">
                                <text class="iconfont red">&#xe62b;</text>
                                <text class="red">{{ i.first_teac }}</text>
                            </view> -->
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="fz_w_text">让数字经济赋能美好生活！</view>
        <!-- 城市选择 -->
        <h-address @select="selectaddress" :visible.sync="showAddress" />
        <!-- 隐私指引 -->
        <!-- <xh-privacy title="隐私保护指引" color="#18bb88"></xh-privacy> -->
        <!-- #ifdef APP-PLUS -->
        <uni-popup ref="popup">
            <view class="progressBox">
                <icon type="loading" size="26"/>
                <text class="words">下载中 请勿退出 {{ totalBytesWritten + " / " + totalBytesExpectedToWrite }}</text>
            </view>
        </uni-popup>
        <!-- #endif -->
    </div>
</template>
<script>
// import xhPrivacy from "@/components/xh-privacy/xh-privacy.vue"; //隐私保护指引
import swiperBanner from "@/components/swiperBanner/index.vue"; //轮播
import hAddress from "@/components/h-address/address.vue"; //城市选择
// import tabs from '@/static/js/tabs' //专区入口
import { post } from "@/request/api.js";
import { formatBytes } from "@/utils/index";
export default {
    name: "Appindex",
    components: {
        swiperBanner, //轮播
        hAddress
        // xhPrivacy,
    },
    data() {
        return {
            BannerImg: [], // 轮播图列表
            not_list: [], // 公告列表
            homeImg: "", //活动列表
            productList: [], //商品数据
            searchKey: "", //搜索关键词
            LocationCity: "中国",
            showAddress: false,
            tabs: [],
            totalBytesWritten: "0B", // 已经下载的数据长度
            totalBytesExpectedToWrite: "0B", // 预期需要下载的数据总长度
            filePath:"",
            percentVal:0,
            newAppInfo:{}
        };
    },
    onLoad(option) {
        this.getToCity()
        this.loadData()
        // uni.Luserfun()
        // #ifdef APP-PLUS
        this.getNewVersion()
        // #endif
    },
    onShow() {
        this.getBanner(); //获取轮播图
        this.getAnnounce(); //获取公告列表
        this.gethomeImg(); //活动列表
        this.getTabs(); //获取专区
    },
    onHide() {},
    methods: {
        loadData() {
            post("v1/goods/indexGoods").then((res) => {
                if (res.code === 0) {
                    this.productList = res.data.data;
                }
            });
            
        },
        getNewVersion(){
            post("v1/getAppVersion").then((res) => {
                if (res.code === 0) {
                    console.log(res.data.data);
                    if(plus.os.name == "Android"){
                        this.filePath = res.data.data.android.url
                        this.newAppInfo = res.data.data.android
                        // 获取当前版本
                        plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
                            console.log();
                            if(wgtinfo.versionCode < this.newAppInfo.version){
                                this.update()
                            }
                        });
                    }
                    
                }
            });
        },
        // 跳转到商品详情页
        NavToGoodsDetail(id, type) {
            this.goto("/pages/product/p_details", { id, type });
        },
        // 获取轮播图
        getBanner() {
            post("v1/banner").then((res) => {
                if (res.code === 0) {
                    this.BannerImg = [];
                    res.data.data.forEach((e) => {
                        if (e.image) this.BannerImg.push(e.image);
                    });
                }
            });
        },
        // 获取专区
        getTabs() {
            post("local/menu/list").then((res) => {
                if (res.code === 0) {
                    this.tabs = res.data
                }
            });
        },
        // 活动列表
        gethomeImg() {
            post("v1/homeImg").then((res) => {
                if (res.code === 0) {
                    this.homeImg = res.data.data
                }
            });
        },
        // 跳转公告列表页
        goNoticeList() {
            this.goto("/pages/consultation-list/index");
        },
        // 获取公告列表
        getAnnounce() {
            post("v1/notice", { is_index: 1 }).then((res) => {
                if (res.code === 0) {
                    this.not_list = res.data.data;
                }
            });
        },
        //跳转公告详情
        toDetail(id) {
            this.goto("/pages/notice/detail", { id });
        },
        // 轮播图跳转
        goList(e) {},
        // 金刚区跳转
        setPageUrl(item) {
            if ([1, 3, 4, 6].includes(item.type)) {
                this.goto("/pages/product/productRetail", { type: item.type });
            } else if (item.type == 2) {
                this.goto("/pages/product/productWholesale", { type: 2 });
            } else if (item.type == 5) {
                this.goto("/pages/product/productTeaBaby", { type: item.type });
            } else {
                appEv.errTips("此功能暂未开放！");
                return false;
            }
        },
        toActivePage(item){
            let istab = item.url.indexOf('tab=1') 
            if(istab>0){
                let url = item.url.split('?')[0]
                uni.switchTab({
                    url: url
                })
            }else{
                this.goto(item.url)
            }
            
        },
        goVipGift() {
            this.goto("/pages/product/productRetail", { type: 4, is_vip: 1 });
        },
        // 搜索
        toSearch() {
            this.goto("/pagesC/settledMerchant/index", { key: this.searchKey });
        },
        // 获取当前城市
        async getToCity() {
            let { lat, lng } = await uni.Location();
            post("local/hotel/city", { longitude: lng, latitude: lat }).then(res => {
                if (res.code == 0) {
                    let da = res.data
                    // this.LocationCity = da.cityName;
                }
            })
        },
        // 选择城市
        selectaddress(da) {
            this.LocationCity = da.cityName;
            this.showAddress = false;
        },
        update(){
            const _this = this;
            uni.showModal({
                title: "版本更新",
                content: "APP有新版本发布，点击 立即更新 进行最新版本下载。",
                showCancel: this.newAppInfo.is_mast == 1 ? true: false,
                confirmText: "立即更新",
                cancelText: "稍后进行",
                success: function (res) {
                if (res.confirm) {
                    _this.$refs.popup.open()
                    
                    // _this.show = true; // show变量控制一个下载进度弹框（这个UI样式自己写即可）
                    // 创建一个下载任务，并根据后端返回的apk静态资源地址filePath进行下载
                  
                    let downloadTask = uni.downloadFile({
                        url: _this.filePath,
                        success: (res) => {
                        console.log(res, "下载成功");
                        this.updateProgressShow = false;
                        if (res.statusCode === 200) {
                            _this.$refs.popup.close()
                            plus.runtime.install(
                            res.tempFilePath,
                            {},
                            function () {
                                console.log("install success...");
                                plus.runtime.restart();
                                // uni.hideLoading();
                                uni.setStorageSync("wgtinfo", null);
                            },
                            function (e) {
                                uni.showToast({
                                    icon: "error",
                                    title: "更新失败",
                                    duration: 1500,
                                });
                            }
                            );
                        } else {
                            _this.$refs.popup.close()
                            uni.showToast({
                                icon: "error",
                                title: "更新失败",
                                duration: 1500,
                            });
                        }
                        },
                        fail: (err) => {
                            _this.$refs.popup.close()
                            uni.showToast({
                                icon: "error",
                                title: "更新失败",
                                duration: 1500,
                            });
                        },
                    });
                    downloadTask.onProgressUpdate((res) => {
                        // console.log(res, "进度");
                        // console.log("下载进度" + res.progress);
                        // console.log("已经下载的数据长度" + res.totalBytesWritten);
                        // console.log(
                        //   "预期需要下载的数据总长度" + res.totalBytesExpectedToWrite
                        // );
                        let totalBytesWritten = formatBytes(res.totalBytesWritten);
                        let totalBytesExpectedToWrite = formatBytes(
                        res.totalBytesExpectedToWrite
                        );
                        let num1 = totalBytesWritten.fileSize.split(
                        totalBytesWritten.matchUnit.unitName
                        );
                        let num2 = totalBytesExpectedToWrite.fileSize.split(
                        totalBytesExpectedToWrite.matchUnit.unitName
                        );
                        _this.totalBytesWritten =
                        Math.floor(num1[0] * 100) / 100 +
                        totalBytesWritten.matchUnit.unitName;
                        _this.totalBytesExpectedToWrite =
                        Math.floor(num2[0] * 100) / 100 +
                        totalBytesExpectedToWrite.matchUnit.unitName;
                        _this.percentVal = res.progress;
                    });
                } else if (res.cancel) {
                    console.log("稍后更新");
                }
                },
            });
    
        }
    },
    computed: {},
    watch: {},
};
</script>
<style scoped lang='scss'>
.head {
    padding: 12rpx 28rpx;
}

.head_search {
    width: 100%;
    height: 64rpx;
    line-height: 64rpx;
    background: #f3f5f7;
    border-radius: 32rpx;
    text-align: center;
    font-size: 28rpx;
    color: #bbbbbb;
    margin-bottom: 26rpx;

    .search_text {
        margin-left: 14rpx;
    }
}

.head_notice {
    margin: 30rpx 0;

    .notice_title {
        width: 130rpx;
        height: 40rpx;
        float: left;

        .gg_img {
            width: 100%;
            height: 40rpx;
        }
    }

    .notice_swiper {
        height: 40rpx;
        padding-left: 20rpx;
        font-size: 28rpx;
        float: left;
        box-sizing: border-box;
        width: calc(100% - 130rpx);

        .not_list {
            width: calc(100% - 50rpx);
        }

        .not_ico {
            width: 30rpx;
            font-size: 28rpx;
            color: #999;
        }

        .not_list,
        .not_ico {
            display: inline-block;
            vertical-align: middle;
            height: 40rpx;
            line-height: 40rpx;
        }
    }
}

.l_tabBar {
    margin: 32rpx 0;
    background-color: #fff;
    padding: 10rpx 20rpx;
    border-radius: 10rpx;
    box-shadow: 4rpx 4rpx 8rpx 4rpx rgba(0, 0, 0, 0.12);
    flex-wrap: wrap;

    .search-box {
        width: 100%;
        padding: 10rpx;
        margin-bottom: 12rpx;

        .district {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;

            .iconfont {
                font-size: 20rpx;
                margin-left: 12rpx;
            }
        }

        .search {
            border: 1px solid #D78C2E;
            height: 60rpx;
            line-height: 60rpx;
            padding-left: 20rpx;
            border-radius: 31rpx;

            .iconfont {
                font-size: 30rpx;
            }

            .inp {
                font-size: 25rpx;
                padding: 0 8rpx;
                width: 300rpx;
            }

            .search_btn {
                background-color: #D78C2E;
                height: 100%;
                color: #fff;
                border-radius: 31rpx;
                font-size: 28rpx;
                padding: 0 28rpx;
            }
        }

        .scan-ico {
            font-size: 55rpx;
        }
    }

    .item {
        width: 105rpx;
        margin: 10rpx 10rpx;
    }

    .ico {
        width: 100%;
        height: 138rpx;
    }

    // .tit{
    //   font-size: 26rpx;
    //   text-align: center;
    // }
}

.bou_head {
    width: 100%;
    height: 114rpx;
    // margin-top: 50rpx;

    .bou_img {
        width: 92rpx;
        height: 30rpx;
    }

    .bou_title {
        height: 30rpx;
        line-height: 30rpx;
        font-size: 36rpx;
        color: #121212;
        font-weight: bold;
        margin: 0 36rpx;
    }
}

// 活动
.activity {
    .act_one_img {
        display: inline-block;
        width: 300rpx;
        height: 378rpx;
        margin-right: 10rpx;
    }

    .act_other {
        display: inline-block;
        width: calc(100% - 300rpx - 10rpx);
    }

    .act_two_img {
        width: 100%;
        height: 185rpx;
    }

    .act_img {
        border-radius: 10rpx;
    }
}

// 活动-end

// 商品列表
.list_bar {
    .tit {
        text-align: center;
        font-size: 36rpx;
        color: #121212;
        padding: 40rpx 0 20rpx;
        font-weight: bold;
    }
}

.product-list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    padding: 0 30rpx;

    .product {
        width: 48.5%;
        margin-bottom: 20rpx;
        padding-bottom: 12rpx;
        border-radius: 10rpx;
        box-shadow: 4rpx 4rpx 8rpx 4rpx rgba(0, 0, 0, 0.12);

        &:nth-child(2n) {
            margin-left: 3%;
        }
    }

    .product-image {
        border-radius: 10rpx 10rpx 0 0;
        width: 100%;
        height: 42.3vw;
        object-fit: cover;
    }

    .content-view {
        padding: 0 16rpx;
    }

    .product-title {
        width: 100%;
        overflow: hidden;
        line-height: 1.5;
        font-size: 28rpx;
        color: #121212;
    }

    .product-price {
        color: #121212;
        font-size: 28rpx;
        position: relative;
    }

    .product-price-original {
        color: #18bb88;
        font-size: 32rpx;
        font-weight: bold;

        &:before {
            content: "￥";
            font-size: 20rpx;
        }
    }

    .product-price-favour {
        color: #888888;
        text-decoration: line-through;
        margin-left: 20rpx;
    }

    .product-tip {
        position: absolute;
        right: 20rpx;
        background-color: #ff3333;
        color: #ffffff;
        padding: 0 20rpx;
        border-radius: 10rpx;
    }

    .product-unit {
        font-size: 24rpx;
        color: #18bb88;
    }

    .product-txt,
    .product-text {
        font-size: 22rpx;
        color: #787878;

        .iconfont {
            margin-right: 3rpx;
        }
    }

    .product-price-msg {
        font-size: 20rpx;
        color: #ff6d44;
    }

    .product-text {
        margin-left: 16rpx;
    }

    .red {
        color: #FA2E18;
    }

    .fenxiang {
        font-size: 20rpx;
        background: rgba(250, 46, 24, 0.08);
        display: inline-block;
        border-radius: 6rpx;
        padding: 0 16rpx;
    }
}

.progressBox{
    padding: 40rpx;
    border-radius: 4rpx;
    background-color: #fff;
}
</style>