<template>
  <div class="newRole">
    <div class="newRole-head flex-wrap">
      <div class="manageTitle">{{ title }}</div>
    </div>
    <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" v-model="search">
            </el-input>
          </div>
        </div>
        <div class="newRole-content-left-bottom">
          <template v-if="dataList.length">
            <el-scrollbar ref="scroll" style="height: 100%">
              <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
                <div v-for="(item,index) in dataList" :key="index" @click.stop="handleClick(item,index)" :class="index == activeIndex ? 'active':''" class="contents flex">
                  <div class="left">
                    <span class="txt">{{ item.role_name }}</span>
                  </div>
                  <div v-show="activeIndex == index" class="right">
                    <span @click.stop="handleError" class="error">删除</span>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </template>
          <template v-else>
            <el-empty description="暂无数据"></el-empty>
          </template>
        </div>
      </div>
      <div class="newRole-content-right">
        <div class="newRole-content-right-top">
          <div class="flex">
            <div class="title">角色信息 {{ dataObj.role_name }}</div>
            <el-button type="primary" @click="handleSave" :disabled="flag" class="bcButton" size="small">保存</el-button>
          </div>
          <div class="demo-form">
            <el-form :inline="true" :model="formInline" class="flex-wrap">
              <el-form-item label="角色名称">
                <el-input style="width:250px;margin-right: 50px;" clearable v-model="formInline.role_name" :disabled="activeIndex == null" size="small" placeholder="请输入角色名称"></el-input>
              </el-form-item>
              <el-form-item class="flex1" label="角色描述">
                <el-input style="width:600px;" clearable v-model="formInline.comment" :disabled="activeIndex == null" size="small" placeholder="请输入角色描述"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div style="height: calc(100% - 180px)" 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="setItem(node,data)" v-if="data.auth_id != 0 && data.auth_type == 4" 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 stripe :maxHeight="tableHeight" 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 label="行授权">
                  <template slot-scope="scope">
                    <el-input size="small" placeholder="请输入内容" v-model="scope.row.rowauth" 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.role_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 { Query, newData, modifyData, moveData } from "@/api/webApi"
