<template>
  <div class="new-design-panel">
    <template v-if="layoutType !== 1">
    <draggable
      v-model="data.list"
      v-bind="{  
        group: 'form',
        ghostClass: 'ghost',
        animation: 200,
        handle: '.drag-handler',
      }"
      class="draggable-item"
      @add="handleWidgetAdd"
    >
      <transition-group name="fade" tag="div" class="widget-form-list">
        <template v-if="data.list.length > 0" >
          <template v-for="(item,index) in data.list.filter(it=>it.key)">
            <grid-layout
            :class="[`grid-layout_${item.type}`,item.key===currentKey?'is-active':'']"
            :key="item.key"
            :colConfig="item"
            :col-layout-index="index"
            :select.sync="selectWidget"
            :data="data"
            @click="handleClick(item.key)"
          ></grid-layout>
          </template>
        </template>
        <el-empty
          v-else
          :image-size="380"
          key="empty"
          :image="noDataImg"
          description="拖拽栏目布局组件进行门户设计"
        >
        </el-empty>
      </transition-group>
    </draggable>
    </template>
    <template v-else>
      <div class="mobile-design__wrap">
        <div class="btn-group" :style="{top:btnGroupTop+'px'}" v-if="isShowBtnGroupComputed&&isShowBtnGroup">
          <div class="icon-wrap"  @click="handleWidgetUp">
            <img :src="moveUpIcon">
          </div>
          <div class="icon-wrap">
            <img :src="moveDownIcon" @click="handleWidgetDown">
          </div>
          <div class="icon-wrap">
            <img :src="copyIcon" @click="handleWidgetCopy">
          </div>
          <div class="icon-wrap" @click="handleWidgetDelete">
            <img :src="deleteIcon">
          </div>
          
        </div>
        <div class="mobile-design">        
          <div class="mobile-design--box" @scroll="handleMobileScroll">
            <div class="mobile-design__header">
                <div class="mobile-design__status" :class="[isShowCarousel?'showCarousel__status':'']">
                  <img :src="mobileStatusBarImg"  class="mobile-design__img "/>
                </div>
              <img :src="mobileHeaderSlideImg"
              ref="carouselImgRef"
              style="height:240px" class="mobile-design__img mobile-design__slide" v-if="isShowCarousel">
              <div class="mobile-design__white" v-else>
                <span class="text">首页</span>
              </div>
            </div>
            <draggable
              v-model="data.mobileList"
              v-bind="{
                group: 'column',
                ghostClass: 'ghost',
                animation: 200,
                handle: '.drag-handler-mobile'
              }"
              class="mobile-draggable"
              :style="{top:isShowCarousel?'180px':'95px'}"
              @add="handleWidgetAdd($event,'mobile')"
              @end="handleWidgetEnd($event)"
            >
              <transition-group
                name="fade"
                tag="div"
                class="widget-form-list"
                :class="{'widget-form__bg': layoutType === 1}"
              >
                <template v-if="data.mobileList.filter(it=>it.key).length > 0">
                  <template v-for="(element, index) in data.mobileList.filter(it=>it.key)">
                    <mobile-grid-layout
                      :key="element.key"
                      :hasKeyList="data.mobileList.filter(it=>it.key)"
                      :colConfig="element"
                      :col-layout-index="index"
                      :select.sync="selectWidget"
                      :data="data"
                      @handleClick="handleMobileClick"
                    ></mobile-grid-layout>
                    
                  </template>
                </template>                
              </transition-group>
            </draggable>
              <template v-if="data.mobileList.filter(it=>it.key).length == 0">
                <div key="empty" class="empty__col">
                  <img class="empty__col--img" :src="noDataImage"/>
                  <p class="no-data-text">拖拽栏目布局和栏目进行门户设计</p>
                </div>
              </template>
          </div>
        </div>
      </div>
    </template>    
  </div>
</template>

