<template>
    <van-pull-refresh
        success-text="加载成功"
        success-duration="500"
        class="discover"
        v-model="isLoading"
        @refresh="onRefresh"
    >
        <van-sticky ref="top">
            <div class="padding-safe-top" style="background: #222426">
                <div class="top">
                    <div class="top-btn">
                        <div class="btn" :class="{ active: active === 'explore' }" @click="changeActive('explore')">
                            我拥有的
                        </div>
                        <div
                            class="btn"
                            v-if="!$store.state.reviewPay"
                            :class="{ active: active === 'creator' }"
                            @click="changeActive('creator')"
                        >
                            我卖出的
                        </div>
                        <div
                            class="btn"
                            v-if="companyInfo.airdrop"
                            :class="{ active: active === 'coupon' }"
                            @click="changeActive('coupon')"
                        >
                            兑换券
                        </div>
                    </div>
                    <div
                        class="search"
                        v-if="isLogin && active !== 'coupon'"
                        @click="$router.push('/' + this.$route.params.companyId + '/assetSearch?status=' + status)"
                    >
                        <img src="@assets/svgs/search.svg" alt="" />
                    </div>
                </div>

                <van-tabs
                    class="darkTabs"
                    v-model:active="type"
                    line-width="16"
                    line-height="2"
                    :ellipsis="false"
                    @click="changeTab"
                >
                    <van-tab
                        :title="item.label"
                        :name="item.value"
                        :title-class="item.type === 'select' && sortDes ? sortDes : ''"
                        :key="index"
                        v-for="(item, index) in typeOptions"
                    >
                        <template v-if="item.type === 'select'" #title>
                            <div class="tab">
                                <span>{{ item.label }}</span>
                                <van-icon size="8" name="arrow-up" />
                                <van-icon size="8" name="arrow-down" />
                            </div>
                        </template>
                    </van-tab>
                </van-tabs>
            </div>

            <!-- <van-button
        color="#272828"
        round
        size="mini"
        icon="arrow-down"
        icon-position="right"
        class="select"
        @click="showSelect = true"
      >
        全部
      </van-button> -->
        </van-sticky>

        <van-list
            class="box-list"
            :style="{
                paddingBottom: showList.length % 3 === 0 ? '35.73vw' : '20px'
            }"
            :class="{ couponList: active === 'coupon', roomList: active === 'showRoom' }"
            v-model:loading="loading"
            :finished="finished"
            finished-text=""
            @load="getList"
        >
            <template v-for="(item, index) in showList" :key="index">
                <coupon-info :info="item" v-if="active == 'coupon'"></coupon-info>
                <show-info v-model:info="list[index]" v-else-if="active == 'showRoom'"></show-info>
                <div
                    class="asset-list"
                    v-else
                    :style="{
                        backgroundImage:
                            active !== 'coupon' && active !== 'showRoom' && showList.length > 0
                                ? `url(${require('../assets/png-zhantai.png')})`
                                : ''
                    }"
                >
                    <asset-info
                        :info="asset"
                        v-for="(asset, assetIndex) in item"
                        :key="assetIndex"
                        :num="asset.num"
                        @showMore="showMore"
                    ></asset-info>
                </div>
            </template>

            <van-empty
                v-if="empty || (showList.length === 0 && !loading)"
                :description="active == 'coupon' ? '你还没有优惠券哦～' : '你还没有藏品哦～'"
                :image="require('@assets/kong_black.png')"
            />
            <img src="../assets/icon_zhiding.png" @click="goTop" class="goTop" v-if="bodyScroll > 100" alt="" />
        </van-list>
        <van-action-sheet
            ref="action"
            v-model:show="showSelect"
            description="选择筛选方式"
            :actions="actions"
            cancel-text="取消"
            close-on-click-action
        />

        <div class="tabbar-placeholder"></div>
    </van-pull-refresh>

    <van-overlay :show="show" :lock-scroll="false" @click="show = false" z-index="99">
        <div class="wrapper" @click.stop>
            <div class="wrapper-title">{{ moreTitle }}</div>
            <div class="wrapper-box">
                <van-list
                    v-model:loading="assetLoading"
                    :finished="assetFinished"
                    :immediate-check="false"
                    finished-text=""
                    loading-text="加载中..."
                    @load="getMoreList"
                >
                    <asset-info-se :info="asset" v-for="asset in assetList" :key="asset.id"></asset-info-se>
                </van-list>
            </div>
            <img src="@assets/icon_fenxiang_close.png" @click="show = false" alt="" class="wrapper-close" />
        </div>
    </van-overlay>
</template>

