<template>
  <div class="newRole">
    <div class="newRole-content flex-wrap">
      <div class="newRole-content-left">
        <div class="newRole-content-left-top">
          <div class="flex head">
            <div class="title">账号列表</div>
            <!-- <el-button @click="handleAdd" class="serButton" size="small">新增</el-button> -->
          </div>
          <div class="search">
            <el-input size="small" placeholder="请输入内容" clearable prefix-icon="el-icon-search" :filter-node-method="filterArrNode" v-model="search">
            </el-input>
          </div>
        </div>
        <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="newRole-content-left-bottom">
          <el-scrollbar ref="scroll" style="height: 100%">
            <div class="treeArr">
              <el-tree ref="treeArr" :data="arrs" :props="defaultArrProps" highlight-current :filter-node-method="filterArrNode" default-expand-all node-key="user_group_id" @node-click="handleClick" :expand-on-click-node="false">
                <span class="custom-tree-node" slot-scope="{ node,data }">
                  <div class="flex">
                    <div :class="!data.user_id ? 'bigText':''">
                      <span class="customTxt mr16">{{ node.label }}</span>
                      <span style="margin-left: 10px;" class="customTxt" v-if="!data.user_id">({{ data.user_group_id }})</span>
                    </div>
                  </div>
                </span>
              </el-tree>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <div class="newRole-content-right">
        <div style="height: 100%" class="flex newRole-content-right-new">
          <div class="newRole-content-right-bottom contents1 flex1">
            <div class="newRole-content-left-top">
              <div class="flex head">
                <div class="title">功能授权</div>
              </div>
              <div class="search">
                <el-input size="small" placeholder="请输入内容" clearable prefix-icon="el-icon-search" :filter-node-method="filterNode" v-model="filterText">
                </el-input>
              </div>
            </div>
            <div class="newRole-content-left-bottom">
              <el-scrollbar ref="scroll" style="height: 100%">
                <div class="newRole-content-left-bottom-tree">
                  <el-tree ref="tree" show-checkbox :data="treeData" :props="defaultProps" highlight-current :filter-node-method="filterNode" default-expand-all node-key="auth_id" @check="checkChange" @node-click="handleNodeClick" :expand-on-click-node="false">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span class="customTxt">{{ node.label }}</span>
                      <span v-show="treeCheckId == data.auth_id" class="customBtn">
                        <span @click.stop="setItem(node,data)" v-if="data.auth_id != 0 && (data.auth_type == 4 || data.auth_type == 5)" class="ym">列授权</span>
                      </span>
                    </span>
                  </el-tree>
                </div>
              </el-scrollbar>
            </div>
          </div>
          <div class="newRole-content-right-bottom contents2 flex1">
            <div class="newRole-content-left-top">
              <div class="flex head">
                <div class="title">数据授权</div>
                <el-button type="primary" @click="handleColSave" class="bcButton" size="small">保存</el-button>
              </div>
            </div>
            <div class="newRole-content-left-bottom">
              <el-table ref="multipleTable" class="multipleTable" :data="checkArrs" border height="100%" stripe tooltip-effect="dark" style="width: 100%;" @selection-change="handleSelectionChange">
                <el-table-column label-class-name="DisabledSelection" type="selection" width="100">
                </el-table-column>
                <el-table-column prop="columnLabel" label="列名">
                </el-table-column>
                <el-table-column v-if="isAuth" label="行授权">
                  <template slot-scope="scope">
                    <el-input size="small" placeholder="请输入内容" v-model="scope.row.row_auth" clearable>
                    </el-input>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Dialog :flag="rmFlag">
      <div class="airportInfoDialog">
        <div class="title del-title">删除</div>
        <div class="content del-content">
          <span class="el-icon-error error r10"></span>您是否确认删除<span class="error l10">{{ dataObj.user_group_name }}</span>
          ？
        </div>
        <div class="foot right Delfoot">
          <el-button size="medium" class="r24" @click="tableRemove" type="danger">删除</el-button>
          <el-button size="medium" @click="rmFlag = false">取消</el-button>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import Table from '@/views/newTable/index.vue'