import { setTree } from '@/utils/validate'
import pb from '@/layout/mixin/getPublicData'
import pf from '@/layout/mixin/publicFunc'
import * as _ from 'lodash'
export default {
  name: 'NewService',
  components: { Table, Dialog },
  mixins: [pb, pf],
  data () {
    return {
      title: '服务设置',
      search: '',
      filterText: '',
      arrs: [],
      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'
      },
      checkGroup: [],
      checkArrs: [],
      checkDatas: [],
      checkGroups: [],
      multipleTable: [],
      rmFlag: false
    }
  },
  computed: {
    dataList () {
      return this.arrs.filter(data => !this.search || data.role_name.toLowerCase().includes(this.search.toLowerCase()))
    },
    tableHeight () {
      const dom = document.querySelector('.contents2')
      if (dom) {
        const height = dom.clientHeight
        return height
      } else {
        return 500
      }
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    const { title, qid } = this.$route.meta
    this.title = title
    this.queryId = qid
    this.getQueryListCo(qid)
    this.setTreeData()
  },
  updated () {
    this.scrollDown()
  },
  methods: {
    //获取tree数据
    async setTreeData () {
      const { code, returnData } = await this.getQueryList(SERVICE_ID.sysMenuId)
      if (code == 0) {
        const treeMenu = setTree(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;
    },
    async getQueryListCo (id) {
      try {
        this.loading = true;
        const { code, returnData } = await Query({
          serviceId: id,
          page: ++this.pageIndex,
          pageSize: this.pageSize,
          dataContent: this.dataContent,
        })
        if (code == 0) {
          if (returnData.length === 0) {
            this.pageIndex--;
            this.noMore = true;
          }
          this.arrs.push(...returnData)
          if (this.dataType == 'add') {
            const item = this.arrs[this.arrs.length - 1]
            if (Object.keys(item).length) {
              this.dataObj = item
              this.flag = false
            }
          }
          this.loading = false;
        } else {
          this.pageIndex--;
          this.loading = false;
        }
      } catch (error) {
        this.pageIndex--;
        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 { code, returnData } = await this.getQueryList(SERVICE_ID.authTreeId, { role_id: item.role_ID })
      if (code == 0) {
        const result = returnData
        this.checkDatas.push(result)
        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) => {
              this.$refs.tree.setChecked(item.auth_id, false, false);
            });
          }, 50);
        }
      }
    },
    //服务列表-点击
    handleClick (item, index) {
      this.dataType = 'edit'
      this.dataObj = _.cloneDeep(item)
      this.formInline = _.cloneDeep(item)
      this.activeIndex = index
      this.flag = false
      this.getRoleQuth(item)
    },
    //服务列表-保存
    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.treeCheckId = data.auth_id
      this.treeCheckObj = data
    },
    checkChange () {
      if (this.dataObj.role_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)
        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 msgs = []
      res.forEach(item => {
        msgs.push({
          ID: item.ID
        })
        item.role_id = this.dataObj.role_ID
        item.role_name = this.dataObj.role_name
        item.role_status = this.dataObj.role_status
      })
      if (type == 'add') {
        const { code } = await this.getChangeList(SERVICE_ID.authTreeId, res, 1)
        if (code == 0) {
          setTimeout(() => {
            this.getRoleQuth(this.dataObj)
          }, 100);
        }
        this.tipMsg(code)
      } else {
        const { code } = await this.getChangeList(SERVICE_ID.authTreeId, msgs, 3)
        if (code == 0) {
          setTimeout(() => {
            this.getRoleQuth(this.dataObj)
          }, 100);
        }
        this.tipMsg(code)
      }
      // this.checkArrs = []
    },
    async setItem (node, data) {
      if (this.dataObj.role_ID) {
        const { code, returnData } = await this.getQueryList(SERVICE_ID.getTableColumnId, { serviceOutPutId: data.auth_id })
        if (code == 0) {
          const result = returnData
          if (result && result) {
            this.checkArrs = result
            const { code, returnData } = await this.getQueryList(SERVICE_ID.authTreeId, [{ auth_id: data.auth_id }, { role_id: this.dataObj.role_ID }])
            if (code == 0) {
              const res = returnData
              if (res && res.length) {
                const resmsg = []
                result.forEach((item) => {
                  res.forEach(p => {
                    if (item.queryTemplateColumnSetID == p.queryTemplateColumnSetID) {
                      item.rowauth = p.rowauth
                      resmsg.push(item)
                    }
                  })
                })
                if (resmsg && resmsg.length) {
                  resmsg.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                  });
                }
                this.checkGroups = resmsg
                this.multipleTable = resmsg
              }
            }
          }
        }
      } else {
        this.$message.error('请选中角色后再操作');
      }
    },
    async groupChange (val) {
      this.checkGroups.push(val)
      if (this.checkGroups.length == 1) {
        const res = this.getColName(val)
        const result = this.sendCheckData(res)
        const { code } = await this.getChangeList(SERVICE_ID.authTreeId, result, 1)
        this.tipMsg(code)
      } else if (this.checkGroups.length > 1) {
        const data1 = this.checkGroups[this.checkGroups.length - 1]; //最后一条数据
        const data2 = this.checkGroups[this.checkGroups.length - 2]; //倒数第二条数据
        const msg = [...data1, ...data2].filter((item) => !(data1.some((p) => item == p) && data2.some((c) => item == c)));
        const cap = this.getColName(msg)
        const result = this.sendCheckData(cap)
        if (data1.length > data2.length) {
          const { code } = await this.getChangeList(SERVICE_ID.authTreeId, result, 1)
          this.tipMsg(code)
        } else {
          const { code } = await this.getChangeList(SERVICE_ID.authTreeId, result, 3)
          this.tipMsg(code)
        }
      }
    },
    sendCheckData (arr, type = false) {
      const newData = []
      arr.forEach(item => {
        if (type) {
          const obj = {
            "role_id": this.dataObj.role_ID,
            "auth_id": this.treeCheckObj.auth_id,
            "queryTemplateColumnSetID": item.queryTemplateColumnSetID,
          }
          newData.push(obj)
        } else {
          const obj = {
            "role_id": this.dataObj.role_ID,
            "role_name": this.dataObj.role_name,
            "role_status": this.dataObj.role_status,
            "auth_id": this.treeCheckObj.auth_id,
            "auth_type": this.treeCheckObj.auth_type,
            "queryTemplateColumnSetID": item.queryTemplateColumnSetID,
            "columnLabel": item.columnLabel,
            "columnname": item.columnName,
            "rowauth": item.rowauth
          }
          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 () {
      const result = this.sendCheckData(this.multipleTable)
      const dis = this.sendCheckData(this.checkGroups, true)
      if (dis && dis.length) {
        await this.getChangeList(SERVICE_ID.authTreeId, dis, 3)
      }
      const { code } = await this.getChangeList(SERVICE_ID.authTreeId, result, 1)
      this.tipMsg(code)
    }
  }
}
</script>

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