<template>
  <div>
    <div class="search-input-wrap">
      <el-autocomplete
        class="inline-input search-input"
        v-model="controlSearch"
        :fetch-suggestions="querySearch"
        placeholder="请输入关键字"
        suffix-icon="el-icon-search"
        :trigger-on-focus="false"
        @select="handleSelect"
        @keyup.enter.native="search"
        clearable
      ></el-autocomplete>
    </div>
    <el-scrollbar class="scrollbar-fullheight">
      <div class="control-list">
        <template v-if="layoutComponents.length && type !== 1">
          <div class="widget-cate column-layout-title">栏目布局</div>
          <draggable
            tag="ul"
            class="flex-container"
            :list="layoutComponents"
            v-bind="{
              group: {name: 'form', pull: 'clone', put: false},
              sort: false,
              ghostClass: 'ghost'
            }"
            @end="handleMoveEnd"
            @start="handleMoveStart"
            :move="handleMove"
          >
            <li
              class="flex-item"
              :class="{'no-put': item.type == 'divider'}"
              v-for="(item, index) in layoutComponents"
              :key="index"
              :id="item.desc"
            >
              <a>
                <i class="icon" :class="item.icon"></i>
                <span> &nbsp;{{ item.name }}</span>
              </a>
            </li>
          </draggable>
        </template>

        <div
          class="widget-cate-wrap"
          :style="[layoutComponents.length && type !== 1 ? {marginTop: 0} : {}]"
        >
          <el-collapse v-model="activeNames">
            <el-collapse-item
              v-for="(value, key, index) in columnMap"
              :key="index"
              :name="key"
            >
              <template slot="title">
                <i
                  class="cate-icon"
                  :class="
                    activeNames.includes(key)
                      ? 'el-icon-caret-bottom'
                      : 'el-icon-caret-top'
                  "
                ></i>
                <div class="widget-cate">{{ key }}</div>
              </template>
              <template>
                <draggable
                  class="flex-container"
                  tag="ul"
                  :list="value"
                  v-bind="{
                    group: {name: 'column', pull: 'clone', put: false},
                    sort: false,
                    ghostClass: 'ghost'
                  }"
                  @start="handleMoveStart"
                  :move="handleMove"
                >
                  <li
                    class="flex-item"
                    :class="[
                      {'no-put': item.type == 'divider'},
                      item.name == controlSearch ? 'active' : ''
                    ]"
                    v-for="(item, key, index) in value"
                    :key="index"
                    :id="item.name"
                  >
                    <div class="img-wrap">
                      <snapshot-img :imageData="item"></snapshot-img>
                    </div>
                    <a class="flex__item--title">
                      <div
                        class="title-text"
                        v-if="item.name && item.name.length < 7"
                      >
                        {{ item.name }}
                      </div>
                      <el-popover
                        v-else
                        placement="top-start"
                        width="150"
                        trigger="hover"
                        :content="item.name"
                      >
                        <div class="title-text" slot="reference">
                          {{ item.name }}
                        </div>
                      </el-popover>
                    </a>
                  </li>
                </draggable>
              </template>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>