<script>
  import _ from 'lodash'
  import Draggable from 'vuedraggable'
  import GridLayout from '@/components/portal/GridLayout.vue'
  import MobileGridLayout from '@/components/portal/MobileGridLayout.vue'
  export default {
    name: 'NewDesignPanel',
    components: {
      GridLayout,
      Draggable,
      MobileGridLayout,
    },
    props: {
      data: {
        type: Object,
        default: () => {},
      },
      select: {
        type: Object,
        default: () => {},
      },
      layoutType:{
        type:Number,
        default:0
      },
      layoutObj:{
        type:Object,
        default:() => {},
      }
    },
    data() {
      return {
        selectWidget: this.select,
        currentKey:'',
        noDataImg: require('@/assets/nodata_images/no-data.png'),
        noDataImage: require('@/assets/nodata_images/dragArrow.png'),
        btnGroupTop:0,
        currentMobileIndex:0,
        mobileHeaderSlideImg:'',
        timer:null,
        mobileClickTimer:null,
        statusBarBgColor:'',
        isShowBtnGroup:false,
        copyIcon:require('@/assets/column_images/tips/copy.svg'),
        deleteIcon:require('@/assets/column_images/tips/delete.svg'),
        moveUpIcon:require('@/assets/column_images/tips/moveUp.svg'),
        moveDownIcon:require('@/assets/column_images/tips/moveDown.svg'),
      }
    },
    computed:{
      mobileStatusBarImg(){
        if(this.isShowCarousel){
          return require('@/assets/img/mobile-white-status-bar.png')
        }
        else {
          return require('@/assets/img/mobile-status-bar.png')
        }
      },    
      isShowBtnGroupComputed(){
        const isShow = this.data.mobileList.filter(item=>item.key)&&this.data.mobileList.filter(item=>item.key).length > 0
        
        return isShow
      },
      isShowCarousel(){
        return this.layoutObj.bannerTypeIds&&this.layoutObj.bannerTypeIds.length!=0
      }
    },
    watch: {
      select(val) {
        this.selectWidget = val;
      },
      selectWidget: {
        handler(val) {
          this.$emit("update:select", val);
        },
        deep: true
      },
      layoutObj:{
        async handler(val){
          if(val.bannerTypeIds&&val.bannerTypeIds.length>0){
            await this.getSidleImg() 
          }
        },
        deep:true,
      },
      
    },
    mounted(){
      this.handleMobileClick()
    },
    beforeDestroy(){
      clearTimeout(this.timer);
      clearTimeout(this.mobileClickTimer);
    },
    methods: {
      handleClick(key){
        this.currentKey = key
        console.log(key)
      },
      async handleMobileClick(index){
        await this.$nextTick()
        let self = this;
        if(index||index==0){
          self.currentMobileIndex = index;
        }
        self.mobileClickTimer = setTimeout(()=>{
          self.findElementPosition()
        },500)
      },
      handleWidgetAdd(evt,type) {
        const newIndex = evt.newIndex
        //为拖拽到容器的元素添加唯一 key
        const key = `${Date.parse(new Date())}_${Math.ceil(Math.random() * 10e6)}`
        if(type){//mobile
          console.log(this.data.mobileList,evt.newIndex,'evt-newIndex--------')
          this.$set(this.data.mobileList, newIndex, {
            ...this.data.mobileList[newIndex],
            key,
          })
          this.selectWidget = this.data.mobileList[newIndex];
          this.currentMobileIndex = newIndex;
          this.handleMobileClick()
        }else{
          this.$set(this.data.list, newIndex, {
            ...this.data.list[newIndex],
            key,
          })
          this.$set(this.data.list, newIndex, {
            ...this.data.list[newIndex],
            columns: this.data.list[newIndex].columns.map(item => ({ ...item }))
          });
          this.selectWidget = this.data.list[newIndex];
        }
      },
       deleteColumn(index, type, main = '') {
        this.$emit('delete-column', index, type, main)
      },
      async findElementPosition(){
        let self = this;
        await this.$nextTick()
        const activeEle = document.querySelector('.mobile-design .is-active')
        const wrap = document.querySelector('.mobile-design')
        if(!activeEle||!wrap)return
        let activeRect = activeEle.getBoundingClientRect();
        let wrapRect = wrap.getBoundingClientRect();
        let boundary = 250;
        self.isShowBtnGroup = true;
        if(activeRect.top<wrapRect.top){
          self.btnGroupTop = 0
          let positiveNum = Math.sign(activeRect.top) === -1 ? -activeRect.top : activeRect.top; //取正数
          self.isShowBtnGroup = !(positiveNum+wrapRect.top>activeRect.height)
        }else{
          if(activeRect.top>wrapRect.bottom - boundary){
            self.btnGroupTop = wrapRect.bottom - boundary    
            self.isShowBtnGroup =!(activeRect.top+20>wrapRect.bottom)        
          }else{
            self.btnGroupTop = activeRect.top - wrapRect.top + 24//加了padding 24px
          }
        }
      },
      handleWidgetUp(){
        let copyList = _.cloneDeep(this.data.mobileList)
        let hasKeyMobileList = copyList.filter(item=>item.key)
        let currentIndex = copyList.findIndex((item)=>item.key==hasKeyMobileList[this.currentMobileIndex].key)
        
        if(this.currentMobileIndex>0){
          this.currentMobileIndex -= 1
        }else{
          return
        }
        let newCurrentIndex = copyList.findIndex((item)=>item.key==hasKeyMobileList[this.currentMobileIndex].key)
        
        console.log(this.selectWidget,currentIndex,this.currentMobileIndex,'handleWidgetUp--------')
        this.$nextTick(() => {
          const item = copyList[currentIndex];
          copyList.splice(currentIndex, 1, copyList[newCurrentIndex]);
          copyList.splice(newCurrentIndex, 1, item);
          this.data.mobileList.splice(0, this.data.mobileList.length, ...copyList);
          this.handleMobileClick();
        })
      },
      handleWidgetDown(){
        let copyList = _.cloneDeep(this.data.mobileList)
        let hasKeyMobileList = copyList.filter(item=>item.key)
        let currentIndex = copyList.findIndex((item)=>item.key==hasKeyMobileList[this.currentMobileIndex].key)
        if(this.currentMobileIndex!=hasKeyMobileList.length - 1){
          this.currentMobileIndex += 1
        }else{
          return
        }
        let newCurrentIndex = copyList.findIndex((item)=>item.key==hasKeyMobileList[this.currentMobileIndex].key)
        
        console.log(this.selectWidget,currentIndex,this.currentMobileIndex,'handleWidgetDown--------')
        this.$nextTick(() => {
          const item = copyList[currentIndex];
          copyList.splice(currentIndex, 1, copyList[newCurrentIndex]);
          copyList.splice(newCurrentIndex, 1, item);
          this.data.mobileList.splice(0, this.data.mobileList.length, ...copyList);
          this.handleMobileClick();
        })
      },
      handleWidgetCopy(){
        let copyList = _.cloneDeep(this.data.mobileList)
        let hasKeyMobileList = copyList.filter(item=>item.key)
        let currentIndex = copyList.findIndex((item)=>item.key==hasKeyMobileList[this.currentMobileIndex].key)
        
        let copyItem = {...hasKeyMobileList[this.currentMobileIndex]}
        // 唯一 key
        const key = `${Date.parse(new Date())}_${Math.ceil(Math.random() * 10e6)}`
        copyItem.key = key
        
        console.log(this.selectWidget,currentIndex,this.currentMobileIndex,'handleWidgetCopy--------')
        this.$nextTick(() => {
          
          this.data.mobileList.splice(this.currentMobileIndex+1, 0, copyItem);
          // this.handleMobileClick();
        })
      },
      handleWidgetDelete() {
        let hasKeyMobileList = this.data.mobileList.filter(item=>item.key)
        if(hasKeyMobileList.length==1){
          this.currentMobileIndex=0
        }
        let currentIndex = this.data.mobileList.findIndex((item)=>item.alias==hasKeyMobileList[this.currentMobileIndex].alias)
        if (hasKeyMobileList.length - 1 === this.currentMobileIndex) {
          if (this.currentMobileIndex === 0) {
            this.selectWidget = {}
          } else {
            this.selectWidget = hasKeyMobileList[this.currentMobileIndex - 1]
          }
        } else {
          this.selectWidget = hasKeyMobileList[this.currentMobileIndex + 1]
        }
        console.log(this.selectWidget,currentIndex,this.currentMobileIndex,'selectWidget--------')
        this.$nextTick(() => {
          this.data.mobileList.splice(currentIndex, 1)
          this.handleMobileClick();
        })
      },
      getSidleImg(cb){
        return new Promise((resolve, reject) =>{
          let param ={
            "pageBean": {
                "page": 1,
                "pageSize": 50,
                "total": 3
            },
            "sorter": [
                {
                    "property": "sn",
                    "direction": "ASC"
                }
            ],
            "querys": [
                {
                    "property": "classifyId",
                    "value": this.layoutObj.bannerTypeIds[0],
                    "group": "advance",
                    "relation": "AND",
                    "operation": "EQUAL"
                }
            ]
          }
          this.$http
          .post('${portal}/portalNewsNotice/v1/query', param)
          .then(
            resp => {
              if(resp.data&&resp.data.rows&&resp.data.rows.length>0){
                let data = resp.data.rows
                let firstSrc = data[0].rotatingDisplayPictures
                let reg = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/
                if(reg.test(firstSrc)){
                  this.mobileHeaderSlideImg = firstSrc
                }else{
                  this.mobileHeaderSlideImg = `${window.context.portal}/system/file/v1/downloadFile?fileId=${firstSrc}`
                }
              }
            },
            error => {
              reject(error)
              console.error(error)
            }
          )
          .finally(() => {
            resolve()
            cb && cb()
          })
        })
        
      },
      handleMobileScroll:_.debounce(function(e){
        this.handleMobileClick()
      },500),
      handleWidgetEnd(e){
        this.handleMobileClick()
      }
    },
  }
