<template>
    <med-container>
        <view class="brand-allfunction">
            <view v-if="showlist && showlist.length" class="showlist">
                <view class="c-font-big c-color-333 font-wb c-padding-h">常用功能</view>
                <view class="list-cont list-cont-show">
                    <med-drag
                        ref="meddrag"
                        :dis-left="13"
                        :open-drag="isEdit"
                        :list-data="showlist"
                        @renderEnd="onRenderEnd"
                        @listChange="onListChange"
                    >
                        <template slot-scope="slotProp">
                            <!-- eslint-disable max-len -->
                            <view
                                class="show-item list-item"
                                :class="{'list-item-edit': isEdit}"
                                :style="{width: contWidth / 4 + 'px'}"
                                @tap.stop="onItemTap('del', slotProp.dragitem, slotProp.dragindex, slotProp.sortkey, $event)"
                            >
                                <view class="list-img" @touchstart="onTouch">
                                    <c-image
                                        :src="slotProp.dragitem.imgUrl"
                                        has-compress
                                        mode="widthFix"
                                        :hack-white-stroke="false"
                                        :is-round="false"
                                        width="100%"
                                        height="100%"
                                        :extra="{column: 1}"
                                    />
                                </view>
                                <view class="c-font-normal c-color-333" @touchstart="onTouch">{{ slotProp.dragitem.title }}</view>
                                <view v-if="slotProp.dragitem.promotionText" class="brand-allfunction-promotion">{{ slotProp.dragitem.promotionText }}</view>
                                <view
                                    v-if="isEdit && !slotProp.dragitem.promotionText"
                                    class="list-icon list-icon-del"
                                    @tap.stop="onIconTap('del', slotProp.dragitem, slotProp.dragindex, slotProp.sortkey)"
                                >
                                    <view class="icon-del"/>
                                </view>
                            </view>
                        </template>
                    </med-drag>
                </view>
            </view>
            <template v-if="hidelist && hidelist.length && isRender">
                <view class="hidelist c-gap-top-ll">
                    <view class="c-font-big c-color-333 font-wb c-padding-h">更多功能</view>
                    <view class="list-cont c-padding-h">
                        <view
                            v-for="(item, index) in hidelist"
                            :key="index"
                            use-trackby
                            class="hide-item list-item"
                            :class="{'list-item-edit': isEdit, 'c-gap-left-middle': (index + 1) % 4 !== 1}"
                            :style="{width: contWidth / 4 + 'px'}"
                            @tap.stop="onItemTap('add', item, index, $event)"
                        >
                            <!-- <image :src="item.imgUrl" class="list-img"/> -->
                            <!-- eslint-disable max-len -->
                            <view class="list-img">
                                <c-image
                                    :src="item.imgUrl"
                                    has-compress
                                    mode="widthFix"
                                    :hack-white-stroke="false"
                                    :is-round="false"
                                    width="100%"
                                    height="100%"
                                    :extra="{column: 1}"
                                />
                            </view>
                            <view class="c-font-normal c-color-333">{{ item.title }}</view>
                            <view
                                v-if="isEdit"
                                class="list-icon list-icon-add"
                                @tap.stop="onIconTap('add', item, index)"
                            >+</view>
                        </view>
                    </view>
                </view>
            </template>
            <view :style="{height: '60px'}" class="swan-security-padding-bottom"/>
            <view v-if="isRender" class="edit-btn-wrap swan-security-padding-bottom">
                <view
                    class="edit-btn"
                    :class="{'edit-btn-ing': isEdit}"
                    :style="{
                        width: isEdit ? '100%' : 'calc(50% - 5px)',
                    }"
                    @tap.stop="onEditTap"
                >
                    {{ isEdit ? '保存' : '编辑' }}
                </view>
                <view
                    v-if="!isEdit"
                    class="edit-btn edit-btn-ing c-gap-left"
                    :style="{
                        width: 'calc(50% - 5px)',
                    }"
                    @tap.stop="onItemTap('back', {unifiUrl: '/pages/brand/home/index', openType: 'relaunch'})"
                >
                    返回首页
                </view>
            </view>
        </view>
    </med-container>