<script>
import { mapState } from 'vuex';
import AssetInfo from '../components/asset/assetInfo.vue';
import AssetInfoSe from '../components/asset/assetInfoSe.vue';
import ShowInfo from '../components/asset/showInfo.vue';
import CouponInfo from '../components/CouponInfo.vue';
import asset from '../mixins/asset';
import coupon from '../mixins/coupon';
export default {
    name: 'store',
    mixins: [asset, coupon],
    inject: ['bar', 'setKeeps', 'scrollWrapper', 'changeScroll', 'bodyScroll'],
    components: {
        AssetInfo,
        AssetInfoSe,
        CouponInfo,
        ShowInfo
    },
    data() {
        return {
            active: 'explore',
            stiky: null,
            type: '',
            empty: false,
            list: [],
            label: '全部',
            showSelect: false,
            actions: [{ name: '选项一' }, { name: '选项二' }, { name: '选项三' }],
            action: null,
            loading: false,
            finished: false,
            page: 0,
            name1: '',
            name: '',
            scrollTop: 0,
            sortDes: '',
            showRoom: false,
            show: false,
            moreTitle: '',
            assetLoading: false,
            assetFinished: false,
            assetPage: 0,
            assetList: []
        };
    },
    computed: {
        ...mapState(['companyId', 'companyInfo']),
        typeOptions() {
            if (this.active === 'explore') {
                if (!this.$store.state.reviewPay) {
                    return [
                        {
                            label: '全部',
                            value: '',
                            type: ''
                        },
                        {
                            label: '寄售',
                            value: 'ON_SALE',
                            type: ''
                        },
                        {
                            label: '仅展示',
                            value: 'NORMAL',
                            type: ''
                        },
                        {
                            label: '未展示',
                            value: 'NOT_NORMAL',
                            type: ''
                        }
                    ];
                } else {
                    return [
                        {
                            label: '全部',
                            value: '',
                            type: ''
                        },
                        {
                            label: '仅展示',
                            value: 'NORMAL',
                            type: ''
                        }
                    ];
                }
            } else if (this.active === 'showRoom') {
                return [
                    {
                        label: '全部',
                        value: '',
                        type: ''
                    },
                    {
                        label: '展览中',
                        value: true,
                        type: ''
                    },
                    {
                        label: '未展览',
                        value: false,
                        type: ''
                    }
                ];
            } else if (this.active === 'creator') {
                return [
                    {
                        label: '市场交易',
                        value: 'TRANSFERRED',
                        type: ''
                    }
                    // {
                    //     label: '价格',
                    //     value: 'price',
                    //     type: 'select'
                    // }
                ];
            } else {
                return [
                    {
                        label: '未使用',
                        value: 'CAN_USE',
                        type: ''
                    },
                    {
                        label: '不可用',
                        value: 'CANNOT_USE',
                        type: ''
                    }
                ];
            }
        },
        showList() {
            if (this.active === 'coupon') {
                return [...this.list].filter(item => {
                    if (this.type === 'CAN_USE') {
                        return this.checkTime(item);
                    } else {
                        return !this.checkTime(item);
                    }
                });
            } else if (this.active == 'showRoom') {
                return this.list;
            } else {
                let list = [...this.list];
                let _list = [];
                for (let i = 0; i <= Math.floor(list.length / 3); i++) {
                    _list.push(list.slice(i * 3, (i + 1) * 3));
                }
                return _list.filter(item => {
                    return item.length > 0;
                });
            }
        },
        sort() {
            return 'createdAt,desc';
        },
        url() {
            if (this.active === 'coupon') {
                return '/userCoupon/all';
            } else if (this.active === 'showRoom') {
                return '/showroom/all';
            } else if (this.active === 'explore') {
                return '/assetSuperimposition/all';
            } else {
                return 'asset/all';
            }
        },
        status() {
            if (this.active === 'explore') {
                if (this.type === 'paimai') {
                    return 'AUCTIONING';
                } else {
                    return 'NORMAL,TRADING,GIFTING,MINTING,AUCTIONING';
                }
            } else if (this.active === 'creator') {
                return this.type || 'TRANSFERRED';
            } else {
                return '';
            }
        }
    },
    mounted() {
        if (window.cordova && StatusBar && StatusBar.isVisible) {
            StatusBar.styleLightContent();
        }
        this.checkLogin();
        this.emitter.on('updateList', info => {
            console.log(info);
            let list = [...this.list];
            let assetList = [...this.assetList];
            if (assetList.length == 1) {
                this.show = false;
            }
            if (!this.show) {
                list.forEach((item, index) => {
                    if (item.id === info.id || item.assetId === info.id) {
                        list[index] = {
                            ...item,
                            ...info,
                            num: item.num,
                            id: item.id,
                            assetId: item.assetId
                        };
                        if (info.status === 'DESTROYED') {
                            list.splice(index, 1);
                        }
                    }
                });
                this.list = list;
            }

            if (assetList.length > 1) {
                assetList.forEach((item, index) => {
                    if (item.id === info.id) {
                        assetList[index] = info;
                        if (info.status === 'DESTROYED') {
                            assetList.splice(index, 1);
                            let _index = [...this.list].findIndex(item => {
                                return item.prefixName === this.moreTitle;
                            });
                            let _info = {};
                            if (_index !== -1) {
                                _info = { ...this.list[_index] };
                                _info.num = _info.num - 1;
                            }
                            if (index === 0) {
                                _info = {
                                    ..._info,
                                    ...assetList[0],
                                    num: _info.num,
                                    id: _info.id,
                                    assetId: assetList[0].id
                                };
                            }
                            this.list[_index] = _info;
                        }
                    }
                });
                this.assetList = assetList;
            }

            // let list = [...this.list];
            // list.forEach((item, index) => {
            //     if (item.id === info.id) {
            //         list[index] = info;
            //     }
            // });

            this.list = [...this.list].filter(item => {
                return item.status !== 'DESTROYED';
            });
            this.$toast.clear();
        });
        this.emitter.on('refreash', () => {
            this.page = 0;
            this.getList();
        });
        if (this.isLogin) {
            this.$http
                .post(
                    '/showroom/all',
                    {
                        query: {
                            del: false,
                            userId: this.$store.state.userInfo.id
                        }
                    },
                    { body: 'json' }
                )
                .then(res => {
                    if (!res.empty) {
                        this.showRoom = true;
                    }
                });
        }
    },
    beforeRouteLeave(to, from, next) {
        if (to.path === '/assetDetail' || to.path === '/hall') {
            this.scrollTop = this.scrollWrapper.scrollTop;
            this.setKeeps(['index', 'store']);
        } else {
            this.scrollTop = 0;
            this.setKeeps(['index', 'store'], false);
        }
        next();
    },
    activated() {
        this.$nextTick(() => {
            this.changeScroll(this.scrollTop);
            if (window.cordova && StatusBar && StatusBar.isVisible) {
                StatusBar.styleLightContent();
            }

            this.$nextTick(() => {
                this.stiky = this.$refs.top.$el.childNodes[0];
                this.$el.parentNode.childNodes[1].className =
                    this.$el.parentNode.childNodes[1].className.replace(/ bgBack/, '') + ' bgBack';
            });
        });
    },
    methods: {
        showMore(asset) {
            console.log(asset);

            this.moreTitle = asset.prefixName;
            this.show = true;
            this.assetLoading = true;
            this.getMoreList(true);
            //
        },
        getMoreList(init = false) {
            if (init) {
                this.assetList = [];
                this.assetPage = 0;
            }
            this.assetLoading = true;
            this.assetFinished = false;
            return this.$http
                .post(
                    '/asset/all',
                    {
                        page: this.assetPage,
                        size: 50,
                        query: {
                            userId: this.$store.state.userInfo.id,
                            status: this.status,
                            prefixName: this.moreTitle,
                            companyId: this.companyId
                        }
                    },
                    { body: 'json' }
                )
                .then(res => {
                    if (res.first) {
                        this.assetList = res.content;
                    } else {
                        this.assetList = [...this.assetList, ...res.content];
                    }
                    this.assetLoading = false;
                    this.assetFinished = res.last;
                    if (!this.assetFinished) {
                        this.assetPage = this.assetPage + 1;
                    }
                    return Promise.resolve();
                });
        },
        getList() {
            if (!this.isLogin) {
                this.empty = true;
                this.loading = false;
                return Promise.resolve();
            }
            if (this.page === 0) {
                this.list = [];
            }
            this.finished = false;
            this.empty = false;
            this.loading = true;
            let form = {
                page: this.page,
                size: 20,
                sort: this.sort === 'price' ? this.sort + this.sortDes : this.sort,
                query: {
                    userId: this.$store.state.userInfo.id,
                    ...this.beforeQuery()
                }
            };
            return this.$http.post(this.url, form, { body: 'json' }).then(res => {
                // if (this.active === 'coupon' || this.active === 'showRoom') {
                if (res.first) {
                    this.list = res.content;
                } else {
                    this.list = [...this.list, ...res.content];
                }
                this.empty = res.empty && res.first;
                this.loading = false;
                this.finished = res.last;
                if (!this.finished) {
                    this.page = this.page + 1;
                }
                // } else {
                //     this.list = res;
                //     this.empty = res.length === 0;
                //     this.loading = false;
                //     this.finished = true;
                // }
            });
        },
        beforeQuery() {
            let form = {};
            if (this.active == 'explore') {
                form = {
                    status: this.status
                };
                if (this.type === 'NORMAL') {
                    form = {
                        ...form,
                        publicShow: true,
                        consignment: false
                    };
                }
                if (this.type === 'NOT_NORMAL') {
                    form = {
                        ...form,
                        publicShow: false,
                        consignment: false
                    };
                }
                if (this.type === 'ON_SALE') {
                    form = {
                        ...form,
                        consignment: true
                    };
                }
            } else if (this.active == 'showRoom') {
                form = {
                    publish: this.type
                };
            } else if (this.active === 'creator') {
                form = {
                    status: this.status
                };
            } else {
                form = {
                    used: false
                };
            }

            if (this.companyId) {
                form.companyId = this.companyId;
            }

            return form;
        },
        changeActive(active) {
            this.list = [];
            this.active = active;
            this.loading = true;
            setTimeout(() => {
                this.$nextTick(() => {
                    this.type = this.typeOptions[0].type;
                    this.page = 0;
                    this.getList();
                });
            }, 100);
        },
        changeTab(info) {
            if (info.name === 'price') {
                this.sortDes = this.sortDes == 'desc' ? 'asc' : 'desc';
            }
            if (this.active !== 'coupon') {
                this.loading = true;
                this.page = 0;
                this.getList();
            }
        },
        goTop() {
            this.changeScroll(0, true);
        },
        onRefresh() {
            this.page = 0;
            this.getList().then(() => {
                this.isLoading = false;
            });
        }
    }
};
</script>

