<template>
    <Layout>
        <Header ref="headerHeight" style="padding: 0 20px; background-color: #fff; border-bottom: 1px solid #ccc; box-shadow: 0 0 3px #ccc"
        :style="{height: headerHeight+'px',
        lineHeight: headerHeight + 'px'}">
            
            <div style="float: left; width:30%;">
                <span style="cursor: pointer;"  v-on:click="gotoHomeList">返回首页列表</span>
            </div>
           
            <DraggerButton></DraggerButton>
            
            <div style="float: right;">
                <!-- <Button size="small">分享</Button> -->
                <Button size="small" v-on:click="gotoPreview">预览</Button>
                <!-- <Button size="small"> 权限设置</Button> -->
                <Button size="small" v-on:click="showHomeSetting">全局设置</Button>
                <Button size="small" v-on:click="saveHome">保存</Button>
                <Button size="small" v-on:click="publishHome">发布</Button>
            </div>
        </Header>
        <Content>
           <Layout>
               <Content>
                    <Scroll :height = "scrollHeight">
                    <!-- <div class="scroll-wrapper" :style="{height: scrollHeight+'px'}" ref="scrollwrapper"> -->
                        <div style="margin: 0 auto;" :style="{background: homeSetting.bg, marginTop: contentMargin+'px'}">
                            <HeaderView v-if="HeaderFlag" :reloadData="reloadData"></HeaderView>
                            <div id="bar">
                                <TopBar :Flag="true"></TopBar>
                            </div>
                            <div id="gridVue" class="grid-stack" :style="{
                                border: homeProperties.border,
                                width: homeProperties.width + 'px',
                                minHeight: (scrollHeight - getHeaderHeight)+ 'px'}">

                                <div  v-for="(item,index) in items"
                                v-bind:data-gs-x="item.x" 
                                v-bind:data-gs-y="item.y"
                                v-bind:data-gs-width="item.vwidth"
                                v-bind:data-gs-height="item.vheight"
                                v-bind:data-gs-id="item.id" 
                                v-bind:key="index">

                                    <div class="grid-stack-item-content" style="text-align: center;"
                                    :style="{background: item.contentSetting.ContentBg,
                                            border: item.contentSetting.BorderWidth +'px '+ item.contentSetting.BorderColor + ' solid',
                                            opacity: item.contentSetting.Opacity,
                                            boxShadow: '0px ' + '0px '+ item.contentSetting.ShadowBlur + 'px '+ item.contentSetting.ShadowColor }">
                                        <component :is="item.type" :itemId="item.id" ></component>
                                    </div>

                                </div>

                            </div>
                        </div>
                        
                    <!-- </div> -->
                    </Scroll>
               </Content>
               <Sider hide-trigger :width="300" style="overflow: hidden;" :style="{height: scrollHeight+'px'}">
                   <!-- <Scroll :height='scrollHeight'> -->
                    <vue-scrollbar classes="my-scrollbar" ref="propertiesScrollbar" :style="{height: scrollHeight+'px'}">
                        <div style="overflow:hidden" :style="{minHeight: scrollHeight + 'px'}">
                            <component v-if="!homeProperties.isShowHomeSetting&&item.isPropShow"  v-for="(item,index) in items" :is="item.propertiesType" :itemdata="item" :itemId="item.id" :key="index" ></component>
                            <HeaderView-properties v-if="!homeProperties.isShowHomeSetting&&homeProperties.isShowHeaderProp"></HeaderView-properties>
                            <HomeProperties v-if="homeProperties.isShowHomeSetting"></HomeProperties>
                            <TopBar-properties v-if="!homeProperties.isShowHomeSetting&&homeProperties.isShowBarProp"></TopBar-properties>
                            <div>
                                <ComponentProperty v-if="!homeProperties.isShowHomeSetting&&!homeProperties.isShowHeaderProp&&item.isPropShow"
                                v-for="(item,index) in items"  :itemdata="item" :itemId="item.id" :key="index"></ComponentProperty>
                            </div>
                        </div>
                    </vue-scrollbar>
                   <!-- </Scroll> -->
               </Sider>
           </Layout>
        </Content>
    </Layout>