<script>
const SnapshotImg = () => import('@/components/portal/SnapshotImg.vue')
import portal from '@/api/portal.js'
import Draggable from 'vuedraggable'
export default {
  name: 'column-panel',
  components: {Draggable, SnapshotImg},
  props: {
    columnMap: {
      type: Object
    },
    type: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      layoutComponents: [
        {
          type: 'one',
          name: '一行一列',
          icon: 'icon-yihangyilie',
          columns: [
            {
              span: 24,
              list: []
            }
          ]
        },
        {
          type: 'two',
          name: '一行两列',
          icon: 'icon-yihanglianglie',
          columns: [
            {
              span: 16,
              list: []
            },
            {
              span: 8,
              list: []
            }
          ]
        },
        {
          type: 'three',
          name: '一行三列',
          icon: 'icon-yihangsanlie',
          columns: [
            {
              span: 8,
              list: []
            },
            {
              span: 8,
              list: []
            },
            {
              span: 8,
              list: []
            }
          ]
        }
      ],
      controlSearch: '', //搜索关键字
      controlSearchList: [],
      activeNames: []
    }
  },
  watch: {
    columnMap: {
      handler(val) {
        this.handleColumnMapImgUrl()
      },
      deep: true
    }
  },
  methods: {
    handleMoveEnd: function() {},
    handleMoveStart: function() {},
    handleMove: function() {},
    handleColumnMapImgUrl() {
      this.activeNames = []
      let aliasArr = []
      for (let key in this.columnMap) {
        this.activeNames.push(key)
        for (let subKey in this.columnMap[key]) {
          this.controlSearchList.push({
            id: this.columnMap[key][subKey]['alias'],
            value: this.columnMap[key][subKey]['name']
          })
          if (
            !this.columnMap[key][subKey]['snapshotId'] &&
            this.columnMap[key][subKey]['alias']
          ) {
            aliasArr.push(this.columnMap[key][subKey]['alias'])
          }
        }
      }
      this.getHasAliasImgUrl(aliasArr)
    },
    getHasAliasImgUrl(aliasArr) {
      let params = aliasArr.join(',')
      portal.getAliasImgUrl(params).then(res => {
        if (res.data && res.data.value) {
          let val = res.data.value
          let hasSnapshotIdArr = []
          for (let key in this.columnMap) {
            for (let subKey in this.columnMap[key]) {
              if (val[this.columnMap[key][subKey]['alias']]) {
                this.$set(
                  this.columnMap[key][subKey],
                  'snapshotId',
                  val[this.columnMap[key][subKey]['alias']]
                )
              }
              if (
                this.columnMap[key][subKey] &&
                this.columnMap[key][subKey]['snapshotId']
              ) {
                hasSnapshotIdArr.push(this.columnMap[key][subKey])
              }
            }
          }
          this.$emit('updateDataImage', hasSnapshotIdArr)
        }
      })
    },
    // fetch-suggestions 是一个返回输入建议的方法属性，在该方法中你可以在输入建议数据准备好时通过 cb(data) 返回到 autocomplete 组件中.
    querySearch(queryString, cb) {
      const controlSearchList = this.controlSearchList
      const results = queryString
        ? controlSearchList.filter(this.createFilter(queryString))
        : controlSearchList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return controlSearch => {
        return (
          controlSearch.value
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) !== -1 // 改为===0 就是筛选的数据只是首字匹配的列表项，需要包含输入字的所有列表项改为！==-1
        )
      }
    },
    search() {
      if (!this.controlSearch) {
        this.$message.warning('请输入关键字')
        return
      }
      let controlSearchMess = []

      for (let key in this.columnMap) {
        this.columnMap[key].forEach(item => {
          if (item.name === this.controlSearch) {
            controlSearchMess.push(item.name)
            if (!this.activeNames.includes(key)) {
              this.activeNames.push(key)
            }
          }
        })
      }
      // 判断一下，如果该长度为0的话，那就证明输入的内容和列表的内容不一样。
      if (controlSearchMess.length === 0) {
        this.$message.warning('不存在“' + this.controlSearch + '”栏目')
        return
      }
      setTimeout(() => {
        this.toTarget('#' + this.controlSearch)
      }, 500)
    },
    /* 跳转并传值 */
    handleSelect(data) {
      for (let key in this.columnMap) {
        this.columnMap[key].forEach(item => {
          if (item.name === this.controlSearch) {
            if (!this.activeNames.includes(key)) {
              this.activeNames.push(key)
            }
          }
        })
      }
      setTimeout(() => {
        this.toTarget('#' + data.value)
      }, 500)
    },

    toTarget(selector) {
      this.$el
        .querySelector(selector)
        .scrollIntoView({behavior: 'instant', block: 'end', inline: 'nearest'})
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/form-editor.scss';

.widget-cate {
  padding: 10px 0 0 10px;
  font-weight: bold;
  color: #777;
  font-size: 16px;
}

ul.flex-container {
  margin: 0;
  list-style: none;
  padding: 0 10px 10px 22px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

ul.flex-container > li.flex-item {
  padding: 5px;
  margin: 4px;
  width: 110px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  &:nth-child(1),
  &:nth-child(2) {
    margin-top: 0;
  }
}
ul.flex-container > li.flex-item {
  &.active {
    border: 1px solid #409eff;
  }
}
ul.flex-container > li.flex-item:hover {
  // box-shadow: 0 2px 5px rgba(86, 96, 117, 0.15);
  .img-wrap {
    border-color: $--color-primary;
  }
}

li.flex-item > a > i {
  font-size: 16px;
}

li.flex-item .title-text {
  margin-left: 8px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  width: 100%;
}

.img-wrap {
  width: 112px;
  height: 104px;
  background: #f9f9f9;
  border-radius: 4px 4px 4px 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px;
  overflow: hidden;
  box-sizing: border-box;
  border: 1px solid #dcdee0;
}
.flex__item--title {
  margin-top: 10px;
  font-size: 14px;
  color: #262626;
  width: 100%;
  div {
    margin-left: 0 !important;
    white-space: normal;
  }
}
.control-list {
  box-sizing: border-box;
}
.search-input-wrap {
  background-color: #fff;
  padding: 25px 0 0 15px;
  box-sizing: border-box;
  width: 290px;
  height: 65px;
  position: fixed;
  z-index: 99;
  top: 48px;
  box-shadow: 0 -2px 0 #ededed;
  .search-input {
    margin-left: 14px;
    width: 245px;
  }
}
.widget-cate-wrap {
  margin-top: 20px;
  .cate-icon {
    margin-left: 24px;
    font-weight: bold;
    font-size: 16px;
    margin-top: 10px;
  }
}

::v-deep {
  .el-collapse-item__arrow {
    display: none;
  }
  .el-collapse-item__header {
    border-bottom: none;
  }
}
.scrollbar-fullheight {
  padding-top: 70px;
}
.column-layout-title {
  padding-left: 25px;
  padding-bottom: 6px;
}
</style>