</template>

<script>

import MedContainer from '../../../components/common/container';
import MedDrag from '../../../components/brand/drag-list';
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';

import {request} from '../../../utils/request';
import {navigate, navToH5} from '../../../utils/navigate';
import * as conf from '../../../utils/conf';

import CImage from '@components/common/image';


/**
 * @file 全部功能
 * @author chenshuo04
 * @query
 */
export default {
    components: {
        MedContainer,
        MedDrag,
        CImage
    },
    data() {
        const systemInfo = getSystemInfo();
        return {
            editUrl: '',
            showlist: [],
            hidelist: [],
            showlistCopy: [],
            hidelistCopy: [],
            contWidth: systemInfo.screenWidth - 60,
            windowHeight: systemInfo.windowHeight,
            isEdit: false,
            isRender: false,
            disableEditToast: ''
        };
    },
    onLoad(q) {
        this.init(q);
    },
    onShow() {
        this.addStyleToBody();
    },
    onHide() {
        this.addStyleToBody(false);
    },
    methods: {
        init(data) {
            request({
                url: conf.goJianKangApiHost + '/harbor/med/allfunction/h5?vn=med',
                // url: 'http://jiafengfeng.bcc-gzhxy.baidu.com:8888/med/allfunction/h5?vn=med',
                data,
                isNeedLogin: true,
                isFirstScreen: true
            }).then(res => {
                const {hidelist, editUrl, toast} = res.data;
                let {showlist} = res.data;
                showlist && (showlist = showlist.map(ele => {
                    return {
                        ...ele,
                        fixed: !!ele.promotionText
                    };
                }));
                Object.assign(this, {showlist, hidelist, editUrl});
                this.disableEditToast = toast;
                res.update.call(this, () => {
                    this.onRenderEnd();
                    this.addStyleToBody();
                });
            });
        },
        onTouch(e) {
            if (this.isEdit) {
                e.cancelable && e.preventDefault();
            }
        },
        onEditTap() {
            if (this.disableEditToast) {
                this.$api.showToast({
                    icon: 'none',
                    title: this.disableEditToast
                });
                return;
            }
            if (this.isEdit) {
                const tablist = this.showlistCopy
                    .map(item => item.id)
                    .join(',');
                request({
                    url: conf.goJianKangApiHost + '/harbor/med/editallfunction/h5',
                    // url: 'http://jiafengfeng.bcc-gzhxy.baidu.com:8888/med/editallfunction/h5',
                    data: {
                        type: 7,
                        act: 'favoriteaction',
                        funcType: '4',
                        action: 'add',
                        vn: 'med',
                        tablist: tablist
                    },
                    isNeedLogin: true,
                    isFirstScreen: false
                })
                    .then(res => {
                        if (res.data.status) {
                            this.$api.showToast({title: '编辑成功！', icon: 'none'});
                            this.isEdit = false;
                        }
                        else if (res.data.status === 0) {
                            this.$api.showToast({title: '保存失败，请重试', icon: 'none'});
                        }
                    });
            }
            else {
                this.isEdit = true;
            }
        },
        onItemTap(action, item, index, e) {
            e && e.cancelable && e.preventDefault();
            e && e.stopPropagation && e.stopPropagation();
            /* eslint-disable */
            if (this.isEdit) return;
            /* eslint-enable */
            if (item.tcUrl) {
                navToH5(item.tcUrl);
            }
            else if (item.xcx) {
                this.$api.navigateToSmartProgram({
                    appKey: item.xcx.appKey,
                    path: item.xcx.path
                });
            }
            else {
                navigate({
                    url: item.unifiUrl,
                    openType: item.openType,
                    extra: {
                        title: item.title
                    }
                });
            }
        },
        onIconTap(action, data, index, sortkey) {
            if (action === 'del') {
                if (this.showlistCopy.length < 5) {
                    this.$api.showToast({title: '常用功能不能少于4个', icon: 'none'});
                    return;
                }
                this.$refs.meddrag.delDragItem(index, sortkey);
                this.hidelist.unshift(data);
            }
            else if (action === 'add') {
                if (this.showlistCopy.length > 8) {
                    this.$api.showToast({title: '常用功能不能多于9个', icon: 'none'});
                    return;
                }
                this.hidelist.splice(index, 1);
                let finalIndex = this.findLastIndex(this.showlistCopy, 'promotionText');
                this.$refs.meddrag.addDragItem(data, finalIndex);
            }
        },
        findLastIndex(array, searchKey) {
            const index = array.slice().reverse().findIndex(x => x[searchKey]);
            const count = array.length - 1;
            const finalIndex = index >= 0 ? count - index : index;
            return finalIndex;
        },
        onRenderEnd() {
            this.$set(this, 'isRender', true);
        },
        onListChange(list) {
            this.showlistCopy = list.map(item => {
                return item.data;
            });
        },
        addStyleToBody(status = true) {
            if (process.env.MARS_ENV === 'h5') {
                const body = document.getElementsByTagName('body')[0];
                /* eslint-disable */
                body.style.cssText = status ? '-moz-user-select:none; -webkit-user-select:none; -ms-user-select:none; user-select:none;' : '';
                /* eslint-enable */
            }
        }
    }
};
</script>
<style lang="less" scoped>
.brand-allfunction {
    -moz-user-select: none;/* 火狐 */
    -webkit-user-select: none;/* webkit浏览器 */
    -ms-user-select: none;/* IE10 */
    -khtml-user-select: none;/* 早期浏览器 */
    user-select: none;

    .list-cont {
        // display: flex;
        &-show {
            padding: 0 13px;
        }
    }

    .list-item {
        position: relative;
        display: inline-block;
        text-align: center;
        padding: 10px 0;
        margin-top: 8px;
        border-radius: 4px;

        &-edit {
            background: #f8f8f8;
        }
    }

    .show-item {
        margin-left: 4px;
        margin-right: 4px;
    }

    .list-img {
        width: 30px;
        height: 30px;
        background-size: 100% 100%;
        background-position: 0 0;
        background-repeat: no-repeat;
        position: relative;
        margin: auto;
        margin-bottom: 5px;
    }

    .list-icon {
        z-index: 10;
        position: absolute;
        top: 5px;
        right: 5px;
        font-size: 14px;
        font-weight: bold;
        width: 14px;
        height: 14px;
        line-height: 14px;
        border-radius: 10px;
        color: #fff;

        &-del {
            background: #ff6050;
            display: flex;
            align-items: center;
            justify-content: center;

            .icon-del {
                display: inline-block;
                height: 2px;
                width: 8px;
                background: #fff;
                border-radius: 3px;
            }
        }

        &-add {
            background: #00c8c8;
        }
    }

    .edit-btn {
        height: 44px;
        line-height: 44px;
        font-size: 17px;
        border: 1px solid #333;
        border-radius: 22px;
        color: #333;
        margin: 8px 0;

        &-ing {
            color: #fff;
            border-width: 0;
            background: linear-gradient(134deg, #00cfa3 0%, #05cfcd 61%, #00d3ea 100%);
        }

        &-wrap {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding-left: 17px;
            padding-right: 17px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            text-align: center;
            background: #fff;
        }
    }

    .font-wb {
        font-weight: bold;
    }

    &-promotion {
        position: absolute;
        left: 50%;
        bottom: -4px;
        transform: translateX(-50%);
        white-space: nowrap;
        font-size: 8px;
        color: #00c8c8;
    }
}
</style>
