<template>
    <Panel name="text" :title="title">
        <template slot="tab" slot-scope="{active}">
            <!-- 自定义label 并带有 active 状态 -->
            <slot name="label" :active="active">
                <Icon name="text" />
                <span>文字</span>
            </slot>
        </template>
        <template slot="title">
            <slot name="title"/>
        </template>
        <!-- 重写 panel 内容 -->
        <slot>
            <div :class="bem()">
                <ul :class="bem('list')">
                    <li
                        v-for="font in fonts"
                        :key="font.label"
                        @click="$emit('addElement', font.data)"
                        :style="{
                            fontSize: font.displayFontSize + 'px',
                            fontWeight: font.data.fontWeight,
                            fontFamily: font.data.fontFamily
                        }"
                    >
                        <span>{{font.label}}</span>
                    </li>
                    <li
                        v-for="item in textEffects"
                        :key="item.id"
                        :style="{
                            backgroundImage: getTextResourceCssBg(item)
                        }"
                        @click="getTextEffect(item.id)"
                    />
                </ul>
                <LoadMore
                    :class="bem('loadmore')"
                    :loadmore="loadMore"
                    :isNoMore="pagination.num >= Math.ceil(pagination.total / pagination.size)"
                />
            </div>
        </slot>
    </Panel>
</template>

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

const PREVIEW_WIDTH = 110;
const PREVIEW_HEIGHT = 74;

const cachesMap = {};

export default {
    name: createComponentName('editor-text-panel'),
    components: {
        Panel,
        LoadMore,
        Icon,
    },
    mixins: [componentMixin],
    props: {
        // 默认字体
        fonts: {
            type: Array,
            default: () => [
                {
                    label: '标题',
                    displayFontSize: 28,
                    data: {
                        type: 'text',
                        content: '双击编辑文字',
                        fontFamily: 'SourceHanSansSC-Bold',
                        fontWeight: 700,
                        fontSize: 70,
                        textAlign: 'center',
                        color: '#333',
                        ruleIndex: -1,
                    },
                }, {
                    label: '正文',
                    displayFontSize: 16,
                    data: {
                        type: 'text',
                        content: '双击编辑文字',
                        fontFamily: 'SourceHanSansSC-Regular',
                        fontSize: 20,
                        textAlign: 'center',
                        color: '#333',
                        ruleIndex: -1,
                    },
                },
            ],
        },
        // 获取字体数据的平台ID
        platformId: {
            type: Number,
            default: 256,
        },
        // 业务场景，二进制 1：web  2：淘宝 web 4： 超级详情 8：APP 16: H5 32: 小程序
        channels: {
            type: [String, Number],
        },
        title: {
            type: String,
        }
    },
    data() {
        return {
            textEffects: [],
            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;
        },
        loadMoreData() {
            return request.get('/api/materials', { params: {
                page_num: this.pagination.num + 1,
                page_size: this.pagination.size,
                type: 'text_effect',
                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.textEffects.push(...res.data);
            });
        },
        getTextEffect(id) {
            if (cachesMap[id]) return this.$emit('addElement', cloneDeep(cachesMap[id]));
            request.get(`/api/materials/${id}`).then(res => {
                const model = JSON.parse(res.data.content).model;
                model.materialId = res.data.id;
                model.disableColor = true;
                model.ruleIndex = -1;
                cachesMap[id] = model;
                this.$emit('addElement', cloneDeep(model));
            }).catch(err => {
                throw err;
            });
        },
        getTextResourceCssBg(item) {
            let url = item.preview && item.preview.url;

            // zoom with max width or height
            if (url) {
                url += `?x-oss-process=image/resize,w_${Math.ceil(PREVIEW_WIDTH * 2)},h_${Math.ceil(PREVIEW_HEIGHT * 2)}/interlace,1`;
            }

            return url ? ossDprURL(`url(${url})`) : null;
        },
    },
};
</script>

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

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

.@{b} {
    width: 270px;
    &__list {
        display: flex;
        padding: 0;
        flex-wrap: wrap;

        li{
            display: inline-block;
            background: #FFF no-repeat 50% 50%;
            background-size: contain;
            border: 1px solid #f0f2f5;
            border-radius: 6px;
            cursor: pointer;
            width: 112px;
            height: 76px;
            line-height: 76px;
            margin-bottom: 13px;
            margin-left: 14px;
            text-align: center;
            transition: all linear .2s;
            &:hover{
                border-color: #AEAEAE;
            }
        }
    }
    &__loadmore {
        .@{loadmore}__error {
            width: 200px;
            height: 30px;
            background: #fff;
            color: #000;
            box-shadow: 0 0 0 0;
        }
    }
}

</style>
