<template>
  <div>
    <base-right-dialog
      ref="baseRightDialog"
      :footerShow="true"
      :appendBody="true"
      :dialogVisible.sync="drawer"
      :withHeader="false"
      title="权限分配"
      @handleClose="handleDialogClose"
      @handleConfirmClick="handleConfirmClick"
      :size="'60%'"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="功能权限" name="first">
          <el-table
            border
            ref="multipleTable"
            :data="menuDatas"
            row-key="id"
            tooltip-effect="dark"
            style="width: 100%"
            :default-expand-all="true"
            :default-checked-keys="keys"
            @select-all="selectAll"
            @select="handleSelectionChange"
            v-loading="buttonLoading"
          >
            <el-table-column
              type="selection"
              width="45"
              :reserve-selection="true"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="菜单名称"
              width="200"
            ></el-table-column>
            <el-table-column prop="buttonSelection" label="按钮">
              <template slot-scope="scope">
                <div style="display: flex;align-items: center">
                  <i
                    class="el-icon-star-on"
                    style="
                    height: 30px;
                    line-height: 30px;
                    font-size: 25px;
                    margin-right: 7px;
                    cursor: pointer;
                  "
                    v-show="btnShowHandle(scope.row.buttonList,true)"
                    @click="cancellation(scope.row.buttonList)"
                  ></i>
                  <i
                    class="el-icon-star-on"
                    style="
                    height: 30px;
                    line-height: 30px;
                    font-size: 25px;
                    margin-right: 7px;
                    color: #808080;
                    cursor: pointer;
                  "
                    @click="selectAllButton(scope.row.buttonList)"
                    v-show="btnShowHandle(scope.row.buttonList,false)"
                  ></i>
                  <el-checkbox v-model="item.check" v-for="item in scope.row.buttonList">{{ item.nameCh }}</el-checkbox>
                </div>


              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane
        >
<!--        <el-tab-pane label="数据权限" name="second">-->
<!--          <data-permissions ref="dataPermissions"></data-permissions>-->
<!--        </el-tab-pane>-->
        <el-tab-pane label="首页拖拽权限" name="layOutAuth">
          <layOutPermissions ref="layOutPermissions"></layOutPermissions>
        </el-tab-pane>
      </el-tabs>
    </base-right-dialog>
  </div>
</template>

<script>
import baseRightDialog from '@/components/base/baseRightDialog'
import { PopedomSaveData, GetAllBilldata } from '@/api/apis/jurisdiction'
import dataPermissions from './dataPermissions.vue'
import layOutPermissions from './layOutPermissions.vue'
import loginVue from '../../../login.vue'
import { authApi } from '@/api/apis/auth'

