<template>
  <el-container style="height: 100%;position: absolute;width: 100%;">
    <el-col :span="16" style="height:100%;">
      <div style="color:#909399;">
        部门：
        <el-select v-model="query.depart_code" clearable placeholder="部门编码" style="width: 110px">
          <el-option
            v-for="item in dm_depart"
            :key="item.depart_code"
            :label="item.depart_name"
            :value="item.depart_code"
          />
        </el-select>
        姓名：
        <el-input v-model="query.yhms" placeholder="姓名" style="width: 110px" clearable />
        <el-button style="margin: 1px" type="primary" icon="el-icon-search">查询</el-button>
        <div style="float: right;">
          <el-button style="margin: 1px" type="success" @click="handleAddYhxx">增加</el-button>
          <el-button style="margin: 1px" type="warning" @click="handleUpdateYhxx">修改</el-button>
          <el-button style="margin: 1px" type="danger" @click="handleDeleteYhxx">删除</el-button>
          <el-button style="margin: 1px" @click="exportExcel">Excel</el-button>
        </div>
      </div>

      <el-table
        ref="yhxxTable"
        v-loading="isYhxxTableLoading"
        class="yhxxTable"
        :show-overflow-tooltip="true"
        :data="c_yhxxTableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
        height="calc(100% - 30px - 35px)"
        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"
        @current-change="handleYhxxCurrentChange"
        @header-click="showFilter"
      >
        <el-table-column sortable label="账号" property="yhdm" />
        <el-table-column sortable label="职号" property="ylzd2" />
        <el-table-column sortable label="姓名" property="yhms" />
        <el-table-column sortable label="IP地址" property="ipAddress" />
        <el-table-column sortable label="部门" width="100px">
          <template slot-scope="scope">
            {{ getDepartName(scope.row.bmbm) }}
          </template>
        </el-table-column>

        <el-table-column sortable label="审批权限" >
        <template slot-scope="scope">
          {{ getSpqx(scope.row.ylzd1) }}
        </template>
        </el-table-column>
<!--        <el-table-column sortable label="代码(复制到)" property="yhdm1"/>-->