<style lang="less" scoped>
.top {
    display: flex;
    padding: 10px 16px;
    background-color: #222426;
    .top-btn {
        flex-grow: 1;
        .btn {
            font-size: @font3;
            line-height: 26px;
            display: inline-block;
            vertical-align: text-bottom;
            color: #fff;

            &.active {
                color: var(--prim);
                font-size: @font3;
                font-weight: bold;
            }
        }

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

    .search {
        img {
            display: block;
        }
    }
}
/deep/.van-sticky--fixed {
    background-color: #222426;
}
.van-tabs {
    background-color: #222426;
    /deep/.van-tab {
        margin-right: 30px;
    }
}
.select {
    position: absolute;
    right: 16px;
    bottom: 9px;
    color: @text3 !important;
    min-width: 96px;
}
// /deep/.van-sticky {
//     position: relative;
// }

.discover {
    background-color: #0f0f0f;
    min-height: var(--app-height);
    min-height: var(--app-height);
    box-sizing: border-box;
}
.grid-img {
    display: block;
}
.van-grid {
    margin-top: 12px;
}
/deep/.van-tabs__nav--line.van-tabs__nav--complete {
    border-top-color: #303133;
}

/deep/ .van-grid-item__content {
    padding: 14px 20px 16px;
}
/deep/ .van-grid-item__text {
    color: #fff;
    font-size: 13px;
    line-height: 18px;
    margin-top: 4px;
}

.title {
    padding: 16px 20px 8px;
    color: @prim;
    font-size: 18px;
    font-weight: bold;
}

.box-list {
    // display: flex;
    // flex-wrap: wrap;
    // padding: 8px 8px 100px;
    // padding: 0 0 0 4.2vw;
    background-size: 100vw 42vw;
    background-position: 0 -10vw;
    box-sizing: border-box;

    &.couponList {
        padding: 8px 8px 100px;
    }
    &.roomList {
        padding: 10px 0 100px;
    }

    .asset-list {
        background-size: 100vw auto;
        background-position: 0 -10vw;
        box-sizing: border-box;
        padding: 0 0 0 4.2vw;
    }
}

.tab {
    position: relative;
    padding-right: 14px;
    .van-icon {
        position: absolute;
        right: 0;

        &.van-icon-arrow-down {
            top: 8px;
        }

        &.van-icon-arrow-up {
            bottom: 8px;
        }
    }
}
/deep/.coupon {
    &::after {
        background-color: #181818;
    }

    .coupon-bottom {
        &::before,
        &::after {
            background-color: #0f0f0f;
        }
    }
    .btn {
        &::after {
            background-color: #181818;
        }
    }
}
.goTop {
    position: fixed;
    right: 16px;
    bottom: 70px;
    bottom: calc(env(safe-area-inset-bottom) + 70px);
    width: 44px;
    height: 44px;
    display: block;
    z-index: 20;
}

.wrapper-box {
    width: 306px;
    height: 394px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 16px;
    border: 1px solid #c8c9cc;
    backdrop-filter: blur(10px);
    overflow: auto;
    .van-list {
        padding: 12px 8px;
        min-height: 364px;
    }
}

.wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .flex-col();

    .wrapper-title {
        font-size: 20px;
        font-weight: bold;
        color: #ffffff;
        line-height: 24px;
        text-align: center;
        margin-bottom: 30px;
    }
    .wrapper-close {
        width: 40px;
        height: 40px;
        align-self: center;
        margin-top: 10vh;
    }
}
</style>