</template>
<script>
    import { mapGetters, mapMutations } from "vuex";
    import grid from './CreateGrid'
    import Components from './ComponentSetting'
    import api from '@modules/portal/api/homeAPI'
    import {getQueryParam, initBrowserTitle} from '@libs/base'
    //import VueScrollbar from 'vue2-scrollbar';
    import defaultSetting from './defaultSetting'
    import {getGuid, initItemsData} from "./utils"

    var homeId = null;

    export default {
        data(){
            return {
                curItems: [],
                mhomeSetting: {},
                scrollHeight: 800,
                headerHeight: 54,
                isFullScreen: false,
                contentMargin: 10,
                reloadData: false
            }
        },

        created (){

            var _this = this;

            _this.updateDesignModel(true);

            homeId = getQueryParam("homeId");

            var mhomeSetting = defaultSetting.getDefaultHomeSetting();
            _this.mhomeSetting = mhomeSetting;
            
            api.getDesignHomeDefine({homeId: homeId}, function(result){
                if(result.Result.Result){
                    let updateHeaderFlag = _this.HeaderFlag;
                    _this.setBrowserTitle(result);
                    var propertiesObj = result.home.Styles;

                    if(!propertiesObj) return;

                    var properties = JSON.parse(propertiesObj);
                    if(!properties) return;

                    $.extend(mhomeSetting, properties);

                    _this.mhomeSetting = mhomeSetting;

                    //保证homeSetting中属性改变流程走完再去设置块内的属性；
                    //属性改变的watch函数是在整个属性改变后执行，使用nextTick处理，可以保证homeSetting先去改变属性值，再用块内的属性覆盖全局属性
                    _this.$nextTick(function(){
                        var items = JSON.parse(result.homeModuleDef.Config);

                        items = initItemsData(items, Components);

                        _this.curItems = items;
                    });

                    _this.updateHomeTitle(result.home.Title);

                    _this.updateGlobalInfo(result.GlobalInfo);

                    _this.splitBg(_this.mhomeSetting.bg);
                    if (updateHeaderFlag) {
                        _this.updateHeaderFlag(true)
                    } else {
                        _this.updateHeaderFlag(false)
                    }
                }else{
                    _this.$Message.error(result.Result.Message);
                }
            });

            _this.setHomeId(homeId);
        },

        computed: {
            ...mapGetters({
                initItems: "items",
                homeProp: "homeProp",
                getHomeSetting: "getHomeSetting",
                getProperty: "getProperty",
                getHomeId: "getHomeId",
                getHeaderHeight: "getHeaderHeight",
                getItemById: "getItemById",
                HeaderFlag: 'HeaderFlag'
            }),

            items (){
                return this.initItems(this.curItems);
            },

            homeProperties (){
                return this.homeProp();
            },

            homeSetting (){
                return this.getHomeSetting(this.mhomeSetting);
            }
        },
        methods:{
            ...mapMutations([
                'updateContainerWidth',
                'updateNode',
                'updateNodePropShow',
                'updateNodesWidth',
                'removeItem',
                'updateBgImgUrl',
                'updateBgRepeat',
                'updateBgType',
                'updateBgColor',
                'setHomeId',
                'updateColumns',
                'updateIsShowHomeSetting',
                'updateHomeTitle',
                'updateCurItemId',
                'updateDesignModel',
                'updateMaxWidth',
                'updateGlobalInfo',
                "setHeaderProp",
                'updateBarPropShow',
                'updateNodePropShow',
                'updateHeaderFlag'
            ]),
            gotoPreview:function(){
                if(!window.localStorage){
                    alert("浏览器支持localstorage");
                }else{
                    var storage=window.localStorage;
                    var o = {
                        homeSetting: this.homeSetting,
                        items: this.items
                    }
                    storage.properties = JSON.stringify(o);
                }

                api.gotoPreviewHome();  
            },

            saveHome: function(){
                var _this = this;
                var homeSetting = this.homeSetting;
                var items = this.items;
                console.log(homeSetting)
                // homeSetting.TopBar = {
                //     TopBarBg:'#fff',
                //     TopBarBgLeft:'#fff',
                //     TopBarBgRight:'#fff',
                //     TopBarFlag: false,
                //     TopBarMarginTop: 2,
                //     TopBarMarginBottom: 2,
                //     TopBarImg:'',
                //     TopBarUrl:'',
                //     RadioFlag: 1
                // }
                api.updateHome({homeId: homeId, title: this.homeProperties.homeTitle, homeSetting: JSON.stringify(homeSetting), modulesConfig: JSON.stringify(items)}, function(result){
                    if(result.Result.Result){
                        _this.$Message.success("保存成功！");
                    }else{
                        _this.$Message.error(result.Result.Message);
                    }
                });
            },

            publishHome: function(){
                var _this = this;
                var homeSetting = this.homeSetting;
                var items = this.items;
                
                //
                api.publishHome({homeId: homeId, title: this.homeProperties.homeTitle, homeSetting: JSON.stringify(homeSetting), modulesConfig: JSON.stringify(items)}, function(result){
                    if(result.Result.Result){
                        _this.$Modal.confirm({
                            title: '首页',
                            content: '<p>发布首页成功，是否跳转页面？</p>',
                            onOk: () => {
                                let newTab = window.open('about:blank');
                                let url = api.getHomeUrl({homeId: result.homeId});
                                newTab.location.href=url;
                            }
                        });
                    }else{
                        _this.$Message.error(result.Result.Message);
                    }
                })
            },

            showHomeSetting: function(){
                this.updateIsShowHomeSetting(true);
                this.$refs.propertiesScrollbar.scrollToY(0);
            },

            gotoHomeList: function(){
                api.gotoHomeList();
            },

            setBrowserTitle(homeResult){
                if(homeResult && homeResult.home && homeResult.GlobalInfo){
                    var title = homeResult.GlobalInfo.SysName;
                    var logo = homeResult.GlobalInfo.SysLogo;
                    initBrowserTitle(title, logo);
                }
            },

            showCurNode: function(container, node){
                $('body').find(".active").removeClass("active");
                if(node)
                    $(node.el).find(".grid-stack-item-content").addClass("active");
            },

            addEvent: function(){
                var _this = this;

                var headerHeight = _this.$refs.headerHeight.$el.offsetHeight;
                $("#gridVue").click(function(e){
                    var node = grid.getCurNode(e);
                    _this.showCurNode($(this), node);
                    if(!node) return;
                    //_this.updateIsShowHomeSetting(false);
                    _this.updateNodePropShow(node);
                    _this.$refs.propertiesScrollbar.scrollToY(0);
                });

                var maxWidth = _this.homeSetting.MaxWidth;
                var minWidth = _this.homeProperties.minWidth;

                var documentHeight = document.documentElement.clientHeight;
                
                _this.updateContainerWidth(Math.min(Math.max(minWidth, _this.homeProperties.width), ($("body").width() - 18)));
                _this.isFullScreen = _this.homeSetting.Align == "FullScreen";

                if(_this.isFullScreen){
                    _this.updateContainerWidth($("body").width() - 300 - 18);
                }

                this.scrollHeight = documentHeight - headerHeight - this.contentMargin;

                var width = _this.homeProperties.width;
                $(window).resize(function(sender, eventArgs){
                    if(sender.target != window) return;
                
                    var windowWidth = $("body").width() - 300 - 18;

                    if(_this.isFullScreen){
                        if(windowWidth > minWidth)
                            _this.updateContainerWidth(windowWidth);
                    }else{
                        if(windowWidth < maxWidth && windowWidth > minWidth)
                            _this.updateContainerWidth(windowWidth);
                    }

                    _this.scrollHeight = document.documentElement.clientHeight - headerHeight - _this.contentMargin;
                });
                $('#bar').click(function () {
                    $('body').find(".active").removeClass("active");
                    $('#bar').addClass("active");
                    _this.$refs.propertiesScrollbar.scrollToY(0);
                    _this.updateNodePropShow();
                    _this.updateBarPropShow();
                })
            },

            splitBg: function(bg){
                var _this = this;
                var bgArr = bg.split(" ");
                if(bgArr.length == 1){
                    _this.updateBgType("Color");
                    _this.updateBgColor(bgArr[0]);
                }else{
                    var bgImgUrl = bgArr[0];
                    var bgRepeat = bgArr[1];

                    _this.updateBgType("Img");
                    _this.updateBgImgUrl(bgImgUrl);
                    _this.updateBgRepeat(bgRepeat);
                }
            }
        },

        components: Components,
        mounted () {

            var _this = this;
            
            var options = {
                verticalMargin: 10,
                horizontalMargin: 5,
                snap: true,
                cellHeight: 5,
                cellWidth: 10,
                fixed: true,
                disableDrag: false,
                disableResize: false,
                isShowDel: true,
                afterMoved: function (nodes) {
                    if (!nodes || nodes.length <= 0) {
                        return;
                    }
                    
                    for (var n = 0, nl = nodes.length; n < nl; n++) {
                        var changeNode = nodes[n];

                        _this.updateNode(changeNode);
                    }
                    // _this.scroll1.refresh();                   
                    // _this.scroll1.stop();
                },
                afterDel: function(id){
                    var item = _this.getItemById(id);
                    if(!!item.type){
                        _this.$Modal.confirm({
                            title: '删除组件',
                            content: '<p>确定要删除该组件吗？</p>',
                            onOk: () => {
                                _this.removeItem(id);
                            }
                        });
                    }else{
                         _this.removeItem(id);
                    }
                }
            };

            $.extend(options, _this.homeSetting);
            $.extend(options, _this.homeProperties);

            grid.createGrid($("#gridVue"), options);
            var columns = grid.getColumns();
            _this.updateColumns(columns);
            //console.log(this.$refs.dragBtnContainer.$el.offsetHeight);
            _this.updateNodesWidth();
           
            _this.addEvent();
        },
        watch:{
            'homeProperties.width':function(val, oldval){
                var _this = this;
                this.$nextTick(function(){
                    grid.updateWidth();
                    
                    if(_this.homeSetting.Align != "FullScreen")
                        _this.updateMaxWidth(val);

                    _this.updateNodesWidth(); 

                });
            },

            'items':function(val, oldval){
                var _this = this;

                var layoutType = this.homeSetting.LayoutType;
                this.$nextTick(function(){
                    grid.createGrid($("#gridVue"), null, layoutType); 
                    grid.packNodes();

                    _this.updateNodesWidth();
                });
            },

            'homeSetting.Align': function(val){
                var _this = this;
                _this.isFullScreen = val == "FullScreen";

                if(_this.isFullScreen){
                    _this.updateContainerWidth($("body").width() - 300 - 18);
                }else{
                    var minWidth = _this.homeProperties.minWidth;

                    //var documentHeight = document.documentElement.clientHeight;
                    //_this.homeProperties.width = Math.max(minWidth, _this.homeProperties.width);
                    _this.updateContainerWidth(Math.max(minWidth, _this.homeSetting.MaxWidth));
                }
            }
        } 
    }

