<template>
  <div class="inner-dialog">
    <el-dialog
      :title="$t1('常用功能')"
      :append-to-body="true"
      :modal-append-to-body="true"
      :close-on-click-modal="falseValue"
      top="40px"
      :visible.sync="showDialog"
      :modal="falseValue"
      custom-class="dialog-style list-dialog"
      width="1200px"
      @close="dialogClose"
      v-el-drag-dialog
      v-el-dialog-center
    >
      <div class="cont" style="height:calc(100vh - 112px)">
        <div class="fast-set" style="background-color: #fff;">
          <div class="set-tips">{{ $t1('按住拖拽调整顺序，最多只能设置7个常用功能') }}</div>
          <div class="set-box">
            <div class="set-drag" id="imageChange">
              <div
                class="item"
                :class="curIndex"
                v-for="(menuItem, index) in selectedMenus"
                :key="index"
                draggable="true"
                @dragstart="handleDragStart($event, menuItem)"
                @dragover.prevent="handleDragOver($event, menuItem)"
                @dragenter="handleDragEnter($event, menuItem)"
                @dragend="handleDragEnd($event, menuItem)"
              >
                <span>{{ menuItem.menuName }}</span>
                <i class="el-icon-close" @click="removeCommMenu(menuItem, index)"></i>
              </div>
            </div>
          </div>
          <div class="set-menu" id="menu-area">
            <template v-for="(item,index1) in menus">
              <div class="item" :key="index1" v-if="item.enabled && item.children && item.children.length > 0">
                <div class="m-1">
                  <span>
                    <i class="el-icon-collection"></i>
                    {{ item.menuName }}
                  </span>
                </div>
                <template v-for="(subItem,index2) in item.children">
                  <dl :key="index2" v-if="subItem.enabled && subItem.children && subItem.children.length > 0">
                    <dt class="m-2">{{ subItem.menuName }}</dt>
                    <dd class="m-3">
                      <template v-for="(thrItem,index3) in subItem.children">
                        <el-checkbox
                          :key="index3"
                          v-model="thrItem.checked"
                          :label="thrItem.menuName"
                          @change="
                            (val, event) => {
                              checkMenu(thrItem);
                            }
                          "
                        ></el-checkbox>
                      </template>
                    </dd>
                  </dl>
                </template>
              </div>
            </template>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain class="button-sty" @click="dialogClose">
          <i class="el-icon-close el-icon"></i>
          {{ $t1('取 消') }}
        </el-button>
        <el-button type="primary" @click="saveData" class="button-sty">
          <i class="el-icon-check el-icon"></i>
          {{ $t1('确 定') }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'commMenuIndex',
  props: ['visiable', 'topValue'],
  components: {},
  data() {
    return {
      showDialog: true,
      falseValue: false,
      topVal: '40px',
      menus: [],
      selectedMenus: [],
      curIndex: '',
      currentMenuId: 0
    };
  },
  created() {
    if (this.topValue == null) {
      this.topVal = '40px';
    }
    // this.currentMenuId = localStorage.getItem('currentMenuId');
  },
  async mounted() {
    var that = this;
    await this.initMenu();
    this.initCommMenu();
  },
  methods: {
    checkMenu(menu, val) {
      let selectedMenus = this.selectedMenus;
      if (menu.checked && selectedMenus.length >= 7) {
        this.$nextTick(() => {
          this.$baseAlert(this.$t1('最多只能设置7个常用功能'));
          /* menu.checked = false;
          et.target.checked = false;
          this.$forceUpdate(); */
          this.$set(menu, 'checked', false);
        });
        return;
      }
      let cIndex = null;
      for (let i = 0; i < selectedMenus.length; i++) {
        let selectedMenu = selectedMenus[i];
        if (menu.id == selectedMenu.id) {
          cIndex = i;
          break;
        }
      }
      if (menu.checked) {
        if (cIndex === null) {
          selectedMenus.push(menu);
          // this.selectedMenus = selectedMenus;
        }
      } else {
        if (cIndex !== null) {
          selectedMenus.splice(cIndex, 1);
          // this.selectedMenus = selectedMenus.splice(cIndex,1)
        }
      }
    },
    removeCommMenu(menu, cIndex) {
      this.selectedMenus.splice(cIndex, 1);
      this.menus.forEach(item => {
        if (item.children) {
          item.children.forEach(subItem => {
            if (subItem.children) {
              subItem.children.forEach(thrItem => {
                if (thrItem.id == menu.id) {
                  thrItem.checked = false;
                }
              });
            }
          });
        }
      });
    },
    initMenu() {
      // if(!this.currentMenuId)return;
      let that = this;
      return this.$http({
        url: USER_PREFIX + '/menu/currentList',
        method: 'post',
        success: res => {
          let rows = res.objx || [];
          // this.menus = rows.filter(row=>row.id == this.currentMenuId);
          this.menus = rows;
        }
      });
    },
    initCommMenu() {
      // if(!this.currentMenuId)return;
      this.$http({
        url: USER_PREFIX + '/comm_menu/currentList',
        method: 'post',
        data: {longOne: 0},
        success: res => {
          var datas = res.objx || [];
          this.selectedMenus = datas;
          let idMap = {};
          for (let i = 0; i < datas.length; i++) {
            let data = datas[i];
            idMap[data.id] = true;
          }
          this.menus.forEach(item => {
            if (item.children) {
              item.children.forEach(subItem => {
                if (subItem.children) {
                  subItem.children.forEach(thrItem => {
                    if (idMap[thrItem.id]) {
                      thrItem.checked = true;
                    }
                  });
                }
              });
            }
          });
          this.$forceUpdate();
        }
      });
    },
    dialogClose() {
      this.$emit('update:visiable', false);
    },
    dialogPrimary() {
      var rows = this.$refs['table-m2'].getTableData().fullData;
      this.$emit('confirm', rows);
      this.$emit('update:visiable', false);
    },
    saveData() {
      // var param = '';
      /*
      this.selectedMenus.forEach(function(selectedMenu) {
        param += '&menuId=' + selectedMenu.id;
      });
      if (param) {
        param = param.substring(1, param.length);
      } */
      let ids = this.selectedMenus.map(menu => menu.id);
      // let param = {menuIds:ids};
      let datas = this.selectedMenus;

      var url = USER_PREFIX + '/comm_menu/addCommMenus';

      this.$http({
        url: url,
        method: `post`,
        data: {parent: this.currentMenuId, menuIds: ids},
        isLoading: true,
        success: res => {
          //更新
          this.$message({
            message: res.content,
            type: 'success',
            duration: 500,
            onClose: t => {
              this.$emit('confirm', datas);
              this.$emit('update:visiable', false);
            }
          });
        }
      });
    },
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null;
    },
    //首先把div变成可以放置的元素，即重写dragenter/dragover
    handleDragOver(e) {
      e.dataTransfer.dropEffect = 'move'; // e.dataTransfer.dropEffect="move";//在dragenter中针对放置目标来设置!
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = 'move'; //为需要移动的元素设置dragstart事件
      if (item === this.dragging) {
        return;
      }
      const newItems = [...this.selectedMenus];
      // console.log(newItems)
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(item);

      newItems.splice(dst, 0, ...newItems.splice(src, 1));

      this.selectedMenus = newItems;
      this.curIndex = src;
    },
    rourteTo(route, firstRow) {
      this.showMenuModal = true;
      setTimeout(() => {
        this.showMenuModal = false;
      }, 200);
      try {
        if (route.linkType == 4) {
          this.jumpOutLink(route)
        } else if (route.linkType == 3) {
          this.$router.push({path: route.path, query: {url: route.outLink}});
        } else {
          // this.jumpTo(route, firstRow)
          this.$router.push(route.path);
        }
      } catch (e) {
        console.error(e);
      }
    },
  }
};
</script>

<style></style>