</script>

<style lang="scss" scoped>
  .new-design-panel {
    min-height: calc(100% - 48px);
    background: #fff;
    .draggable-item {
      height: 100%;
      .widget-form-list {
        height: calc(100% - 40px);
        padding: 20px;
        ::v-deep{
          .el-empty{
            height: 100%;
          }
        }
      }
    }
    .mobile-design {
      background: url('../../assets/img/mobile-android.png') no-repeat;
      background-size: 100% 100%;
      background-color: #f5f5f5;

      border-radius: 55px;
      padding: 15px 0;
      scrollbar-width: 0;
      box-sizing: border-box;
      margin: 0 auto;
      overflow-x: hidden;
      overflow-y: scroll;
      display: flex;
      justify-content: center;
      &::-webkit-scrollbar {
        width: 0;
      }
      -ms-overflow-style: none;/*这将影响IE10+*/
      scrollbar-width: none; /*这将影响Firefox*/
      &--box{
              
        border-radius:28px;
        overflow-x: hidden;
        overflow-y: scroll;
        scrollbar-width: 0;
        position:relative;
        &::-webkit-scrollbar {
          width: 0px;
          background-color: transparent;
        }
        -ms-overflow-style: none;/*这将影响IE10+*/
        scrollbar-width: none; /*这将影响Firefox*/
        // border:1px solid yellow;
        // margin-top: 5px;
      }
      &__img{
        width:100% !important;
        height:auto;
      }
      &__status{
        width:100%;
        background-color: #fff;
        padding:13px 28px;
        box-sizing: border-box;
        // position: absolute;
        // top:0;
        // left: 0;
        // z-index: 99;
      }
      &__slide{
        // width:100%;
        // position: absolute;
        // top:0;
        // left:0;
      }
      &__white{
        width: 100%;
        height: 44px;
        background-color: #fff;
        text-align: center;
        line-height: 44px;
        .text{
          font-size: 17px;
          font-weight: 800;
          color: #222222;
        }
      }
      .mobile-draggable {
        height: calc(100% - 184px);
        width: 100%;
        position: absolute;
        top: 180px;
        left: 0;
      }
      
      .widget-form-list {
        background: none;
        height: calc(100% - 40px);
        // overflow: auto;
          
        .draggable-content__header {
          margin-bottom: 16px;
          background: #fff;
          border: none;
          border-radius: 10px;
          padding: 0 10px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
      }
      ::v-deep {
        .mobile-design__header {
          text-align: center;
          position: relative;
          margin-bottom: 5px;
          .el-image {
            width: 350px;
            border-radius: 26px 26px 0 0;
          }
        }
      }
    }
  }
  .empty__col {
    background: #fff;
    height: 160px;
    padding-top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    // flex-direction: column;
    border-radius: 12px;
    border: 1px dashed #409EFF;
    margin:0 15px;
    .no-data-text {
      font-size: 14px;
      margin-left: 10px;
    }
    .empty__col--img{
      // width:56px;
      height: 26px;
    }
  }
  .widget-form__bg {
    // width: 315px;
    margin: 0px auto;
    // border-radius: 36px;
    // padding: 10px;
  }
  .template-item_img{
    width: 100%;
  }
  .mobile-design__wrap{
    margin:0 auto;
    position:relative;
    padding: 24px 0;
  }
  .btn-group{
    width: 40px;
    // height: 148px;
    background:#409EFF;
    position:absolute;
    right: -35px;
    top:0;
    background: #FFFFFF;
    box-shadow: 0px 0px 4px 1px rgba(87,87,87,0.16);
    border-radius: 4px 4px 4px 4px;
    padding: 5px 0;
    box-sizing: border-box;
    overflow: hidden;
    .icon-wrap{
      width: 100%;
      display: flex;
      align-items:center;
      justify-content: center;
      padding:8px 0;
      cursor:pointer;
      img{
        width:20px;
        height:20px;
      }
    }
  }
// 屏幕小于 1440px 时应用该样式
  @media screen and (max-width: 1441px) {
    .mobile-design__wrap{width: 340px;
      height: 640px;}
    .mobile-design {
      width: 320px;
      height: 640px;
      padding-top: 13px !important;
      border-radius: 38px!important;
      &--box {
        border-radius: 18px!important;
        width: calc(320px - 26px);
        height: calc(640px - 45px);
      }
      .mobile-draggable {
        width: calc(320px - 40px);
        top: 160px;
      }
    }
  }

  // 屏幕大于 1440px 或小于 1920px 时应用该样式
  @media screen and (min-width: 1440px) and (max-width: 1920px) {
    .mobile-design__wrap{ width: 427px;
      height: 812px;}
    .mobile-design {
      width: 407px;
      height: 812px;
      padding-top: 16px !important;
      &--box {
        width: calc(407px - 32px);
        height: calc(812px - 45px);
        border-radius: 30px!important;
      }
      .mobile-draggable {
        width: calc(407px - 60px);
        top:180px;
      }
    }
  }
  // 屏幕大于 1920px 时应用该样式
  @media screen and (min-width: 1920px) {
    .mobile-design__wrap{ width: 427px;
      height: 812px;}
    .mobile-design {
      width: 407px;
      height: 812px;
      padding-top: 16px !important;
      &--box {
        width: calc(407px - 32px);
        height: calc(812px - 45px);
        border-radius: 30px!important;
      }
      .mobile-draggable {
        width: calc(407px - 60px);
        top:180px;
      }
    }
  }
  .showCarousel__status{
    position: absolute !important;
    z-index:20!important;
    background:transparent!important;
  }
</style>