<!--
 * @Author: your name
 * @Date: 2021-11-29 09:27:43
 * @LastEditTime: 2022-03-21 03:21:52
 * @LastEditors: your name
 * @Description: 权限管理
 * @FilePath: \Foshan4A2.0\src\views\authorityManagement\components\home.vue
-->
<template>
  <div class="authority-home">
    <!--状态和搜索-->
    <div class="authority-head flex">
      <div class="status flex-wrap">
        <div class="status1"><span class="icon"></span>应用权限项</div>
        <div class="status2"><span class="icon"></span>普通权限项</div>
      </div>
      <Search @getSearchData="getSearchData" @clearSearchData="clearSearchData" />
    </div>
    <!--权限树-->
    <!-- <div class="authority-content">
      <OrgTree :dataList="dataList" :renderContent="renderContent" />
    </div> -->
    <div class="authority-content">
      <!-- <OrgTree :dataList="dataList" :renderContent="renderContent" /> -->
      <el-row :gutter="24" class="bodyContent">
        <el-col :span="6" class="bodyPart">
          <div class="grid-content">
            <div class="title">权限树</div>
            <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" class="contentTree">
              <el-tree ref="tree" :data="dataListTree" :props="defaultProps" node-key="AuthId" :filter-node-method="filterNode" highlight-current :default-expanded-keys="expandedKeys" :current-node-key="currentKey" @node-expand="handleExpand" @node-collapse="handleCollapse" @node-click="handleNodeClick">
              </el-tree>
            </div>
          </div>
        </el-col>
        <el-col :span="18" class="bodyPart">
          <div class="grid-contentTop">
            <div class="title">当前</div>
            <div class="content">
              <template v-if="currDataArr.length">
                <el-row>
                  <el-col :span="6" v-for="(data,index) in currDataArr" :key="data.AuthId">
                    <div class="account-left-content-teams">
                      <div class="team">
                        <div class="bg" :class="data.Type == 1 || data.Type == 0 ? 'status1' : 'status2'"></div>
                        <div class="list" :class="data.QueryTarget == 1 ? 'activeStatus' : ''">
                          <div class="flex info">
                            <div :title="data.AuthName" class="name">{{data.AuthName}}</div>
                            <div class="icon">
                              <el-tooltip effect="dark" content="新增应用" placement="bottom">
                                <span v-if="data.Type === 0" @click="renderAdd()" class="cap cap-plus"></span>
                              </el-tooltip>
                              <el-tooltip effect="dark" content="修改应用" placement="bottom">
                                <span v-if="data.Type === 1" @click="renderEdit(data)" class="cap cap-edit"></span>
                              </el-tooltip>
                              <el-tooltip v-is="['authtree_btn_add_auth']" effect="dark" content="新增权限项" placement="bottom">
                                <span v-if="data.Type === 2" @click="renderSub(data)" class="cap cap-sub"></span>
                              </el-tooltip>
                              <el-tooltip v-is="['authtree_btn_update_auth']" effect="dark" content="编辑权限项" placement="bottom">
                                <span v-if="data.Type > 2" @click="renderEdit(data)" class="cap cap-edit"></span>
                              </el-tooltip>
                              <el-tooltip v-is="['authtree_btn_add_auth']" effect="dark" content="新增权限项" placement="bottom">
                                <span v-if="data.Type > 2" @click="renderSub(data)" class="cap cap-sub"></span>
                              </el-tooltip>
                            </div>
                          </div>
                          <div v-if="data.Type > 0" class="flex details">
                            <div class="details-msg">状态：<span :class="data.Status === 1 ? 'success' : 'error'">{{data.Status === 1 ? '启用' : '禁用'}}</span></div>
                            <div v-is="['authtree_btn_state_swatch']" class="details-info">
                              <el-switch v-model="data.flag" @change="renderChange(data,index)" active-color="#6F81BC">
                              </el-switch>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div v-is="['authtree_btn_del_auth']">
                        <div v-if="data.Type !== 0 && data.Type !== 2" @click="onNodeClick(data)" class="info-close">
                          <i class="icon el-icon-close" :class="data.Type === 1 ? 'close1' : data.Type > 2 ? 'close2' : ''"></i>
                        </div>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </template>
              <template v-else>
                <el-empty :image-size="80" description="暂无数据"></el-empty>
              </template>
            </div>
          </div>
          <div class="grid-contentBottom">
            <div class="title">拥有权限</div>
            <div class="content">
              <template v-if="childrenData.length">
                <el-row :gutter="24">
                  <el-col :span="6" v-for="(data,index) in childrenData" :key="data.AuthId">
                    <div @click.stop="childrenClick(data)" class="account-left-content-teams">
                      <div class="team">
                        <div class="bg" :class="data.Type == 1 ? 'status1' : 'status2'"></div>
                        <div class="list" :class="data.QueryTarget == 1 ? 'activeStatus' : ''">
                          <div class="flex info">
                            <div :title="data.AuthName" class="name">{{data.AuthName}}</div>
                            <div class="icon">
                              <el-tooltip effect="dark" content="新增应用" placement="bottom">
                                <span v-if="data.Type === 0" @click.stop="renderAdd()" class="cap cap-plus"></span>
                              </el-tooltip>
                              <el-tooltip effect="dark" content="修改应用" placement="bottom">
                                <span v-if="data.Type === 1" @click.stop="renderEdit(data)" class="cap cap-edit"></span>
                              </el-tooltip>
                              <el-tooltip v-is="['authtree_btn_add_auth']" effect="dark" content="新增权限项" placement="bottom">
                                <span v-if="data.Type === 2" @click.stop="renderSub(data)" class="cap cap-sub"></span>
                              </el-tooltip>
                              <el-tooltip v-is="['authtree_btn_update_auth']" effect="dark" content="编辑权限项" placement="bottom">
                                <span v-if="data.Type > 2" @click.stop="renderEdit(data)" class="cap cap-edit"></span>
                              </el-tooltip>
                              <el-tooltip v-is="['authtree_btn_add_auth']" effect="dark" content="新增权限项" placement="bottom">
                                <span v-if="data.Type > 2" @click.stop="renderSub(data)" class="cap cap-sub"></span>
                              </el-tooltip>
                            </div>
                          </div>
                          <div v-if="data.Type > 0" class="flex details">
                            <div class="details-msg">状态：<span :class="data.Status === 1 ? 'success' : 'error'">{{data.Status === 1 ? '启用' : '禁用'}}</span></div>
                            <div v-is="['authtree_btn_state_swatch']" class="details-info">
                              <el-switch v-model="data.flag" @click.stop.native @change="childrenRenderChange(data,index)" active-color="#6F81BC">
                              </el-switch>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div v-is="['authtree_btn_del_auth']">
                        <div v-if="data.Type !== 0 && data.Type !== 2" @click.stop="onNodeClick(data)" class="info-close">
                          <i class="icon el-icon-close" :class="data.Type === 1 ? 'close1' : data.Type > 2 ? 'close2' : ''"></i>
                        </div>
                      </div>
                      <!-- <div v-if="data.Type !== 0 && data.Type !== 2" @click="onNodeClick(data)" class="info-close">
                        <i class="icon el-icon-close" :class="data.Type === 1 ? 'close1' : data.Type > 2 ? 'close2' : ''"></i>
                      </div> -->
                    </div>
                  </el-col>
                </el-row>
              </template>
              <template v-else>
                <el-empty :image-size="80" description="暂无数据"></el-empty>
              </template>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!--删除弹框-->
    <Dialog :flag="flag">
      <div class="airportInfoDialog">
        <div class="title">删除{{ type === 1 ? '应用' : '权限' }}</div>
        <div class="content">是否确认删除{{ title }}？</div>
        <div class="foot right t30">
          <el-button size="medium" class="r24" @click="remove" type="danger">删除</el-button>
          <el-button size="medium" @click="flag = false">取消</el-button>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import OrgTree from '@/layout/components/OrgTree'
