<template>
  <div>
    <el-dialog
      v-loading="loading"
      :visible.sync="visible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false"
      append-to-body
      custom-class="home-edit-dialog"
      title="Setting"
    >
      <div class="drag-container">
        <div v-loading="allLoading" class="drag-left">
          <div class="item-filter">
            list
            <el-input v-model="systemName" size="mini" clearable class="filter-item-input">
              <el-button slot="append" icon="el-icon-search" />
            </el-input>
          </div>
          <draggable
            v-model="allBizData"
            :group="{name: 'system', pull: 'clone', put: false}"
            :clone="clone"
            :sort="false"
            :move="checkMove"
            :set-data="setData"
            filter=".filtered"
            class="drag-item-box"
          >
            <div
              v-for="(element, index) in allBizData"
              :key="element.id"
              class="drag-item"
              :class="{'filtered': element.isFavorite}"
            >
              <i class="el-icon-plus handle-icon" @click="clickAddItem(index)" />
              <el-avatar :size="56" :src="element.url" />
              <div class="item-name">{{ element.businessName }}</div>
            </div>
          </draggable>
          <div v-if="allBizTotal > 0" class="page">
            <el-pagination
              small
              layout="prev, pager, next"
              :current-page="current"
              :total="allBizTotal"
              :page-size="size"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        <div v-loading="myLoading" class="drag-right">
          <div class="drag-title">My
            <div class="item-tip">tip</div>
          </div>
          <el-scrollbar class="my-scroll-box">
            <draggable
              :list="myBizData"
              group="system"
              class="drag-item-box"
              :set-data="setData"
              @add="addItem"
            >
              <div v-for="(element, index) in myBizData" :key="element.id" class="drag-item">
                <i class="el-icon-minus handle-icon" @click="clickRemoveItem(index)" />
                <el-avatar :size="56" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                <div class="item-content">
                  <div class="item-name">{{ element.businessName }}</div>
                  <div class="item-system">{{ element.appName }}</div>
                </div>
              </div>
            </draggable>
          </el-scrollbar>
        </div>
      </div>
      <div slot="footer">
        <el-button size="small" @click="close">Cancel</el-button>
        <el-button type="primary" size="small" @click="saveFavorite">Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import draggable from 'vuedraggable'

import { hasValidRecords } from '@/utils/convert'
import { fetchAllBizList, fetchMyBizList, pushSaveFavorite } from '@/api/biz'

