<template>
  <el-container style="height: 100%;position: absolute;width: 100%;">
    <el-col :span="6" style="border-right: 1px solid #e6e6e6;height: 100%;">
      <div style="height:30px;">
        <el-button style="margin: 1px" type="primary" icon="el-icon-search" @click="handleWorkGroupQuery">查询</el-button>
        <el-button style="margin: 1px" type="success" @click="handleWorkGroupAdd">增加</el-button>
        <el-button style="margin: 1px" type="warning" @click="handleWorkGroupUpdate">修改</el-button>
        <el-button style="margin: 1px" type="danger" @click="handleWorkGroupDelete">删除</el-button>
        <el-button style="margin: 1px" @click="handleWorkGroupPrint">打印</el-button>
      </div>

      <el-table
        ref="gzzTable"
        v-loading="isGzzTableLoading"
        class="gzzTable"
        style="flex: 1;clear: left;"
        :show-overflow-tooltip="true"
        :data="c_gzzTableData"
        height="calc(100% - 30px)"
        width="100%"
        :border="true"
        highlight-current-row
        element-loading-background="rgba(0, 0, 0, 0.05)"
        element-loading-text="数据正在加载中"
        element-loading-spinner="el-icon-loading"
        @current-change="handleWorkGroupChange"
        @header-click="showFilter"
      >
        <el-table-column sortable label="代码" property="role_code" />
        <el-table-column sortable label="名称" property="role_name" />
      </el-table>

      <el-dialog
        class="WorkGroupDialog"
        :title="dialogTitle"
        :visible.sync="dialogTableVisible"
        width="350px"
        center=""
      >
        <el-row>
          <el-row>
            <span style="width: 60px;display:inline-block;">代码：</span>
            <el-input v-model="updateData.role_code" placeholder="" style="width: 200px;" :disabled="inputDisabled"/>
          </el-row>
          <el-row>
            <span style="width: 60px;display:inline-block;">名称：</span>
            <el-input v-model="updateData.role_name" placeholder="" style="width: 200px;" />
          </el-row>
          <el-row style="margin-top:20px;">
            <el-button
              v-if="dialogTitle =='添加工作组'?true :false"
              style="float: right;"
              type="primary"
              @click="handleWorkGroupAddComplated"
            >添加
            </el-button>
            <el-button
              v-if="dialogTitle =='修改工作组'?true :false"
              style="float: right;"
              type="primary"
              @click="handleWorkGroupUpdateComplated"
            >修改
            </el-button>
          </el-row>
        </el-row>
      </el-dialog>

    </el-col>
    <el-col :span="18" style="height: 100%;" :height="defaultHeight.height">
      <el-tabs v-model="activeTabName" style="padding-left: 5px;" @tab-click="handleTabClick">
        <el-tab-pane label="用户信息" name="yhxx">
          <el-table
            ref="yhxxTable"
            v-loading="isYhxxTableLoading"
            :show-overflow-tooltip="true"
            :data="yhxxTableData"
            :height="defaultHeight.height"
            width="100%"
            :border="true"
            highlight-current-row
            element-loading-background="rgba(0, 0, 0, 0.01)"
            element-loading-text="数据正在加载中"
            element-loading-spinner="el-icon-loading"
          >
            <el-table-column label="" property="checked" style="width: 30px;">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked" @change="handleYhxxSelect(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="用户代码" property="yhdm" />
            <el-table-column label="用户名称" property="yhms" />
            <el-table-column label="所属部门" property="bmbm">
              <template slot-scope="scope">
                {{ getDepartName(scope.row.bmbm) }}
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="分组权限" name="fzqx">
          <el-table
            ref="fzqxTable"
            v-loading="isFzqxTableLoading"
            :show-overflow-tooltip="true"
            :data="fzqxTableData"
            :height="defaultHeight.height"
            width="100%"
            :border="true"
            highlight-current-row
            element-loading-background="rgba(0, 0, 0, 0.01)"
            element-loading-text="数据正在加载中"
            element-loading-spinner="el-icon-loading"
          >
            <el-table-column label="" property="checked" style="width: 30px;">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked" @change="handleFzqxSelect(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="编码" property="institution_code" />
            <el-table-column label="分类组名称" property="institution_name" />
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="子系统权限" name="zxtqx">
          <el-table
            ref="zxtqxTable"
            v-loading="isZxtqxTableLoading"
            :show-overflow-tooltip="true"
            :data="zxtqxTableData"
            :height="defaultHeight.height"
            width="100%"
            :border="true"
            highlight-current-row
            element-loading-background="rgba(0, 0, 0, 0.01)"
            element-loading-text="数据正在加载中"
            element-loading-spinner="el-icon-loading"
          >
            <el-table-column label="" property="checked" style="width: 30px;">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked" @change="handleZxtSelect(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="编码" property="zxtdm" />
            <el-table-column label="子系统名称" property="zxtms" />
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="功能权限" name="gnqx">
          <el-col :span="6" :height="defaultHeight.height" style="overflow-y: scroll">
            <el-tree
              ref="tree"
              v-loading="isGnqxTreeLoading"
              :data="gnqxTreeData"
              :style="defaultHeight"
              show-checkbox
              accordion
              :expand-on-click-node="false"
              highlight-current
              node-key="id"
              @check="treeNodeCheck"
              @node-click="treeNodeClick"
            />
          </el-col>
          <el-col :span="18" :height="defaultHeight.height">
            <div :height="defaultHeight.height">
              <el-table
                ref="gnqxTable"
                v-loading="isGnqxTableLoading"
                :show-overflow-tooltip="true"
                :data="c_gnqxTableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                :height="defaultHeight.height35"
                width="100%"
                :border="true"
                highlight-current-row
                element-loading-background="rgba(0, 0, 0, 0.01)"
                element-loading-text="数据正在加载中"
                element-loading-spinner="el-icon-loading"
              >
                <el-table-column label="" property="checked" style="width: 30px;">
                  <template slot-scope="scope">
                    <el-checkbox v-model="scope.row.checked" @change="handleGnqxSelect(scope.row)" />
                  </template>
                </el-table-column>
                <el-table-column label="菜单名称" property="menu_name" />
                <el-table-column label="功能类别" property="gnlb" />
                <el-table-column label="菜单" property="ylzd1" />
              </el-table>
              <el-pagination
                :current-page="currentPage"
                :page-sizes="[20, 50, 100, 10000]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="c_gnqxTableData.length"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-col>
        </el-tab-pane>
      </el-tabs>
    </el-col>
    <tbfilter ref="tbFilter" :list="c_gzzTableData" :filter="columnFilter" @execFilter="execFilter" />
  </el-container>
</template>
<script>
// import { PlTable, PlTableColumn } from 'pl-table'
import {
  getDepartList,
  getSystemList,
  getRoleList,
  getUserList,
  getInstitutionList,
  getMenuForRole,

  addRole,
  deleteRole,
  updateRole,

  getUserListByRole,
  addRoleForUser,
  deleteRoleForUser,

  getInstitutionListByRole,
  addRoleForInstitution,
  deleteRoleForInstitution,

  getSystemListByRole,
  addRoleForSystem,
  deleteRoleForSystem,

  getMenuListByRole,
  addRoleForMenu,
  deleteRoleForMenu
} from '@/api/sy/yhgl'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import tbfilter from '@/components/TableColumnFilter'

export default {
  name: 'Jsgl',
  components: { tbfilter },
  data() {
    return {
      defaultHeight: {
        height: '',
        height35: ''
      },
      zxtbmList: [],
      dm_depart: [],
      inputDisabled:true,
      currentPage: 1,
      pageSize: 100,
      activeTabName: 'yhxx',
      gzzTableData: [],
      isGzzTableLoading: true,
      yhxxTableData: [],
      isYhxxTableLoading: true,
      fzqxTableData: [],
      isFzqxTableLoading: true,
      zxtqxTableData: [],
      isZxtqxTableLoading: true,
      gnqxTreeData: [],
      isGnqxTreeLoading: true,
      gnqxTableData: [],
      isGnqxTableLoading: true,
      selectWorkGroup: {},
      gnqxQueryZxtbm: '',
      gnqxQueryMenuid: '',
      dialogTableVisible: false,
      dialogTitle: '',
      updateData: {},
      columnFilter: {}
    }
  },
  computed: {
    c_gzzTableData: function() {
      const resultList = this.gzzTableData
      if (this.$refs.tbFilter) {
        return this.$refs.tbFilter.doFilter(this.columnFilter, resultList)
      }
      return resultList
    },
    c_gnqxTableData: function() {
      let resultList = this.gnqxTableData
      if (this.gnqxQueryMenuid === '@') {
        return resultList
      }
      if (!this.gnqxQueryZxtbm) {
        resultList = this.gnqxTableData.filter(data => {
          return data.system_code === this.gnqxQueryMenuid
        })
        return resultList
      }
      if (this.gnqxQueryMenuid) {
        resultList = resultList.filter(data => {
          return data.parent_id === this.gnqxQueryMenuid
        })
        return resultList
      }
      return resultList
    }
  },
  created() {
    getDepartList({}).then(response => {
      this.dm_depart = response.data
      getSystemList({}).then(response => {
        this.zxtbmList = response.data
        this.zxtqxTableData = response.data
        this.isZxtqxTableLoading = false
        getUserList({}).then(response => {
          this.yhxxTableData = response.data
          this.isYhxxTableLoading = false
          getInstitutionList({}).then(response => {
            this.fzqxTableData = response.data
            this.isFzqxTableLoading = false
            getMenuForRole({}).then(response => {
              this.gnqxTreeData = this.parseTreeData(response.data)
              this.gnqxTableData = response.data
              this.isGnqxTableLoading = false
              this.isGnqxTreeLoading = false
              getRoleList({}).then(response => {
                this.gzzTableData = response.data
                this.isGzzTableLoading = false
                this.$refs.gzzTable.setCurrentRow(this.gzzTableData[0])
              })
            })
          })
        })
      })
    })
    window.addEventListener('resize', this.getHeight)
    this.getHeight()
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    showFilter(column) {
      this.$refs.tbFilter.showFilter(column)
    },
    execFilter(property, vals) {
      this.currentPage = 1
      this.$set(this.columnFilter, property, vals)
    },
    getHeight() {
      this.defaultHeight.height = window.innerHeight - 140 + 'px'
      this.defaultHeight.height35 = window.innerHeight - 140 - 35 + 'px'
    },
    getDepartName(depart_code) {
      for (const i in this.dm_depart) {
        if (this.dm_depart[i].depart_code === depart_code) {
          return this.dm_depart[i].depart_name
        }
      }
      return ''
    },
    getSystemName(system_code) {
      for (const i in this.zxtbmList) {
        if (this.zxtbmList[i].zxtdm === system_code) {
          return this.zxtbmList[i].zxtms
        }
      }
      return ''
    },
    parseTreeData(menu) {
      const treeData = [{ 'label': '全部功能', 'id': '@', children: [], disabled: true }]

      const info = menu.reduce((map, node) => {
        node.label = node.menu_name
        return map[node.id] = node, node.children = [], map
      }, {})
      const result = menu.filter(node => {
        if (info[node.parent_id]) {
          info[node.parent_id].children.push(node)
        }
        return !node.parent_id
      })
      const system_menu = {}
      for (let i = 0; i < result.length; i++) {
        if (!system_menu[result[i].system_code]) {
          system_menu[result[i].system_code] = []
        }
        system_menu[result[i].system_code].push(result[i])
      }
      // for (let i = 0; i < this.zxtbmList.length; i++) {
      //   const key = this.zxtbmList[i].zxtdm
      //   console.log(system_menu[key])
      //   treeData[0].children.push({ 'label': this.getSystemName(key), 'id': key, 'children': system_menu[key] })
      // }
      treeData[0].children.push({ 'label': this.getSystemName('PS'), 'id': 'PS', 'children': system_menu['PS'] })
      console.log('treeData',treeData)
      return treeData
    },
    handleWorkGroupChange(val) {
      if (!val) return
      this.selectWorkGroup = val
      this.isYhxxTableLoading = true
      this.isFzqxTableLoading = true
      this.isZxtqxTableLoading = true
      this.isGnqxTableLoading = true
      this.isGnqxTreeLoading = true

      for (const j in this.yhxxTableData) {
        this.$set(this.yhxxTableData[j], 'checked', false)
      }
      for (const j in this.fzqxTableData) {
        this.$set(this.fzqxTableData[j], 'checked', false)
      }
      for (const j in this.zxtqxTableData) {
        this.$set(this.zxtqxTableData[j], 'checked', false)
      }
      for (const j in this.gnqxTableData) {
        this.$set(this.gnqxTableData[j], 'checked', false)
      }
      this.$refs.tree.setCheckedNodes([])

      getUserListByRole(val).then(response => {
        for (const i in response.data) {
          for (const j in this.yhxxTableData) {
            if (response.data[i].yhdm === this.yhxxTableData[j].yhdm) {
              this.$set(this.yhxxTableData[j], 'checked', true)
            }
          }
        }
        this.isYhxxTableLoading = false
      })

      getInstitutionListByRole(val).then(response => {
        for (const i in response.data) {
          for (const j in this.fzqxTableData) {
            if (response.data[i].institution_code === this.fzqxTableData[j].institution_code) {
              this.$set(this.fzqxTableData[j], 'checked', true)
            }
          }
        }
        this.isFzqxTableLoading = false
      })

      getSystemListByRole(val).then(response => {
        for (const i in response.data) {
          for (const j in this.zxtqxTableData) {
            if (response.data[i].zxtdm === this.zxtqxTableData[j].zxtdm) {
              this.$set(this.zxtqxTableData[j], 'checked', true)
            }
          }
        }
        this.isZxtqxTableLoading = false
      })

      getMenuListByRole(val).then(response => {
        for (const i in response.data) {
          for (const j in this.gnqxTableData) {
            if (response.data[i].menu_id === this.gnqxTableData[j].id) {
              this.$set(this.gnqxTableData[j], 'checked', true)
            }
          }
        }

        for (const i in response.data) {
          const id = response.data[i].menu_id
          this.$refs.tree.setChecked(id, true, false)
        }
        this.isGnqxTreeLoading = false
        this.isGnqxTableLoading = false
      })
    }, handleWorkGroupQuery() {
      this.isGzzTableLoading = true
      getRoleList({}).then(response => {
        this.gzzTableData = response.data
        this.isGzzTableLoading = false
      })
    }, handleWorkGroupAdd() {
      this.dialogTitle = '添加工作组'
      this.dialogTableVisible = true
      this.inputDisabled=false;
      this.updateData = {}
    },
    handleWorkGroupAddComplated() {
      addRole(this.updateData).then(response => {
        this.$message({ message: '添加用户组成功！', type: 'success' })
        this.updateData = JSON.parse(JSON.stringify(this.updateData))
        this.gzzTableData = [this.updateData].concat(this.gzzTableData)
        this.dialogTableVisible = false
      })
    }, handleWorkGroupUpdate() {
      if (!this.selectWorkGroup || !this.selectWorkGroup.role_code) {
        this.$message({ message: '请选择一个工作组！', type: 'warning' })
        return
      }
      this.dialogTitle = '修改工作组'
      this.dialogTableVisible = true
      this.inputDisabled=true
      this.updateData = JSON.parse(JSON.stringify(this.selectWorkGroup))
    }, handleWorkGroupUpdateComplated() {
      updateRole(this.updateData).then(response => {
        for (const key in this.updateData) {
          this.selectWorkGroup[key] = this.updateData[key]
        }
        this.dialogTableVisible = false
        this.$message({ message: '修改用户信息成功！', type: 'success' })
      })
    }, handleWorkGroupDelete() {
      this.$confirm('此操作将删除该工作组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (!this.selectWorkGroup || !this.selectWorkGroup.role_code) {
          this.$message({ message: '请选择一个工作组！', type: 'warning' })
          return
        }
        deleteRole(this.selectWorkGroup).then(response => {
          this.gzzTableData = this.gzzTableData.filter(t => !(t.role_code === this.selectWorkGroup.role_code))
          this.$message({ message: '删除工作组成功！', type: 'success' })
        })
      })
    }, handleYhxxSelect(row) {
      if (!this.selectWorkGroup || !this.selectWorkGroup.role_code) {
        this.$message({ message: '请选择一个工作组！', type: 'warning' })
        return
      }
      const data = { 'role_code': this.selectWorkGroup.role_code, 'yhdm': row.yhdm, 'yhms': row.yhms }
      if (row.checked) {
        addRoleForUser([data]).then(response => {
          this.$message({ message: '添加用户到工作组成功！', type: 'success' })
        })
      } else {
        deleteRoleForUser([data]).then(response => {
          this.$message({ message: '从工作组移除用户成功！', type: 'success' })
        })
      }
    }, handleFzqxSelect(row) {
      const data = { 'role_code': this.selectWorkGroup.role_code,
                      'FZDM': row.institution_code.substring(0,2) ,
                      'ZXTDM':row.institution_code.substring(2),
                  }
      if (row.checked) {
        addRoleForInstitution([data]).then(response => {
          this.$message({ message: '添加分组权限到工作组成功！', type: 'success' })
        })
      } else {
        deleteRoleForInstitution([data]).then(response => {
          this.$message({ message: '从工作组移除分组权限成功！', type: 'success' })
        })
      }
    }, handleZxtSelect(row) {
      const data = { 'role_code': this.selectWorkGroup.role_code, 'system_code': row.zxtdm }
      if (row.checked) {
        addRoleForSystem([data]).then(response => {
          this.$message({ message: '添加子系统权限到工作组成功！', type: 'success' })
        })
      } else {
        deleteRoleForSystem([data]).then(response => {
          this.$message({ message: '从工作组移除子系统权限成功！', type: 'success' })
        })
      }
    },
    handleGnqxSelect(row) {
      let gnlb=''
      if (row.gnlb){
        gnlb=row.gnlb
      }
      const data = { 'role_code': this.selectWorkGroup.role_code,
                    'system_code': row.system_code,
                    'menu_name': row.menu_name,
                    'gnlb': gnlb,
                    }
      if (row.checked) {
        addRoleForMenu([data]).then(response => {
          this.$refs.tree.setChecked(row.id, true, false)
          this.$message({ message: '添加功能菜单到工作组成功！', type: 'success' })
        })
      } else {
        deleteRoleForMenu([data]).then(response => {
          this.$refs.tree.setChecked(row.id, false, false)
          this.$message({ message: '从工作组移除功能菜单成功！', type: 'success' })
        })
      }
    },
    treeNodeClick(data) {
      this.currentPage = 1
      this.pageSize = 100
      this.gnqxQueryZxtbm = data.system_code
      this.gnqxQueryMenuid = data.id
    },
    treeNodeCheck(checkedNode) {
      const checked = this.$refs.tree.getNode(checkedNode.id).checked
      this.selectMenuRole(checkedNode, checked)
    },
    selectMenuRole(checkedNode, checked) {
      const deleteFunction = []
      const insertFunction = []
      const selectedKeys = this.$refs.tree.getCheckedNodes(false, true)

      for (const j in this.gnqxTableData) {
        const source = this.gnqxTableData[j]['checked']
        this.gnqxTableData[j]['checked'] = false
        for (let i = 0; i < selectedKeys.length; i++) {
          if (this.gnqxTableData[j]['id'] === selectedKeys[i].id) {
            this.gnqxTableData[j]['checked'] = true
          }
        }
        let gnlb=''
        if (this.gnqxTableData[j]['gnlb']){
          gnlb=this.gnqxTableData[j]['gnlb']
        }
        const data = { 'role_code': this.selectWorkGroup.role_code,
                        'system_code': this.gnqxTableData[j]['system_code'],
                        'menu_name': this.gnqxTableData[j]['menu_name'],
                        'gnlb': gnlb
                          }
        if (source && !this.gnqxTableData[j]['checked']) {
          deleteFunction.push(data)
        }
        if (!source && this.gnqxTableData[j]['checked']) {
          insertFunction.push(data)
        }
      }
      addRoleForMenu(insertFunction).then(response => {
        // this.$message({ message: '添加功能菜单到工作组成功！', type: 'success' })
      })
      deleteRoleForMenu(deleteFunction).then(response => {
        // this.$message({ message: '从工作组移除功能菜单成功！', type: 'success' })
      })
      this.$message({ message: '修改工作组功能菜单成功！', type: 'success' })
    },
    handleWorkGroupPrint() {
      /* generate workbook object from table */
      // 表名
      var wb = XLSX.utils.table_to_book(document.querySelector('.gzzTable'))
      /* get binary string as output */
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'gzz.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    }, handleTabClick() {
      if (!this.selectWorkGroup || !this.selectWorkGroup.role_code) {
        this.$message({ message: '请选择一个工作组！', type: 'warning' })
        return
      }
    }
  }
}
</script>

<style scoped>
  .WorkGroupDialog .el-row {
    margin-bottom: 5px;
  }
</style>