import Search from '@/layout/components/Search'
import Dialog from '@/layout/components/Dialog'
import { UpdateAppStatus, UpdateAuthStatus, DeleteApp, DeleteAuth } from '@/api/apiAuthority'
import treeData from '../minixs/treeData'
export default {
  name: 'Authority',
  components: { OrgTree, Search, Dialog },
  mixins: [treeData],
  data () {
    return {
      dataIndex: 1,
      dataNum: 0,
      dataArr: [],
      type: null,
      title: '', //弹框title
      flag: false, //弹框开关
      dataId: null, //tree数据id
      currDataArr: [],
      childrenData: [],
      dataListTree: [],
      defaultProps: {
        children: "children",
        label: "AuthName",
      },
      currentKey: -1,
      expandedKeys: [-1]
    }
  },
  created () {
    let keyWords = "";
    const treeEx = sessionStorage.getItem('authTreeDatas');
    if (this.$route.query.keyWords) {
      keyWords = this.$route.query.keyWords;
    }
    if (treeEx) {
      this.expandedKeys = JSON.parse(treeEx);
    }
    this.getAuthTree(keyWords);
  },
  watch: {
    dataList: {
      handler (val) {
        this.dataListTree = [];
        this.dataListTree.push(_.cloneDeep(val))
      },
      deep: true
    },
    currentKey: {
      handler (val) {
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(val)
        })
      }
    }
  },
  methods: {
    //树点击
    handleNodeClick (data) {
      const dataNew = _.cloneDeep(data)
      this.currentKey = dataNew.AuthId
      this.currDataArr = [];
      this.childrenData = [];
      this.currDataArr = this.decompose(this.dataArr, "AuthId", this.currentKey);
      this.childrenData = this.decompose(this.dataArr, "UpAuthId", this.currentKey);
    },
    //下级卡片点击
    childrenClick (data) {
      const dataNew = _.cloneDeep(data)
      this.currentKey = dataNew.AuthId
      this.currDataArr = [];
      this.childrenData = [];
      this.currDataArr = this.decompose(this.dataArr, "AuthId", this.currentKey);
      this.childrenData = this.decompose(this.dataArr, "UpAuthId", this.currentKey);
      if (!this.expandedKeys.includes(this.currentKey)) {
        this.expandedKeys.push(this.currentKey)
      }
    },
    // 节点展开
    handleExpand (obj) {
      this.expandedKeys.push(obj.AuthId)
      sessionStorage.setItem('authTreeDatas', JSON.stringify(this.expandedKeys))
    },
    // 节点收起
    handleCollapse (obj) {
      const { AuthId, children } = obj
      children.length && this.collapseChilren(children)
      this.expandedKeys = this.expandedKeys.filter(key => key !== AuthId)
      sessionStorage.setItem('authTreeDatas', JSON.stringify(this.expandedKeys))
    },
    // 收起子节点
    collapseChilren (children) {
      children.forEach(child => {
        const { AuthId, children } = child
        children.length && this.collapseChilren(children)
        this.expandedKeys = this.expandedKeys.filter(key => key !== AuthId)
      })
    },
    //下级切换状态
    childrenRenderChange (data, index) {
      const { AuthId, flag, Type } = data
      const isChildren = true
      this.handleChange(AuthId, flag, Type, index, isChildren)
    },
    filterNode (value, data) {
      if (!value) return true;
      return data.AuthName.indexOf(value) !== -1;
    },
    // 添加应用
    renderAdd () {
      this.$router.push('/authority/appAdd')
    },
    // 修改权限
    renderEdit (data) {
      if (data.Type === 1) {
        this.$router.push({ path: '/authority/appEdit', query: { AuthId: data.AuthId, Status: data.Status, UpAuthId: data.UpAuthId } })
      } else if (data.Type > 2) {
        this.$router.push({ path: '/authority/editPower', query: { AuthId: data.AuthId, Status: data.Status, UpAuthId: data.UpAuthId } })
      }
    },
    // 权限树
    renderSub (data) {
      this.$router.push({ path: '/authority/addPower', query: { AuthId: data.AuthId, Status: data.Status, UpAuthId: data.UpAuthId } })
    },
    // 关闭开启
    renderChange (data, index) {
      const { AuthId, flag, Type } = data
      this.handleChange(AuthId, flag, Type, index)
    },
    //删除
    remove () {
      if (this.type === 1) {
        this.deleteApp(this.dataId)
      } else {
        this.deleteAuth(this.dataId)
      }
    },
    //查询
    getSearchData (val) {
      if (val) {
        this.$router.replace({ path: '/authority', query: { keyWords: val } })
      } else if (this.$route.query) {
        this.$router.replace('/authority')
      }
      this.$refs.tree.filter(val);
      // this.getAuthTree(val)
    },
    //清除查询
    clearSearchData () {
      this.$router.replace('/authority')
      this.getAuthTree()
    },
    //节点关闭按钮点击
    onNodeClick (data) {
      this.flag = true
      this.dataId = data.AuthId
      this.title = data.AuthName
      this.type = data.Type
    },
    //获取指定数据
    decompose (value, key, id) {
      let data = _.cloneDeep(value);
      let arr = []
      for (let i = 0; i < data.length; i++) {
        if (data[i][key] == id) {
          arr.push(data[i])
        }
      }
      return arr
    },
    // 更改下级状态
    setChildrenStatus (id, flag) {
      this.dataArr.forEach(data => {
        if (data.UpAuthId === id) {
          data.Status = flag ? 1 : 0
          data.flag = flag
          this.setChildrenStatus(data.AuthId, flag)
        }
      })
    },
    //渲染节点
    // renderContent (h, data) {
    //   return (
    //     <div class="account-left-content-teams">
    //       <div class="team">
    //         <div class={[data.Type <= 1 ? 'status1' : 'status2', 'bg']}></div>
    //         <div class={[data.QueryTarget == 1 ? 'activeStatus' : '', 'list']}>
    //           <div class="flex info">
    //             <div class="name">{data.AuthName}</div>
    //             <div class="icon">
    //               <span v-show={data.Type === 0} onClick={() => this.renderAdd()} class="cap cap-plus"></span>
    //               <span v-show={data.Type === 1} onClick={() => this.renderEdit(data)} class="cap cap-edit"></span>
    //               <span v-show={data.Type === 2} onClick={() => this.renderSub(data)} class="cap cap-sub"></span>
    //               <span v-show={data.Type > 2} onClick={() => this.renderEdit(data)} class="cap cap-edit"></span>
    //               <span v-show={data.Type > 2} onClick={() => this.renderSub(data)} class="cap cap-sub"></span>
    //             </div>
    //           </div>
    //           <div v-show={data.Type > 0} class="flex details">
    //             <div class="details-msg">状态：<span class={[data.Status === 1 ? 'success' : 'error']}>{data.Status === 1 ? '启用' : '禁用'}</span></div>
    //             <div class="details-info">
    //               <el-switch v-model={data.flag} onChange={() => this.renderChange(data)} active-color="#6F81BC">
    //               </el-switch>
    //             </div>
    //           </div>
    //         </div>
    //       </div>
    //       <div v-show={data.Type !== 0 && data.Type !== 2} onClick={() => this.onNodeClick(data)} class="info-close">
    //         <i class={[data.Type === 1 ? 'close1' : data.Type > 2 ? 'close2' : '', 'icon', 'el-icon-close']}></i>
    //       </div>
    //     </div>
    //   )
    // },
    //-----------获取数据------------
    //应用状态变更
    async handleChange (id, flag, type, index, isChildren = false) {
      const Status = flag ? 1 : 0
      try {
        let res = null
        if (type === 1) {
          res = await UpdateAppStatus({
            AppId: id,
            Status: Status
          })
        } else {
          res = await UpdateAuthStatus({
            AuthId: id,
            AuthStatus: Status
          })
        }
        if (res.code === 0) {
          this.$message.success(res.message)
          if (!isChildren) {
            this.currDataArr[0].Status = Status
          } else {
            this.childrenData[index].Status = Status
          }
          this.dataArr.find(data => {
            if (data.AuthId === id) {
              data.Status = Status
              data.flag = flag
              return true
            }
          })
          if (type !== 1) {
            if (!isChildren) {
              this.childrenData.forEach(data => {
                data.Status = Status
                data.flag = flag
              })
            }
            this.setChildrenStatus(id, flag)
          }
          //this.getAuthTree()
        } else {
          this.$message.error(res.message)
          if (!isChildren) {
            this.currDataArr[0].flag = !flag;
          } else {
            this.childrenData[index].flag = !flag;
          }
        }
      } catch (error) {
        console.log('出错了', error)
        if (!isChildren) {
          this.currDataArr[0].flag = !flag;
        } else {
          this.childrenData[index].flag = !flag;
        }
      }
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.currentKey)
      })
    },
    //应用删除
    async deleteApp (id) {
      try {
        const res = await DeleteApp({
          AppId: id,
        })
        if (res.code === 0) {
          this.$message.success(res.message)
          this.flag = false
          this.getAuthTree()
        } else {
          this.flag = false
          this.$message.error(res.message)
        }
      } catch (error) {
        this.flag = false
      }
    },
    //权限项删除
    async deleteAuth (id) {
      try {
        const res = await DeleteAuth({
          AuthId: id,
        })
        if (res.code === 0) {
          this.$message.success(res.message || '成功')
          this.flag = false
          this.getAuthTree()
        } else {
          this.flag = false
          this.$message.error(res.message)
        }
      } catch (error) {
        this.flag = false
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.authority-home {
  padding: 0 64px;
  overflow-x: auto;
  .authority-head {
    position: fixed;
    width: 100%;
    padding: 30px 64px;
    padding-left: 156px;
    left: 0;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background: #f5f7fa;
    z-index: 100;
    .status {
      & > div {
        margin-right: 28px;
        .icon {
          width: 16px;
          height: 16px;
          background: #f3c45e;
          border-radius: 2px;
          display: inline-block;
          vertical-align: middle;
          margin-right: 10px;
          position: relative;
          top: -2px;
        }
        &:last-child {
          margin-right: 0;
        }
      }
      .status2 {
        .icon {
          background: #6f81bc;
        }
      }
    }
  }
  .authority-content {
    // margin-top: 34px;
    ::v-deep .orgTreeContent {
      padding-top: 110px;
      .account-left-content-teams {
        .status1 {
          background: #f3c45e;
        }
        .status2 {
          background: #6f81bc;
        }
        .activeStatus {
          background: #464960;
          .name,
          .details-msg,
          .success,
          .error {
            color: #fff;
          }
        }
        .list {
          .info {
            .name {
              max-width: 100px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
      }
    }
  }
  .authority-content {
    padding-top: 110px;
    height: calc(100vh - 166px);
    box-sizing: border-box;
    .bodyContent {
      height: 100%;
      .bodyPart {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }
    }
    .account-left-content-teams {
      position: relative;
      margin-top: 24px;
      .info-close {
        position: absolute;
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        background: #000000;
        border-radius: 50%;
        top: -12px;
        right: -12px;
        z-index: 5;
        cursor: pointer;
        .icon {
          color: #fff;
          font-weight: 600;
        }
      }
      .list {
        background-color: #f5f7fa;
        .info {
          line-height: normal;
          margin-bottom: 37px;
          .name {
            font-size: 16px;
            font-weight: bold;
            max-width: 120px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .cap {
            width: 24px;
            height: 24px;
            display: inline-block;
            background-repeat: no-repeat;
            background-size: cover;
            transition: all 0.3s;
            margin-left: 16px;
            &:first-child {
              margin-right: 0;
            }
          }
          .cap-plus {
            background-image: url("../../../assets/status/ic_plus.png");
            &:hover {
              background-image: url("../../../assets/status/ic_plus_hovar.png");
            }
          }
          .cap-edit {
            background-image: url("../../../assets/status/ic_edit.png");
            &:hover {
              background-image: url("../../../assets/status/ic_edit_hovar.png");
            }
          }
          .cap-sub {
            background-image: url("../../../assets/status/ic_subordinate.png");
            &:hover {
              background-image: url("../../../assets/status/ic_subordinate_hovar.png");
            }
          }
          .cap-job {
            background-image: url("../../../assets/status/ic_jobs.png");
            &:hover {
              background-image: url("../../../assets/status/ic_jobs_hovar.png");
            }
          }
          .cap-member {
            background-image: url("../../../assets/status/ic_member.png");
            &:hover {
              background-image: url("../../../assets/status/ic_member_hovar.png");
            }
          }
        }
      }
      .team {
        background: #fff;
        border-radius: 5%;
        box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
        overflow: hidden;
        .bg {
          height: 4px;
          background: #6f81bc;
        }
        .status1 {
          background: #f3c45e;
        }
        .status2 {
          background: #6f81bc;
        }
      }
      .list {
        padding: 23px 24px;
        position: relative;
        min-width: 240px;
        min-height: 118px;
        .info {
          margin-bottom: 20px;
          .info-avoutr {
            display: flex;
            .avoutr {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              background: #303133;
              img {
                max-width: 100%;
              }
            }
            .msg {
              margin-left: 20px;
              p {
                margin: 0;
                padding: 0;
                height: 20px;
                line-height: 20px;
              }
              .name {
                font-weight: bold;
                color: #303133;
                font-size: 18px;
                margin-bottom: 8px;
              }
              .group {
                font-size: 14px;
                font-family: Microsoft YaHei;
                font-weight: 400;
                color: #303133;
              }
            }
          }
          .icon {
            font-size: 16px;
            cursor: pointer;
          }
        }
        .time,
        .ip {
          height: 16px;
          line-height: 16px;
          font-size: 16px;
          .glr {
            color: #909399;
          }
        }
        .ip {
          margin-top: 23px;
          margin-bottom: 38px;
        }
        .details {
          height: 24px;
          line-height: 24px;
          .success {
            color: #6f80bc;
          }
          .error {
            color: #f25555;
          }
        }
      }
    }
    .grid-content {
      width: 100%;
      height: 100%;
      background: #ffffff;
      border-radius: 16px;

      .title {
        font-size: 18px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        color: #303133;
        height: 40px;
        padding: 30px;
      }
      .contentTree {
        height: calc(100% - 60px);
        overflow: auto;
        padding: 20px;
      }
    }
    .grid-contentTop {
      width: 100%;
      height: 240px;
      background: #ffffff;
      border-radius: 16px;

      .title {
        font-size: 18px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        color: #303133;
        height: 40px;
        padding: 30px;
      }
      .content {
        width: 100%;
        height: calc(100% - 60px);
        padding: 0 20px;
      }
    }

    .grid-contentBottom {
      width: 100%;
      height: calc(100% - 240px - 24px);
      background: #ffffff;
      border-radius: 16px;
      .title {
        font-size: 18px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        color: #303133;
        height: 40px;
        padding: 30px;
      }
      .content {
        width: 100%;
        height: calc(100% - 60px);
        padding: 0 20px;
        overflow-y: auto;
      }
    }
  }
}
::-webkit-scrollbar-track-piece {
  background: #d3dce6;
}

::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-thumb {
  background: #99a9bf;
  border-radius: 20px;
}
</style>