<!--        <el-table-column sortable label="备注" property="remark" />-->
      </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_yhxxTableData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <el-dialog class="YhxxDialog" :title="dialogTitle" :visible.sync="dialogVisible" width="450px" center="">
        <el-row>
          <el-row>
            <span style="width: 110px;display:inline-block;">账号：</span>
            <el-input v-model="updateData.yhdm" placeholder="" style="width: 250px;" :disabled="inputDisabled"/>
          </el-row>
          <el-row>
            <span style="width: 110px;display:inline-block;">姓名：</span>
            <el-input v-model="updateData.yhms" placeholder="" style="width: 250px;" />
          </el-row>
          <el-row>
            <span style="width: 110px;display:inline-block;">部门：</span>
            <el-select v-model="updateData.bmbm" clearable placeholder="部门" style="width: 250px;">
              <el-option
                v-for="item in dm_depart"
                :key="item.depart_code"
                :label="item.depart_name"
                :value="item.depart_code"
              />
            </el-select>
          </el-row>
          <el-row v-show="!inputDisabled">
            <span style="width: 110px;display:inline-block;">密码：</span>
            <el-input  placeholder="默认无密码" style="width: 250px;" disabled="false"/>
          </el-row>
          <el-row>
            <span style="width: 110px;display:inline-block;">审批权限：</span>
            <el-select v-model="updateData.ylzd1" clearable placeholder="权限" style="width: 250px;">
              <el-option
                v-for="item in spqx"
                :key="item.bm"
                :label="item.bmsm"
                :value="item.bm"
              />
            </el-select>
          </el-row>
          <el-row>
            <span style="width: 110px;display:inline-block;">职号：</span>
            <el-input v-model="updateData.ylzd2" placeholder="" style="width: 250px;" />
          </el-row>
          <el-row>
            <span style="width: 110px;display:inline-block;">IP地址：</span>
            <el-input v-model="updateData.ipAddress" placeholder="" style="width: 250px;" />
          </el-row>
          <el-row>
            <el-button
              v-if="dialogTitle =='添加用户信息'?true :false"
              style="float: right;"
              type="primary"
              @click="handleAddYhxxComplated"
            >添加
            </el-button>
            <el-button
              v-if="dialogTitle =='修改用户信息'?true :false"
              style="float: right;"
              type="primary"
              @click="handleUpdateYhxxComplated"
            >修改
            </el-button>
          </el-row>
        </el-row>
      </el-dialog>

    </el-col>
    <el-col :span="8" style="border-left:1px solid rgb(230, 230, 230);" :height="defaultHeight.height">
      <el-tabs v-model="activeGzzxxTabName" style="padding-left: 5px;" :height="defaultHeight.height">
        <el-tab-pane label="角色信息" name="gzzxx">
          <el-table
            ref="gzzTable"
            v-loading="isGzzTableLoading"
            :show-overflow-tooltip="true"
            :data="gzzTableData"
            :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="isselect" style="width: 30px;">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.isselect" @change="handleGzzSelect(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="代码" property="role_code" />
            <el-table-column label="名称" property="role_name" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-col>
    <tbfilter ref="tbFilter" :list="c_yhxxTableData" :filter="columnFilter" @execFilter="execFilter" />
  </el-container>

</template>

<script>
import {
  getUserList,
  addUser,
  deleteUser,
  updateUser,
  getDepartList,
  getRoleList,
  getRoleListByUser,
  addRoleForUser,
  deleteRoleForUser
} from '@/api/sy/yhgl'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import tbfilter from '@/components/TableColumnFilter'

export default {
  name: 'Yhgl',
  components: { tbfilter },
  data() {
    return {
      defaultHeight: {
        height: ''
      },
      inputDisabled:true,
      activeGzzxxTabName: 'gzzxx',
      dm_depart: [],
      spqx: [],
      query: { depart_code: ''},
      yhxxTableData: [],
      isYhxxTableLoading: true,

      gzzTableData: [],
      isGzzTableLoading: true,
      currentPage: 1,
      pageSize: 100,
      selectYhxx: {},
      dialogVisible: false,
      dialogTitle: '',
      updateData: {},
      columnFilter: {},
      loginType:[{
        value: 1,
        label: '指纹登录'
      }, {
        value: 2,
        label: 'findTxTl'
      }, ],
    }
  },
  computed: {
    c_yhxxTableData: function() {
      const search = this.query
      let resultList = this.yhxxTableData
      if (search && search.depart_code) {
        resultList = this.yhxxTableData.filter(data => {
          return data.bmbm === search.depart_code
        })
      }
      if (search && search.yhms) {
        resultList = resultList.filter(data => {
          return Object.keys(data).some(key => {
            return String(data[key]).indexOf(search.yhms) > -1
          })
        })
      }
      if (this.$refs.tbFilter) {
        return this.$refs.tbFilter.doFilter(this.columnFilter, resultList)
      }
      return resultList
    }
  },
  created() {
    window.addEventListener('resize', this.getHeight)
    this.getHeight()
    getDepartList({}).then(response => {
      this.dm_depart = response.data
      getUserList({}).then(response => {
        this.yhxxTableData = response.data
        this.isYhxxTableLoading = false
        this.$refs.yhxxTable.setCurrentRow(this.yhxxTableData[0])
      })
      getRoleList().then(response => {
        this.gzzTableData = response.data
        this.isGzzTableLoading = false
      })
    const dict= window.localStorage.getItem("SPQX");
     this.spqx=JSON.parse(dict);
    })
  }, methods: {
    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'
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleYhxxCurrentChange(currentRow) {

      if (!currentRow || !currentRow.yhdm) return
      this.selectYhxx = currentRow
      this.isGzzTableLoading = true
      getRoleListByUser(this.selectYhxx).then(response => {
        this.isGzzTableLoading = false
        for (const j in this.gzzTableData) {
          this.$set(this.gzzTableData[j], 'isselect', false)
        }
        for (const i in response.data) {
          for (const j in this.gzzTableData) {
            if (response.data[i].role_code === this.gzzTableData[j].role_code) {
              this.$set(this.gzzTableData[j], 'isselect', true)
            }
          }
        }
      })
    },
    handleGzzSelect(row) {
      if (!this.selectYhxx || !this.selectYhxx.yhdm) {
        this.$message({ message: '请先选择一个用户！', type: 'error' })
        return
      }
      const relation = { 'yhdm': this.selectYhxx.yhdm,
        'role_code': row.role_code,
        'yhms': this.selectYhxx.yhms
      }
      if (row.isselect) {
        addRoleForUser([relation]).then(response => {
          this.$message({ message: '添加角色成功！', type: 'success' })
        })
      } else {
        deleteRoleForUser([relation]).then(response => {
          this.$message({ message: '删除角色成功！', type: 'success' })
        })
      }
    },
    handleAddYhxx() {
      this.dialogVisible = true
      this.inputDisabled=false;
      this.dialogTitle = '添加用户信息'
      this.updateData = {}

    },
    handleAddYhxxComplated() {
      if(this.updateData.login_type===1) {


        var uuid = guid();
        window.location.href = "zwlr://" + uuid;
        console.log(uuid);
        this.updateData.uuid = uuid;
      }
      addUser(this.updateData).then(response => {
        this.updateData = JSON.parse(JSON.stringify(this.updateData))
        this.yhxxTableData.push(this.updateData)
        this.dialogVisible = false
        this.$message({ message: '添加用户信息成功！', type: 'success' })
      })
    },
    handleUpdateYhxx() {
      if (!this.selectYhxx.yhdm) {
        this.$message({ message: '请选择要修改的用户！', type: 'error' })
        return
      }
      this.dialogVisible = true
      this.dialogTitle = '修改用户信息'
      console.log(this.selectYhxx)
      this.updateData = JSON.parse(JSON.stringify(this.selectYhxx))
      this.inputDisabled=true;
    },
    handleUpdateYhxxComplated() {
      updateUser(this.updateData).then(response => {
        for (const key in this.updateData) {
          this.selectYhxx[key] = this.updateData[key]
        }
        this.dialogVisible = false
        this.$message({ message: '修改用户信息成功！', type: 'success' })
      })
    },
    handleDeleteYhxx() {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(this.selectYhxx).then(response => {
          this.yhxxTableData = this.yhxxTableData.filter(t => !(t.user_code === this.selectYhxx.user_code))
          this.$message({ message: '删除用户信息成功！', type: 'success' })
        })
      })
    },
    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 ''
    },
    getSpqx(depart_code) {
      for (const i in this.spqx) {
        if (this.spqx[i].bm === depart_code) {
          return this.spqx[i].bmsm
        }
      }
      return ''
    },
    exportExcel() {
      /* generate workbook object from table */
      // 表名
      var wb = XLSX.utils.table_to_book(document.querySelector('.yhxxTable'))
      /* 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' }), 'yhxx.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    }
  }
}
//用于生成uuid
function S4() {
  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
  return ("user-"+S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
function updateGuid() {
  return ("upda1-"+S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
function updateGuid1() {
  return ("upda2-"+S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
function updateGuid2() {
  return ("upda3-"+S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
</script>

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