export default {
  components: {
    draggable
  },
  props: {},
  data() {
    return {
      // dialog
      visible: false,
      // table
      current: 1,
      size: 15,
      allBizTotal: 0,
      allBizData: [],
      myBizData: [
        { businessName: 'bizleft4', id: 4 },
        { businessName: 'bizleft5', id: 5 },
        { businessName: 'bizleft6', id: 6 },
        { businessName: 'bizleft7', id: 7 }
      ],
      // filter
      formData: {
        systemNumber: '',
        systemName: '',
        businessName: '',
        businessNumber: ''
      },
      // select data
      systemData: [],
      businessData: [],
      // others
      loading: false,
      allLoading: false,
      myLoading: false
    }
  },
  computed: {
    myBizIds() {
      return this.myBizData.map(item => item.id)
    }
  },
  created() {
  },
  methods: {
    // 改变每页显示条数
    handleSizeChange(val) {
      this.current = 1
      this.size = val
      this.getAllBizList()
    },
    // 切换第几页
    handleCurrentChange(val) {
      this.current = val
      this.getAllBizList()
    },
    // 重置搜索项
    resetTable(formName) {
      this.$refs[formName].resetFields()
      this.getAllBizList()
    },
    // 点击搜索按钮
    searchTable() {
      this.current = 1
      this.getAllBizList()
    },
    // 获取table数据
    getAllBizList() {
      this.allLoading = true
      const params = {
        page: this.current,
        size: this.size,
        params: {
          delFlag: 0,
          appName: this.formData.systemName,
          businessName: this.formData.businessName
        }
      }
      fetchAllBizList(params).then(response => {
        this.allLoading = false
        if (hasValidRecords(response)) {
          response.data.records.forEach(item => {
            if (this.myBizIds.includes(item.id)) {
              item.isFavorite = true
            } else {
              item.isFavorite = false
            }
          })
          this.allBizData = response.data.records
          this.allBizTotal = response.data.total
        } else {
          this.allBizData = []
          this.allBizTotal = 0
        }
      }).catch(error => {
        console.log(error)
        this.allLoading = false
        this.$message.error({
          type: 'error',
          duration: 0,
          showClose: true,
          message: error.message
        })
      })
    },
    getMyBizList() {
      this.myLoading = true
      this.allLoading = true
      const params = {
        page: 1,
        size: 50,
        params: {
          delFlag: 0
        }
      }
      fetchMyBizList(params).then(response => {
        this.myLoading = false
        if (hasValidRecords(response)) {
          this.myBizData = response.data.records
        } else {
          this.myBizData = []
        }
        this.searchTable()
      }).catch(error => {
        console.log(error)
        this.myLoading = false
        this.$message.error({
          type: 'error',
          duration: 0,
          showClose: true,
          message: error.message
        })
      })
    },
    saveFavorite() {
      this.loading = true
      pushSaveFavorite(this.myBizData).then(res => {
        this.loading = false
        this.visible = false
        this.$message({
          type: 'success',
          message: 'Save Successfully!'
        })
      }).catch(error => {
        console.log(error)
        this.loading = false
        this.$message.error({
          type: 'error',
          duration: 0,
          showClose: true,
          message: error.message
        })
      })
    },
    /**
     * 加载dialog
     */
    open() {
      this.allBizData = []
      this.myBizData = []
      this.visible = true
      this.getMyBizList()
    },
    close() {
      this.visible = false
    },
    clone(item) {
      return { ...item }
    },
    checkMove(evt) {
      return !this.myBizIds.includes(evt.draggedContext.element.id)
    },
    addItem(evt) {
      this.allBizData[evt.oldIndex].isFavorite = true
    },
    clickAddItem(index) {
      this.myBizData.push({ ...this.allBizData[index] })
      this.allBizData[index].isFavorite = true
    },
    clickRemoveItem(index) {
      const removed = this.myBizData.splice(index, 1)[0]
      this.allBizData.forEach(item => {
        if (item.id === removed.id) {
          item.isFavorite = false
        }
      })
    },
    setData(dataTransfer) {
      // to avoid Firefox bug
      // Detail see : https://github.com/RubaXa/Sortable/issues/1012
      dataTransfer.setData('Text', '')
    }
  }
}
</script>

<style lang="scss" scoped>
.drag-container {
  display: flex;
  justify-content: center;

  .drag-left, .drag-right {
    width: 50%;
    padding: 0 0 20px 20px;
    max-height: 540px;
  }

  .drag-left {
    background-color: #F8F9F9;
    position: relative;

    .page {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      text-align: center;

      ::v-deep {
        .btn-prev, .btn-next, .el-pager li{
          background-color: transparent;
        }
      }
    }
  }

  .drag-right {
    .my-scroll-box {
      // 48 = drag-title + item-tip - drag-right.margin-bottom
      height: calc(100% - 48px);
      margin-top: -2px;
    }

    ::v-deep {
      .el-scrollbar__wrap{
        overflow-x: hidden;
        padding-top: 2px;
      }
      .el-scrollbar__bar.is-horizontal {
        display: none;
      }
    }
  }

  .drag-title {
    font-size: 14px;
    line-height: 2;
    height: 28px;
    color: rgba(0,0,0,0.85);
  }

  .item-filter, .item-tip {
    height: 40px;
  }

  .item-tip {
    font-size: 12px;
    line-height: 40px;
    color: rgba(0,0,0,0.65);
  }

  .filter-item-input {
    float: right;
    width: 150px;
  }

  .drag-item-box {
    display: flex;
    flex-wrap: wrap;
  }

  .drag-item {
    width: 150px;
    height: 100px;
    border: 1px solid rgba(0,0,0,0.09);
    margin-bottom: 10px;
    margin-right: 20px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 10px;
    position: relative;
    cursor: move;
    cursor: -webkit-grabbing;

    .handle-icon {
      display: inline-block;
      position: absolute;
      top: -3px;
      right: -7px;
      border-radius: 50%;
      background-color: #FF0000;
      color: #FFFFFF;
      cursor: pointer;
      z-index: 100;
    }

    &.filtered {
      cursor: pointer;

      .el-icon-plus {
        display: none;
      }
    }

    .item-system {
      width: 130px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }

    .item-system {
      font-size: 14px;
      color: rgba(0,0,0,0.45);
    }
  }
}
</style>