export default {
  data() {
    return {
      drawer: false,
      multipleSelection: [],
      keys: [],
      isAllSelect: false,
      selected: false,
      childNode: false,
      build: '',
      activeName: 'first',
      dataPermissions: [],
      buttonLoading: false,
      menuDatas: []
    }
  },

  props: {
    menuData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },

  components: {
    baseRightDialog,
    dataPermissions,
    layOutPermissions
  },

  beforeUpdate() {
    this.handleTabClick()
  },

  computed: {
    // menuDatas: {
    //   // return JSON.parse(JSON.stringify(this.menuData));
    //   get: function () {
    //     return JSON.parse(JSON.stringify(this.menuData));
    //   },
    //   set: function (item) {
    //     return JSON.parse(JSON.stringify(item));
    //   },
    // },
  },

  methods: {
    //判断全选是否显示
    btnShowHandle(list, flag = false) {
      if (!list.length) return false
      let flagResult = list.every(item => {
        return item.check
      })
      if (flag) {
        return flagResult
      } else {
        return !flagResult
      }
    },
    // tab切换
    handleTabClick() {
      this.$nextTick(() => {
        this.$refs.multipleTable && this.$refs.multipleTable.doLayout()
      })
    },
    selectAllButton(item) {
      item.forEach(item => {
        item.check = true
      })
    },
    cancellation(item) {

      item.forEach(item => {
        item.check = false
      })
    },
    // 全选/取消全选
    selectAll() {
      let data = this.treeToArray(this.menuDatas)
      this.selected = !this.selected
      data.forEach((el, index) => {
        el.check = this.selected
        this.$refs.multipleTable.toggleRowSelection(el, this.selected)
      })
    },
    handleSelectionChange(val, row) {
      // row.check = !row.check
      this.multipleSelection = val;
      let data = this.treeToArray([row]);
      this.childNode = !row.check;
      row.check = !row.check
      if (data.length > 1) {
        data.forEach((el, index) => {
          el.check = this.childNode
          this.$refs.multipleTable.toggleRowSelection(el, this.childNode);
        });
        let ids = data[0].id;
        let arr = this.treeFindPath(
          this.menuDatas,
          (data) => data.id == ids,
          "id"
        );
        arr = arr.splice(0, arr.length - 1);
        let dataList = [];
        let allList = this.treeToArray(this.menuDatas);
        allList.forEach((el, index) => {
          if (arr.includes(el.id)) {
            dataList.push(el);
          }
        });
        dataList.forEach((el, index) => {
          el.check = true
          this.$refs.multipleTable.toggleRowSelection(el, true);
        });
      } else {
        let ids = data[0].id;
        let arr = this.treeFindPath(
          this.menuDatas,
          (data) => data.id == ids,
          "id"
        );
        arr = arr.splice(0, arr.length - 1);
        let dataList = [];
        let allList = this.treeToArray(this.menuDatas);
        allList.forEach((el, index) => {
          if (arr.includes(el.id)) {
            dataList.push(el);
          }
        });
        dataList.forEach((el, index) => {
          el.check=true
          this.$refs.multipleTable.toggleRowSelection(el, true);
        });
      }
    },
    // 默认选中
    exhibitList(menu, list, id) {
      //首页拖拽权限
      this.$refs.layOutPermissions.homeList = list.homeList
      //数据权限
      // this.$refs.dataPermissions.interfaceList = list.interfaceList
      // let data = this.treeToArray(this.menuDatas);
      this.build = id
      // data.forEach((el, index) => {
      //   if (id.includes(el.id)) {
      //     this.$refs.multipleTable.toggleRowSelection(el, true);
      //   }
      // });
      this.menuCheckHandle(menu)
      this.menuDatas = menu
      console.log(this.menuDatas, 'this.menuDatas')
      this.buttonLoading = false
    },
    //数据处理
    menuCheckHandle(arr) {
      arr.forEach(item => {
        if (item.check) {
          this.$refs.multipleTable.toggleRowSelection(item, true)
        }
        if (item.children.length) {
          this.menuCheckHandle(item.children)
        }
      })
    },
    // 数据扁平
    treeToArray(items) {
      let children = []
      items.forEach((item) => {
        children.push(item)
        if (item.children) {
          children = children.concat(this.treeToArray(item.children))
        }
      })
      return children
    },
    handleDialogClose() {
      let data = this.treeToArray(this.menuDatas)
      data.forEach((el, index) => {
        this.$refs.multipleTable.toggleRowSelection(el, false)
      })
      this.changeMenu(this.menuDatas, 0)
      this.drawer = false
      this.$parent.permissionPopup = false
    },
    async handleConfirmClick() {
      let params = {
        id: this.build,
        kindId: 2,
        sysPopedomHomeEntities: [],
        sysPopedomMenuEntities: [],
        sysPopedomOperateEntities: [],
        sysPopedomInterfaceEntities: []
      }
      //数据权限处理
      this.interfaceListHandle(params.sysPopedomInterfaceEntities)
      //首页拖拽处理
      this.homeListHandle(params.sysPopedomHomeEntities)
      //菜单、按钮处理
      this.menuListHandle(this.menuDatas, params.sysPopedomMenuEntities, params.sysPopedomOperateEntities)
      const res = await authApi('sysUserService', '', 'saveJurisdiction', '', params)
      if (res.status == '200') {
        this.handleDialogClose()
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      }
    },
    //接口权限数据处理
    interfaceListHandle(arr) {
      // this.$refs.dataPermissions.interfaceList.forEach(item => {
      //   if (item.check) {
      //     arr.push({ interfaceId: item.id })
      //   }
      // })
    },
    //处理首页拖拽
    homeListHandle(arr) {
      this.$refs.layOutPermissions.homeList.forEach(item => {
        if (item.check) {
          arr.push({ homeId: item.id })
        }
      })
    },
    //菜单数据处理
    menuListHandle(list, result, btnResult) {
      list.forEach(item => {
        if (item.check) {
          result.push({
            menuId: item.id
          })
        }
        if (item.children.length) {
          this.menuListHandle(item.children, result, btnResult)
        }
        if (item.buttonList.length) {
          this.btnListHandle(item.buttonList, btnResult, item.id)
        }
      })
    },
    //按钮选中处理
    btnListHandle(list, btnResult, menuId) {
      list.forEach(item => {
        if (item.check) {
          console.log(btnResult, 'btnResult')
          btnResult.push({
            menuId,
            operate: item.id
          })
        }
      })
    },
    // 递归，添加选中按钮
    addToButtonList(arr, newArr) {
      newArr.forEach((newItem) => {
        this.addToButtonListRecursive(
          arr,
          newItem.op_MenuID,
          newItem.op_OperateKindList
        )
      })
      return arr
    },
    addToButtonListRecursive(arr, targetId, operateKindList) {
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        if (item.id == targetId) {
          let lists = operateKindList.split(',')
          lists.forEach((el) => {
            item.buttonList.push(parseInt(el))
          })
          return item
        }
        if (item.children && item.children.length > 0) {
          this.addToButtonListRecursive(
            item.children,
            targetId,
            operateKindList
          )
        }
      }
    },
    changeMenu(data, num) {
      let level = num
      level = level + 1
      data.forEach((el) => {
        el.buttonList = []
        el.type = false
        if (el.children != null && el.children && el.children.length) {
          this.changeMenu(el.children, level)
        }
      })
    },
    toFlatArray(tree, parentId) {
      return tree.reduce((t, _) => {
        const child = _[children]
        return [
          ...t,
          parentId ? { ..._, parentId } : _,
          ...(child && child.length ? toFlatArray(child, _[id]) : [])
        ]
      }, [])
    },
    getIds(flatArray) {
      let ids = [nodeId]
      let child = flatArray.find((_) => _[id] === nodeId)
      while (child && child.parentId) {
        ids = [child.parentId, ...ids]
        child = flatArray.find((_) => _[id] === child.parentId)
      }
      return ids
    },

    treeFindPath(tree, func, field = '', path = []) {
      if (!tree) return []
      for (const data of tree) {
        field === '' ? path.push(data) : path.push(data[field])
        if (func(data)) return path
        if (data.children) {
          const findChildren = this.treeFindPath(
            data.children,
            func,
            field,
            path
          )
          if (findChildren.length) return findChildren
        }
        path.pop()
      }
      return []
    }
  }
}
</script>
<style scoped lang="scss">
.rightDialog {
  height: 100%;
  padding: 0 16px;
}

::v-deep .cell {
  display: flex;
}

::v-deep .el-checkbox-group {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

::v-deep .el-checkbox {
  margin-right: 15px;
}

::v-deep .el-tabs__nav {
  transform: translateX(22px) !important;
}
</style>
