<template>
    <Panel name="graph" :title="title">
        <template slot="tab" slot-scope="{active}">
            <slot name="label" :active="active">
                <Icon name="graph"/>
                <span>图形</span>
            </slot>
        </template>
        <template slot="title">
            <slot name="title"/>
        </template>
        <slot>
            <ul :class="bem('list')">
                <li
                    v-for="(item, j) in graphEffects"
                    :key="j"
                    :style="{
                        backgroundImage: item.preview && item.preview.url
                            ? 'url('+ item.preview.url + `?x-oss-process=image/resize,w_${targetWidth}/interlace,1`+ ')'
                            : null
                    }"
                    @click="getGraph(item.id)"
                />
            </ul>
            <LoadMore
                :class="bem('loadmore')"
                :loadmore="loadMore"
                :isNoMore="pagination.num >= Math.ceil(pagination.total / pagination.size)"
            />
        </slot>
    </Panel>
</template>

<script>
import Panel from './Panel';
import Icon from '../Icon';
import request from '../request';
import { createComponentName, componentMixin } from '../_utils/component';
import LoadMore from '../LoadMore';
import cloneDeep from 'lodash/cloneDeep';

const cachesMap = {};

export default {
    name: createComponentName('editor-graph-panel'),
    components: {
        LoadMore,
        Panel,
        Icon,
    },
    mixins: [componentMixin],
    props: {
        // 获取图形数据的平台ID
        platformId: {
            type: Number,
            default: 32,
        },
        // 业务场景，二进制 1：web  2：淘宝 web 4： 超级详情 8：APP 16: H5 32: 小程序
        channels: {
            type: [String, Number],
        },
        title: {
            type: String,
            default: '',
        }
    },
    data() {
        return {
            graphEffects: [],
            targetWidth: 148,
            pagination: {
                num: 0,
                size: 40,
                total: 10000,
            },
            autoLoadingTimes: Infinity
        };
    },
    computed: {
        hasMore() {
            return ((this.pagination.num - 1) * this.pagination.size) + this.__listLenght < this.pagination.total;
        },
    },
    methods: {
        async loadMore() {
            await this.loadMoreData();
            return this.hasMore;
        },
        getGraph(id) {
            if (cachesMap[id]) return this.$emit('addElement', cloneDeep(cachesMap[id]));
            request.get(`/api/materials/${id}`).then(res => {
                let element = JSON.parse(res.data.content);

                if (element.model) element = element.model;

                cachesMap[id] = element;
                element.materialId = res.data.id;
                element.disableColor = true;
                element.ruleIndex = -1;

                // Reset position
                delete element.left;
                delete element.top;
                /**
                 * 添加的编辑器元素数据
                 * @arg element
                */
                this.$emit('addElement', cloneDeep(element));
            }).catch(err => {
                throw err;
            });
        },
        loadMoreData() {
            return request.get('/api/materials', { params: {
                page_num: this.pagination.num + 1,
                page_size: this.pagination.size,
                type: 'graph',
                channels: this.channels,
                platforms: this.platformId,
            } }).then(res => {
                this.__listLenght = res.data.length;
                this.pagination.total = res.pagination.total;
                this.pagination.num = res.pagination.num;
                this.graphEffects.push(...res.data);
            });
        },
    },
};
</script>

<style lang="less">
@import '../_styles/base.less';

@b: ~'@{prefix}-editor-graph-panel';

.@{b} {
    &__list{
        display: inline;
        padding: 0;

        li{
            display: inline-block;
            box-sizing: border-box;
            background: #FFF no-repeat 50% 50%;
            background-size: contain;
            border: 1px solid #f0f2f5;
            cursor: pointer;
            width: 74px;
            height: 60px;
            line-height: 76px;
            margin-bottom: 9px;
            margin-left: 10px;
            text-align: center;
            transition: all linear .2s;
            overflow: hidden;
            border-radius: 6px;
            &:hover{
                border-color: rgb(129, 176, 255);
                box-shadow: 0 9px 9px rgba(0, 92, 249, 0.08);
            }
        }
    }

    &__loadmore {
        .@{loadmore}__error {
            width: 200px;
            height: 30px;
            background: #fff;
            color: #000;
            box-shadow: 0 0 0 0;
        }
    }
}

</style>