import Dialog from "@/layout/components/Dialog/index.vue"
import { getAuthData, listToTree } from '@/utils/validate'
import { getToken } from '@/utils/auth'
import pf from '@/layout/mixin/publicFunc'
import * as _ from 'lodash'
export default {
  name: 'NewService',
  components: { Table, Dialog },
  mixins: [pf],
  data () {
    return {
      title: '服务设置',
      search: '',
      filterText: '',
      arrs: [
        {
          "user_group_id": 0,
          "user_group_name": "默认用户组",
          "up_user_group_id": -1,
          "user_group_status": null,
          "user_group_comment": null,
          children: []
        }
      ],
      flag: true,
      formInline: {
        role_name: '',
        comment: ''
      },
      activeIndex: null,
      pageIndex: 0,
      pageSize: 9999,
      dataContent: {},
      queryId: '',
      dataObj: {},
      dataType: 'edit',
      noMore: false,
      loading: false,
      treeData: [
        {
          auth_name: '所有权限',
          auth_id: 0,
          children: [],
          up_auth_id: -1
        }
      ],
      treeCheckId: '',
      treeCheckObj: {},
      defaultProps: {
        children: 'children',
        label: 'auth_name'
      },
      defaultArrProps: {
        children: 'children',
        label: 'user_group_name'
      },
      checkGroup: [],
      checkArrs: [],
      checkDatas: [],
      checkGroups: [],
      multipleTable: [],
      rmFlag: false,
      msgUserId: '',
      userId: '',
      userGroupArr: [],
      userArr: []
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    },
    search (val) {
      this.$refs.treeArr.filter(val);
    },
    treeCheckId () {
      this.checkArrs = []
    }
  },
  computed: {
    isAuth () {
      if (this.userId) {
        return true
      } else {
        return false
      }
    }
  },
  created () {
    const { title, qid, auth_id } = this.$route.meta
    this.title = title
    this.queryId = qid
    const { arrs } = getAuthData(auth_id)
    const btns = arrs.filter(item => item.auth_type == 3)
    if (btns && btns.length) {
      this.userId = btns[0].auth_ident
    }
    this.getQueryListCo(qid)
    this.setTreeData()
  },
  updated () {
    this.scrollDown()
  },
  methods: {
    //获取tree数据
    async setTreeData () {
      const { code, returnData } = await this.getQueryList(SERVICE_ID.sysAuthId, { user_id: getToken('userid') })
      if (code == 0) {
        const treeMenu = listToTree(returnData, 'up_auth_id', 'auth_id')
        this.treeData[0].children = treeMenu
      }
    },
    filterNode (value, data) {
      if (!value) return true;
      return data.auth_name.indexOf(value) !== -1;
    },
    filterArrNode (value, data) {
      if (!value) return true;
      return data.user_group_name.indexOf(value) !== -1;
    },
    async getQueryListCo (id) {
      try {
        this.loading = true;
        const { code, returnData } = await this.getQueryListAuth(SERVICE_ID.userListId)
        if (code == 0 && returnData && returnData.length) {
          this.userGroupArr = [...returnData]
          const treeMenu = listToTree(this.userGroupArr, 'up_user_group_id', 'user_group_id')
          this.arrs = treeMenu
          this.loading = false;
        } else {
          this.loading = false;
        }
      } catch (error) {
        this.loading = false;
      }
    },
    load () {
      if (!this.noMore) {
        this.getQueryListCo(this.queryId);
      }
    },
    scrollDown () {
      if (this.$refs['scroll'] && this.dataType == 'add') {
        this.$refs['scroll'].wrap.scrollTop = this.$refs['scroll'].wrap.scrollHeight
      }
    },
    resetTable () {
      this.pageIndex = 0;
      this.noMore = false;
      this.arrs = [];
    },
    //服务列表-新增
    handleAdd () {
      const datas = this.arrs.filter(item => item.role_name == '新建角色')
      if (datas && datas.length) {
        return
      }
      this.dataType = 'add'
      this.flag = false
      this.dataObj.role_name = '新建角色'
      this.arrs.push({ role_name: '新建角色' })
      this.activeIndex = this.arrs.length - 1
      for (const key in this.formInline) {
        if (Object.hasOwnProperty.call(this.formInline, key)) {
          this.formInline[key] = null
        }
      }
    },
    //获取角色已有权限
    async getRoleQuth (item) {
      this.$refs.tree.setCheckedKeys([])
      const newItem = _.cloneDeep(item)
      const newObj = {}
      if (newItem.hasOwnProperty('user_id')) {
        newObj.user_id = newItem.user_id
      } else {
        newObj.user_group_id = newItem.user_group_id
      }
      let msgId = null
      if (newItem.hasOwnProperty('user_id')) {
        msgId = SERVICE_ID.userAuthorizationId
      } else {
        msgId = SERVICE_ID.userGroupAuthorizationId
      }
      const { code, returnData } = await this.getQueryList(msgId, newObj)
      if (code == 0) {
        const result = returnData
        if (result && result.length) {
          const datas = []
          result.forEach(item => {
            datas.push(item.auth_id)
          })
          this.$refs.tree.setCheckedKeys(datas)
          const treeDatas = this.$refs.tree.getCheckedNodes().concat(this.$refs.tree.getHalfCheckedNodes())
          const res = [...treeDatas, ...result].filter((item) => !(treeDatas.some((p) => item.auth_id == p.auth_id) && result.some((c) => item.auth_id == c.auth_id)))
          setTimeout(() => {
            res.forEach((item) => {
              if (item.auth_id) {
                this.$refs.tree.setChecked(item.auth_id, false, false);
              }
            });
          }, 50);
          setTimeout(() => {
            const newTreeDatas = this.$refs.tree.getCheckedNodes().concat(this.$refs.tree.getHalfCheckedNodes())
            const arrs = newTreeDatas.filter(item => item.auth_id != 0)
            this.checkDatas.push(arrs)
          }, 70);
        }
      }
    },
    removeClass (elements) {
      elements.className = '';
    },
    disRemoveArr (arr, key) {
      arr.forEach(item => {
        if (item.children) {
          item.children = _.uniqBy(item.children, key)
          this.disRemoveArr(item.children, key)
        }
      })
      return arr
    },
    //服务列表-点击
    handleClick (item) {
      this.dataType = 'edit'
      this.dataObj = _.cloneDeep(item)
      this.formInline = _.cloneDeep(item)
      this.activeIndex = item.user_group_id
      this.flag = false
      this.treeCheckId = null
      this.$refs.tree.setCurrentKey(null)
      this.msgUserId = null
      this.checkDatas = []
      if (!item.user_id) {
        this.getUser(item.user_group_id)
      }
      this.getRoleQuth(item)
    },
    //获取用户组-用户
    async getUser (id) {
      const a1 = _.cloneDeep(this.userGroupArr)
      const result = await this.getQueryList(SERVICE_ID.getUserTableId, { up_user_group_id: id })
      if (result.code == 0 && result.returnData && result.returnData.length) {
        this.userArr.push(...result.returnData)
        const a2 = _.cloneDeep(this.userArr)
        a2.forEach(item => {
          if (item.hasOwnProperty('user_name') || item.hasOwnProperty('user_group_id')) {
            item.user_group_name = item.user_name
            item.user_group_id = item.user_id
          }
        })
        const a3 = _.uniqBy(a2, 'user_id')
        const menus = [...a1, ...a3]
        const treeMenu = listToTree(menus, 'up_user_group_id', 'user_group_id')
        this.arrs = this.disRemoveArr(treeMenu, 'user_group_id')
      }
    },
    //服务列表-保存
    async handleSave () {
      if (this.dataObj.role_ID && this.dataType == 'edit') {
        const { code } = await this.getChangeList(this.queryId, this.formInline, 2, 'role_ID')
        if (code == 0) {
          this.resetTable()
          this.getQueryListCo(this.queryId)
        }
        this.tipMsg(code)
      } else if (this.dataType == 'add' && this.arrs[this.arrs.length - 1].role_ID) {
        this.formInline.role_ID = this.arrs[this.arrs.length - 1].role_ID
        const { code } = await this.getChangeList(this.queryId, this.formInline, 2, 'role_ID')
        if (code == 0) {
          this.resetTable()
          this.getQueryListCo(this.queryId)
        }
        this.tipMsg(code)
      } else if (this.dataType == 'add') {
        const { code } = await this.getChangeList(this.queryId, this.formInline, 1)
        if (code == 0) {
          this.resetTable()
          this.getQueryListCo(this.queryId)
        }
        this.tipMsg(code)
      }
      else {
        this.$message.error('请先选中服务后再操作')
      }
    },
    async tableRemove () {
      if (this.dataObj.role_ID && this.dataType == 'edit') {
        const { code } = await this.getChangeList(this.queryId, this.dataObj, 3)
        if (code == 0) {
          this.resetTable()
          this.getQueryListCo(this.queryId)
          this.activeIndex = null;
          this.dataObj = {};
          for (const key in this.formInline) {
            if (Object.hasOwnProperty.call(this.formInline, key)) {
              this.formInline[key] = null
            }
          }
          this.flag = true
        }
        this.tipMsg(code)
      } else if (this.dataType == 'add' && this.arrs[this.arrs.length - 1].role_ID) {
        const { code } = await this.getChangeList(this.queryId, this.arrs[this.arrs.length - 1], 3)
        if (code == 0) {
          this.resetTable()
          this.getQueryListCo(this.queryId)
          this.activeIndex = null;
          this.dataObj = {};
          for (const key in this.formInline) {
            if (Object.hasOwnProperty.call(this.formInline, key)) {
              this.formInline[key] = null
            }
          }
          this.flag = true
          this.dataType = 'edit'
        }
        this.tipMsg(code)
      }
      else {
        this.arrs.splice(this.activeIndex, 1)
        this.activeIndex = null
        this.flag = true
        this.dataObj = {}
      }
      this.rmFlag = false
    },
    //服务列表-删除
    handleError () {
      this.rmFlag = true
    },
    handleNodeClick (data) {
      this.msgUserId = null
      this.treeCheckId = data.auth_id
      this.treeCheckObj = data
      // this.treeCheckId = null
      // this.checkArrs = []
    },
    async checkChange () {
      if (this.dataObj.user_group_id) {
        const datas = this.$refs.tree.getCheckedNodes().concat(this.$refs.tree.getHalfCheckedNodes());
        const arrs = datas.filter(item => item.auth_id != 0)
        this.checkDatas.push(arrs)
        if (this.checkDatas.length == 1) {
          const res = this.checkDatas[this.checkDatas.length - 1]; //最后一条数据
          const addRes = []
          const newDatas = []
          const newItem = _.cloneDeep(this.dataObj)
          res.forEach(item => {
            if (item.children) {
              delete item.children
            }
            if (newItem.hasOwnProperty('user_id')) {
              item.user_id = newItem.user_id
            } else {
              item.user_group_id = newItem.user_group_id
            }
            addRes.push(item)
          })
          const newMsgs = _.cloneDeep(addRes)
          newMsgs.forEach(item => {
            const { auth_id, queryTemplateColumnSetID, row_auth, user_group_id, user_id } = item
            const newObj = { auth_id, user_group_id, user_id }
            newDatas.push(newObj)
          })
          let msgId = null
          if (newItem.hasOwnProperty('user_id')) {
            msgId = SERVICE_ID.userAuthorizationId
          } else {
            msgId = SERVICE_ID.userGroupAuthorizationId
          }
          const { code } = await this.getChangeList(msgId, newDatas, 1)
          if (code == 0) {
            setTimeout(() => {
              this.getRoleQuth(this.dataObj)
            }, 100);
          }
          this.tipMsg(code)
        } else {
          const data1 = this.checkDatas[this.checkDatas.length - 1]; //最后一条数据
          const data2 = this.checkDatas[this.checkDatas.length - 2]; //倒数第二条数据
          if (data1.length > data2.length) {
            this.checksBoxTs(data1, data2, "add");
          } else {
            this.checksBoxTs(data2, data1, "del");
          }
        }
      } else {
        this.$message.error('请选中账号后再操作');
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    async checksBoxTs (datas, arr, type) {
      const res = [...datas, ...arr].filter((item) => !(datas.some((p) => item.auth_id == p.auth_id) && arr.some((c) => item.auth_id == c.auth_id)));
      const addRes = []
      const newDatas = []
      const newItem = _.cloneDeep(this.dataObj)
      res.forEach(item => {
        if (item.children) {
          delete item.children
        }
        if (newItem.hasOwnProperty('user_id')) {
          item.user_id = newItem.user_id
        } else {
          item.user_group_id = newItem.user_group_id
        }
        addRes.push(item)
      })
      const newMsgs = _.cloneDeep(addRes)
      newMsgs.forEach(item => {
        const { auth_id, queryTemplateColumnSetID, row_auth, user_group_id, user_id } = item
        let newObj = null
        if (newItem.hasOwnProperty('user_id')) {
          newObj = { auth_id, user_id }
        } else {
          newObj = { auth_id, user_group_id }
        }
        newDatas.push(newObj)
      })
      if (type == 'add') {
        let msgId = null
        if (newItem.hasOwnProperty('user_id')) {
          msgId = SERVICE_ID.userAuthorizationId
        } else {
          msgId = SERVICE_ID.userGroupAuthorizationId
        }
        const { code } = await this.getChangeList(msgId, newDatas, 1)
        if (code == 0) {
          setTimeout(() => {
            this.getRoleQuth(this.dataObj)
          }, 100);
        }
        this.tipMsg(code)
      } else {
        let msgId = null
        if (newItem.hasOwnProperty('user_id')) {
          msgId = SERVICE_ID.userAuthorizationId
        } else {
          msgId = SERVICE_ID.userGroupAuthorizationId
        }
        const { code } = await this.getChangeList(msgId, newDatas, 3)
        if (code == 0) {
          this.msgUserId = null
          this.checkArrs = []
          setTimeout(() => {
            this.getRoleQuth(this.dataObj)
          }, 100);
        }
        this.tipMsg(code)
      }
      // this.checkArrs = []
    },
    async setItem (node, data) {
      if (this.dataObj.user_id || this.dataObj.user_group_id) {
        this.msgUserId = data.auth_id
        const newItem = _.cloneDeep(this.dataObj)
        const newObj = {}
        if (newItem.hasOwnProperty('user_id')) {
          newObj.user_id = newItem.user_id
        } else {
          newObj.user_group_id = newItem.user_group_id
        }
        newObj.auth_id = data.auth_id
        const { code, returnData } = await this.getQueryList(SERVICE_ID.userColAuthId, { auth_id: data.auth_id, user_id: getToken('userid') })
        if (code == 0) {
          const result = returnData
          if (result && result.length) {
            result.map(item => {
              item.row_auth = null
            })
            this.checkArrs = [...result]
            let msgId = null
            if (newItem.hasOwnProperty('user_id')) {
              msgId = SERVICE_ID.userAuthorizationId
            } else {
              msgId = SERVICE_ID.userGroupAuthorizationId
            }
            const { code, returnData } = await this.getQueryList(msgId, newObj)
            if (code == 0 && returnData && returnData.length) {
              const res = returnData.filter(item => item.queryTemplateColumnSetID)
              if (res && res.length) {
                // const caps = _.intersectionBy([result, res], 'queryTemplateColumnSetID')
                // console.log(caps)
                const resmsg = []
                result.forEach((item) => {
                  res.forEach(p => {
                    if (item.queryTemplateColumnSetID == p.queryTemplateColumnSetID) {
                      item.row_auth = p.row_auth
                      resmsg.push(item)
                    }
                  })
                })
                if (resmsg && resmsg.length) {
                  resmsg.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                  });
                }
                this.multipleTable = resmsg
              }
            }
          }
        }
      } else {
        this.$message.error('请选中账号后再操作');
      }
    },
    sendCheckData (arr, type = false) {
      const newData = []
      const newItem = _.cloneDeep(this.dataObj)
      arr.forEach(item => {
        if (type) {
          const newObj = {
            "auth_id": this.treeCheckObj.auth_id,
            "queryTemplateColumnSetID": item.queryTemplateColumnSetID,
          }
          if (newItem.hasOwnProperty('user_id')) {
            newObj.user_id = newItem.user_id
          } else {
            newObj.user_group_id = newItem.user_group_id
          }
          newData.push(newObj)
        } else {
          const obj = {
            "auth_id": this.treeCheckObj.auth_id,
            "auth_type": this.treeCheckObj.auth_type,
            "queryTemplateColumnSetID": item.queryTemplateColumnSetID,
            "columnLabel": item.columnLabel,
            "columnname": item.columnName,
            "row_auth": item.row_auth
          }
          if (newItem.hasOwnProperty('user_id')) {
            obj.user_id = newItem.user_id
          } else {
            obj.user_group_id = newItem.user_group_id
          }
          newData.push(obj)
        }
      })
      return newData
    },
    getColName (arr) {
      const res = []
      this.checkArrs.forEach(item => {
        arr.forEach(p => {
          if (item.columnName == p) {
            res.push(item)
          }
        })
      })
      return res
    },
    handleSelectionChange (val) {
      this.multipleTable = val
    },
    async handleColSave () {
      if (this.treeCheckObj.auth_id && this.dataObj.user_group_id && this.msgUserId) {
        const newItem = _.cloneDeep(this.dataObj)
        const newObj = {
          "auth_id": this.treeCheckObj.auth_id,
        }
        if (newItem.hasOwnProperty('user_id')) {
          newObj.user_id = newItem.user_id
        } else {
          newObj.user_group_id = newItem.user_group_id
        }
        const result = this.sendCheckData(this.multipleTable)
        let msgId = null
        if (newItem.hasOwnProperty('user_id')) {
          msgId = SERVICE_ID.userAuthorizationId
        } else {
          msgId = SERVICE_ID.userGroupAuthorizationId
        }
        const tes = await this.getChangeList(msgId, [newObj], 3)
        if (tes.code == 0) {
          const { code } = await this.getChangeList(msgId, result, 1)
          this.tipMsg(code)
        }
      } else {
        this.$message.error('请先选中用户和权限后再操作列设置后保存数据')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./css/index.scss";
</style>