</script>

<style>
    .ivu-color-picker-confirm-color-editable{
        width: 135px;
    }
</style>

<style lang= "less" scoped>
    @import url('../../../../base/styles/gridStack.css');
    @import url('./utils.less');
    .right_layout{
        border-left: 1px solid @bgColor;
    }

    .console-manage-right {
        border-left: 1px solid #e6e6e6;
        padding: 0 30px;
    }

     ul li{
	     list-style-type:none;
     }
    ul#navlist{
	    font:12px verdana;
	    padding-bottom: 13px;
    }
 
    ul#navlist li span{
        background: #fff;
        padding: 0 13px;
    }
    ul#navlist li 
    {
	    float: left;
	    height: 30px;

	    border: 0px solid #e6e6e6;
	    width: 100%; 
    }
    ul#navlist .list1
     {
	    border-bottom: 1px solid #e6e6e6;
	    width: 100%;
	    margin-bottom: -15px;
     }
 
    #navlist a
    {
	    display: block;
	    color: #666;
	    text-decoration: none;
	    padding: 6px 5px;
	    width: 100%;
	    text-align: center; 
    }

    .layout_type div {
        float: left;
        width: 100px;
        height: 50px;
        line-height: 50px;
        
        border: 1px solid #ccc;
        margin: 5px;
        text-align: center;
    }

     .grid-stack {
        /*background: lightgoldenrodyellow;*/
        width: 1200px;
        margin: 5px auto;
    }

    .grid-stack-item-content {
        color: #2c3e50;
        text-align: center;
        /* border: 1px solid #ccc; */
        background-color: #fff;
    }

    .grid-stack .ui-state-disabled {
        opacity: 1;
    }

    .clear {
        clear: both;
    }

    .ivu-layout-sider{
        background-color:#fff;
    }

    .active{
        outline:2px solid #f60 !important;
    }
</style>

