<style scoped> </style>
<template>
  <div class="container-fluid">
    <el-row class="filter_style">
      <el-col :span="24" style="padding: 0 0">
        <_BTN_FILTER :btnGroups="btnGroups" :fileName="fileName" @on-change="inputChange"
                     :tableData="tableData"/>
      </el-col>
    </el-row>
    <div>
      <tableVue
        ref="tableGrid"
        stripe border
        maxHeight="500"
        column-type="selection"
        :data="dataSource"
        :columns="columns"
        :pageSizes="pageSizes" :currentPage="currentPage" :pageSize="pageSize"
        :totalCount="totalCount" :hasPagination="hasPagination" :setPage=this.queryData></tableVue>
    </div>
    <_POPUP :dialogObj='dialogObj_base' @confirmBack="confirmBack_base"/>
    <!--<_POPUP :dialogObj='sessionFailedDialogObj' @confirmBack="sessionFailedBack" />-->
    <_TRANSFERPOP ref="child" :dialogObj='dialogObj_power_allot' @confirmBack="confirmBack_power_allot"/>
    <_TREEPOPUP :dialogObj='dialogObj_tree' :treedialogVisible='treedialogVisible'/>

  </div>
</template>
<script>
  import tableVue from '@/views/components/table/table.vue'
  import _BTN_FILTER from '@/views/components/Screen/btn&filterTemp.vue'
  import _POPUP from './Popup.vue'
  import _TRANSFERPOP from './TreePopup.vue'
  import _TREEPOPUP from '@/views/components/Popup/treePopup.vue'
  import api from '@/api'
  import log from '@/log'
  import { getUser } from '@/config/info'
  import BasePath from '@/config/BasePath'
  export default {
    mounted () {
//      this.queryData(this.currentPage, this.pageSize)
      this.init()
    },
    data () {
      return {
        /** table **/
        currentPage: 1, // 默认当前第一页
        pageSize: 10,  // 默认每页20条数据
        pageSizes: [5, 10, 20, 40, 50], // 分页数选择项
        selectSells: [],
        totalCount: 0, // 表格总记录数
        hasPagination: true, // 是否有分页
        columns: [ // 表格列
          { label: '编号', prop: 'roleCode', columnsProps: {width: 200} },
          { label: '名称', prop: 'roleName', columnsProps: {width: 200} },
          { label: '角色类型', prop: 'attrFlag', columnsProps: {width: 200, formatter: this.colFormatter_attrFlag} },
          { label: '备注', prop: 'remark', columnsProps: {width: 200} },
          { label: '操作', prop: 'operation', columnsProps: {width: 220, type: 'button'}, cptProperties: [{ label: '修改', value: 'modify', type: 'text', eventClick: this.modify }, { label: '删除', value: 'del', type: 'text', eventClick: this.del }, { label: '分配', value: 'distribution', type: 'text', eventClick: this.distribution }, { label: '权限', value: 'jurisdiction', type: 'text', eventClick: this.jurisdiction }] }
        ],
        tableData: [], // 表格数据
        dataSource: [], // 当前页的数据
        /** filter **/
        fileName: ['roleCode', 'roleName'], // 过滤字段值
        btnGroups: [
          {
            name: '新增', // 按钮名称
            className: 'btn-info', // 按钮样式名称
            iconName: 'fa-plus', // 按钮图标名称
            event: this.addClk // 按钮事件方法名称；可以自定义
          }
//          {
//            name: '批量删除', // 按钮名称
//            className: 'btn-danger', // 按钮样式名称
//            iconName: 'fa-remove', // 按钮图标名称
//            event: this.batchDelClk // 按钮事件方法名称；可以自定义
//          }
        ], // 按钮组
        treedialogVisible: false,
        /** 弹出层 **/
        dialogObj_base: {
          title: '角色维护',
          type: 'addConfigure',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              roleCode: '',
              roleName: '',
              attr_name: '',
              attrFlag: '',
              remark: '',
              deletedFlag: '0',
              haveAttach: '0',
              mapKey: 'string',
              modificationNum: '0',
              originApp: '1',
              originFlag: '1',
              placeId: 0,
              status: '1'
            }
          }
        },
        /** 弹出层 **/
        dialogObj_tree: {
          title: '',
          type: '',
          nodeKey: '',
          treedialogVisible: false,
          getDataObj: {},
          conmitObj: {}
        },
        temp_base: {
          title: '角色维护',
          type: 'addConfigure',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              roleCode: '',
              roleName: '',
              attr_name: '',
              attrFlag: '',
              remark: '',
              deletedFlag: '0',
              haveAttach: '0',
              mapKey: 'string',
              modificationNum: '0',
              originApp: '1',
              originFlag: '1',
              placeId: 0,
              status: '1'
            }
          }
        }, // 临时变量-角色维护
        /** 弹出层 **/
        dialogObj_power_allot: {
          title: '用户授权',
          type: 'addConfigure',
          Source: '可选用户列表',
          Target: '已选用户列表',
          dialogVisible: false,
          data: {
            form: {
              rowId: ''
            }
          }
        },
        /** 实际操作 **/
        sel_all: [],
        sessionFailedDialogObj: {
          title: '会话失效',
          type: 'sessionFailured',
          dialogVisible: false,
          size: 'tiny',
          data: {
            form: {
              userCode: '',
              password: ''
            }
          }
        }
      }
    },
    methods: {
      getTime (data) {
        return dateFormat(data, 'YYYY-MM-DD')
      },  // 时间格式化
      init () {
        api.requestJava('POST', BasePath.ROLE_SELECT, {})
          .then(request => {
            if (Number(request.data.code) === 200) {
              this.tableData = request.data.data
              this.currentPage = 1
              this.queryData(this.currentPage, this.pageSize)
            } else {
              this.$notify.error({ title: '提示', message: request.data.message })
              throw new Error(JSON.stringify(request))
            }
          })
          .catch(err => {
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      },
      colFormatter_attrFlag (row, column) {
        let retStr = ''
        switch (row.attrFlag) {
          case '1':
            retStr = '管理员'
            break
          case '2':
            retStr = '普通'
            break
          case '3':
            retStr = '其他'
            break
        }
        return retStr
      },
      queryData (page, size) {
        // 前段分页
        this.totalCount = this.tableData.length
        this.dataSource = this.tableData.filter((u, index) => index < size * page && index >= size * (page - 1))
      }, // 分页请求
      select (selection, index) {
        if (selection[0] !== undefined) {
          this.sel_all = []
          for (var i in selection) {
            this.sel_all.push(selection[i].rowId)
          }
          console.log(this.sel_all)
        }
      }, // 选中某1条
      selectAll (data) {
        this.sel_all = []
        for (var i in data) {
          this.sel_all.push(data[i].rowId)
        }
      }, // 全选
      clearObject () {
        console.log('this.temp_base:', this.temp_base)
        let temp = {
          title: '角色维护',
          type: 'addConfigure',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              roleCode: '',
              roleName: '',
              attr_name: '',
              attrFlag: '',
              remark: '',
              deletedFlag: '0',
              haveAttach: '0',
              mapKey: 'string',
              modificationNum: '0',
              originApp: '1',
              originFlag: '1',
              placeId: 0,
              status: '1',
              division: ''
            }
          }
        }
        Object.assign(this.dialogObj_base, temp)
      },
      addClk () {
        this.clearObject()
        this.dialogObj_base.dialogVisible = true
      }, // 新增
      modify (index, row) {
        this.dialogObj_base.data.form.disabled = true
        Object.assign(this.dialogObj_base.data.form, row)
        this.dialogObj_base.dialogVisible = true
      }, // 修改
      del (index, row) {
        let params = {}
        params.rowId = row.rowId
        let permissionParams = {}
        permissionParams.roleId = row.rowId
        console.log(JSON.stringify(params))
        api.requestJava('POST', BasePath.ROLE_PERMISSIONS_QUERY, permissionParams) // 角色赋权查询
          .then(request => {
            if (Number(request.data.code) === 200) {
              console.log(request.data)
              console.log(request.data.data.length)
              if (request.data.data.length === 0) { // 没有赋权删除
//                this.$confirm('确定删除此条信息吗？', '提示', {
//                  confirmButtonText: '确定',
//                  cancelButtonText: '取消',
//                  type: 'warning'
//                }).then(() => {
//                  api.requestJava('POST', BasePath.ROLE_DELETE, params, {})
//                    .then(request => {
//                      if (Number(request.data.code) === 200) {
//                        this.$message({ type: 'success', message: '删除成功!' })
//                        this.init()
//                      } else {
//                        this.$notify.error({ title: '提示', message: Number(request.data.code) })
//                        throw new Error(JSON.stringify(request))
//                      }
//                    }).catch(() => {
//                      this.$message({ type: 'info', message: '删除操作异常!' })
//                    }
//                  )
//                }).catch(() => {
//                  this.$message({ type: 'info', message: '已取消删除!' })
//                })
                api.requestJava('POST', BasePath.ROLE_USER_QUERY, permissionParams, {})
                  .then(request => {
                    if (Number(request.data.code) === 200) {
                      if (request.data.data.length === 0) { // 没有赋权删除
                        api.requestJava('POST', BasePath.ROLE_DELETE, params, {})
                          .then(request => {
                            if (Number(request.data.code) === 200) {
                              this.$message({ type: 'success', message: '删除成功!' })
                              this.init()
                            } else {
                              this.$notify.error({ title: '提示', message: Number(request.data.code) })
                              throw new Error(JSON.stringify(request))
                            }
                          }).catch(() => {
                            this.$message({ type: 'info', message: '删除操作异常!' })
                          }
                        )
                      } else {
                        // 已经赋权
                        this.$confirm('此角色已经被赋权，是否确定删除？', '提示', {
                          confirmButtonText: '确定',
                          cancelButtonText: '取消',
                          type: 'warning'
                        }).then(() => {
                          api.requestJava('POST', BasePath.ROLE_PERMISSIONS_DELETE, permissionParams, {}) // 先删除赋权表
                            .then(request => {
                              if (Number(request.data.code) === 200) {
                                console.log('ROLE_PERMISSIONS_DELETE' + request.data.code)
//                                api.requestJava('POST', BasePath.ROLE_DELETE, params, {})
//                                  .then(request => {
//                                    if (Number(request.data.code) === 200) {
//                                      this.$message({ type: 'success', message: '删除成功!' })
//                                      this.init()
//                                    } else {
//                                      this.$notify.error({ title: '提示', message: Number(request.data.code) })
//                                      throw new Error(JSON.stringify(request))
//                                    }
//                                  }).catch(() => {
//                                    this.$message({ type: 'info', message: '删除操作异常!' })
//                                  }
//                                )
                                api.requestJava('POST', BasePath.ROLE_DELETE, params, {})
                                  .then(request => {
                                    if (Number(request.data.code) === 200) {
                                      api.requestJava('POST', BasePath.ROLE_DELETE, params, {})
                                      .then(request => {
                                        if (Number(request.data.code) === 200) {
                                          this.$message({ type: 'success', message: '删除成功!' })
                                          this.init()
                                        } else {
                                          this.$notify.error({ title: '提示', message: Number(request.data.code) })
                                          throw new Error(JSON.stringify(request))
                                        }
                                      }).catch(() => {
                                        this.$message({ type: 'info', message: '删除操作异常!' })
                                      }
                                )
                                    } else {
                                      this.$notify.error({ title: '提示', message: Number(request.data.code) })
                                      throw new Error(JSON.stringify(request))
                                    }
                                  }).catch(() => {
                                    this.$message({ type: 'info', message: '删除操作异常!' })
                                  }
                                )
                              } else {
                                this.$notify.error({ title: '提示', message: Number(request.data.code) })
                                throw new Error(JSON.stringify(request))
                              }
                            }).catch(() => {
                              this.$message({ type: 'info', message: '删除操作异常!' })
                            }
                          )
                        }).catch(() => {
                          this.$message({ type: 'info', message: '已取消删除!' })
                        })
                      }
                    } else {
                      this.$notify.error({ title: '提示', message: Number(request.data.code) })
                      throw new Error(JSON.stringify(request))
                    }
                  }).catch(() => {
                    this.$message({ type: 'info', message: '删除操作异常!' })
                  }
                )
              } else { // 已经赋权
                this.$confirm('此角色已经被赋权，是否确定删除？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  api.requestJava('POST', BasePath.ROLE_PERMISSIONS_DELETE, permissionParams, {}) // 先删除赋权表
                    .then(request => {
                      if (Number(request.data.code) === 200) {
                        console.log('ROLE_PERMISSIONS_DELETE' + request.data.code)
                        api.requestJava('POST', BasePath.ROLE_DELETE, params, {})
                          .then(request => {
                            if (Number(request.data.code) === 200) {
                              this.$message({ type: 'success', message: '删除成功!' })
                              this.init()
                            } else {
                              this.$notify.error({ title: '提示', message: Number(request.data.code) })
                              throw new Error(JSON.stringify(request))
                            }
                          }).catch(() => {
                            this.$message({ type: 'info', message: '删除操作异常!' })
                          }
                        )
                      } else {
                        this.$notify.error({ title: '提示', message: Number(request.data.code) })
                        throw new Error(JSON.stringify(request))
                      }
                    }).catch(() => {
                      this.$message({ type: 'info', message: '删除操作异常!' })
                    }
                  )
                }).catch(() => {
                  this.$message({ type: 'info', message: '已取消删除!' })
                })
              }
            } else {
              this.$notify.error({ title: '提示', message: Number(request.data.code) })
              throw new Error(JSON.stringify(request))
            }
          }).catch(() => {
            this.$message({ type: 'info', message: '删除操作异常!' })
          }
        )
      },  // 删除
      distribution (index, row) {
        this.dialogObj_power_allot.data.form.rowId = row.rowId
        this.$refs.child.source_goal()
        this.dialogObj_power_allot.dialogVisible = true
      }, // 分配
      jurisdiction (index, row) {
        this.dialogObj_tree.title = '角色权限'
        this.dialogObj_tree.type = 'authority'
        this.dialogObj_tree.nodeKey = 'rowId'
        this.dialogObj_tree.getDataObj = {'url': 'menu/selectByCode.do', params: {'roleId': row.rowId, 'treeKey': 'parentId', 'treeRoot': 1}}
        this.dialogObj_tree.conmitObj = {'url': 'menu/merge.do', params: {'roleId': row.rowId, 'treeKey': 'parentId', 'treeRoot': 1}}
        this.treedialogVisible = true
      }, // 权限
      batchDelClk () {
        if (this.sel_all.length > 0) {
          this.$confirm('确定删除当前选中的所有信息吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let arrRowLis = this.sel_all
            var paramsArr = []
            for (var i in arrRowLis) {
              let params = {}
              params.rowId = arrRowLis[i]
              paramsArr.push(params)
            }
            console.log(paramsArr)
            api.requestJava('POST', '/role/deleteBatch.do', paramsArr, {})
              .then(request => {
                if (Number(request.data.code) === 200) {
                  this.$message({ type: 'success', message: '删除成功!' })
                  this.init()
                } else {
                  this.$notify.error({ title: '提示', message: request.data.message })
                  throw new Error(JSON.stringify(request))
                }
              })
          }).catch(() => {
            this.$message({ type: 'info', message: '已取消删除!' })
          })
        }
      },  // 批量删除
      onendChange (val) {
        var tmp = JSON.parse(val)
        if (Object.prototype.toString.call(tmp) === '[object Array]') {
          this.dataSource = tmp
        } else {
          this.dataSource = []
          this.dataSource.push(tmp)
        }
      }, // 过滤器修改事件
      confirmBack_base (msg) {
        if (msg) {
          if (msg.data.form.rowId === '') {
            this.queryExit()
          } else {
            this._upload_submit()
          }
        } else {
          this.clearObject()
        }
      },
      confirmBack_power_allot (msg) {
        api.requestJava('POST', BasePath.ROLE_USER_DELETE_BATCH, msg)
          .then(request => {
            if (Number(request.data.code) === 200) {
              api.requestJava('POST', BasePath.ROLE_USER_INSERT_BATCH, msg)
                .then(request => {
                  if (Number(request.data.code) === 200) {
                    this.$notify.success({ title: '提示', message: '保存成功' })
                  } else {
                    this.$notify.error({ title: '提示', message: request.data.message })
                    throw new Error(JSON.stringify(request))
                  }
                })
                .catch(err => {
                  let culprit = this.$route.name
                  log.work(err, culprit)
                })
            } else {
              this.$notify.error({ title: '提示', message: request.data.message })
              throw new Error(JSON.stringify(request))
            }
          })
          .catch(err => {
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      },
      queryExit () {
        let params = {}
        params.roleCode = this.dialogObj_base.data.form.roleCode
        api.requestJava('POST', BasePath.ROLE_SELECT, params)
          .then(request => {
            console.log(request.data.data.length)
            if (Number(request.data.code) === 200 && request.data.data.length <= 0) {
              this._upload_submit()
            } else {
              this.$notify.error({ title: '提示', message: '角色编号已被占用' })
              throw new Error(JSON.stringify(request))
            }
          })
          .catch(err => {
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      },
      _upload_submit () {
        let params = this.dialogObj_base.data.form
        params.createdBy = getUser().userID
        if (params.rowId === '') {
          api.requestJava('POST', BasePath.ROLE_INSERT, params)
            .then(request => {
              if (Number(request.data.code) === 200) {
                this.init()
              } else {
                this.$notify.error({ title: '提示', message: '新增错误' })
                throw new Error(JSON.stringify(request))
              }
            })
        } else {
          console.log(JSON.stringify(params))
          api.requestJava('POST', BasePath.ROLE_UPDATE, params)
            .then(request => {
              console.log(request.data.code)
              if (Number(request.data.code) === 200) {
                this.init()
              } else {
                this.$notify.error({ title: '提示', message: '更新错误' })
                throw new Error(JSON.stringify(request))
              }
            })
            .catch(err => {
              let culprit = this.$route.name
              log.work(err, culprit)
            })
        }
      },
      headerClick () {},
      sortChange (msg) {},
      rowClick (msg) {},
      sessionFailedBack (msg) {
        let headers = msg.data.form
        let array = [headers, this]
        this.$store.dispatch('login', array)
          .then((msg) => {
            if (msg === 'success') {
              this.sessionFailedDialogObj.dialogVisible = false
            }
          })
          .catch((err) => { console.log(err) })
      }, // 会话失效
      exportEve () {
        this.$refs.tableGrid.exportExcel()
      }, // 导出Elxc
      inputChange (val) {
        /** 搜索功能回调 **/
        let page = this.currentPage
        let size = this.pageSize
        this.dataSource = JSON.parse(val).filter((u, index) => index < size * page && index >= size * (page - 1))
      }
    },

    components: {
      tableVue,
      _BTN_FILTER,
      _POPUP,
      _TREEPOPUP,
      _TRANSFERPOP
    }
  }
</script>
