<template>
  <div class="subPage">
    <div class="system-table-search">
      <div class="flex-h">
        <div class="flex-item flex-h">
          <el-button size="mini" type="success" @click="addUser">新增用户</el-button>
        </div>
        <ul>
          <li>
            <!-- <span>选择案场：</span> -->
            <el-select v-model="CaseId" placeholder="请选择">
              <el-option
                key=""
                label="所有案场"
                value="">
              </el-option>
              <el-option
                v-for="item in cases"
                :key="item.CaseId"
                :label="item.CaseName"
                :value="item.CaseId">
              </el-option>
            </el-select>
          </li>
          <li>
            <el-select v-model="usertype" placeholder="请选择用户类型">
              <el-option
                key=""
                label=""
                value=""
              >
              </el-option>
              <el-option
                v-for="item in typeList"
                :key="item.TypeId"
                :label="item.TypeName"
                :value="item.TypeId">
              </el-option>
            </el-select>
          </li>
          <li>
            <el-input
              placeholder="请输入用户名"
              v-model="name"
            >
            </el-input>
          </li>
        </ul>
        <el-button
          size="mini"
          type="primary" @click="search">搜索</el-button>
      </div>
      <div class="moreFilter"></div>
    </div>
    <div class="system-table-box">
      <el-table
        :data="currentList"
        stripe
        style="width: 100%">
        <el-table-column
          fixed
          prop="UserName"
          label="用户名"
          width="150">
        </el-table-column>
        <el-table-column
          prop="RealName"
          label="真实姓名"
          width="120">
        </el-table-column>
        <el-table-column
          prop="Email"
          label="邮箱"
          width="150">
        </el-table-column>
        <el-table-column
          prop="WorkNo"
          label="工号"
          width="150">
        </el-table-column>
        <el-table-column
          prop="Phone"
          label="手机号"
          width="200">
        </el-table-column>
        <el-table-column
          prop="UserTypeNames"
          label="用户类型"
          width="100">
        </el-table-column>
        <el-table-column
          prop="CreateDate"
          label="创建时间"
          width="200">
        </el-table-column>
        <el-table-column label="操作" fixed='right' width="350">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button
            size="mini"
            type="success"
            @click="handleBind(scope.$index, scope.row)">绑定角色</el-button>
            <el-button
            size="mini"
            type="primary"
            @click="resetPasswd(scope.$index, scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page.sync="postData.page"
      :page-size="postData.pagesize"
      layout="prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog v-if="currentEditItem != null" :title="'绑定角色 - ' + currentEditItem.UserName" :visible.sync="dialogTableVisible">
      <form class="mainForm">
        <ul>
          <li class="flex-h">
            <span>输入搜索：</span>
            <div class="flex-item">
              <div>
                <el-input
                  placeholder="请输入角色名称并按回车搜索"
                  v-model="postData.name"
                  @change='getRole'
                  clearable>
                </el-input>
              </div>
            </div>
          </li>
          <li class="flex-h">
            <span>搜索结果：</span>
            <div class="flex-item">
              <div>
                <el-button
                  v-for="tag in searchTagList"
                  :key="tag.RoleId"
                  style="margin-right:1rem"
                  @click='addTag(tag)'>
                  {{tag.RoleName}}
                  </el-button>
              </div>
            </div>
          </li>
          <li class="flex-h">
            <span>当前角色：</span>
            <div class="flex-item">
              <div>
                <el-tag
                  v-for="tag in tags"
                  :key="tag.RoleId"
                  style="margin-right:1rem"
                  @close="handleClose(tag)"
                  closable>
                  {{tag.RoleName}}
                </el-tag>
              </div>
            </div>
          </li>
          <li style="text-align:right;">
            <el-button
              size="mini"
              type="success" @click="bindRoles">确认绑定</el-button>
          </li>
        </ul>
      </form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: '',
  data () {
    return {
      name: '',
      usertype: '',
      typeList: [],
      currentEditItem: null,
      dialogTableVisible: false,
      total: 0,
      postData: { // 表格搜索条件
        caseid: '',
        name: '', // 搜索关键词
        page: 1, // 当前页码
        pagesize: 10, // 请求数据量
      },
      currentList: [],
      searchTagList: [],
      tags: [],
    }
  },
  computed: {
    ...mapState({
      cases: x => x.app.cases.list,
      defaultCaseId: x => x.app.cases.default
    }),
    CaseId: {
      get () {
        return this.postData.caseid || this.defaultCaseId
      },
      set (val) {
        this.postData.caseid = val
      }
    }
  },
  mounted () {
    this.$nextTick(function () {
      this.getUserTypeList()
      this.getList()
    })
  },
  methods: {
    getUserTypeList () { // 获取用户类型
      this.$ajax(this.$api.caseManager.getUserTypeList.url, {
        method: this.$api.caseManager.getUserTypeList.method,
      }).then(res => {
        this.typeList = res
      })
    },
    resetPasswd (index, row) { // 重置密码
      this.$confirm('确认重置此用户密码为：123456?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$ajax(this.$api.systemSet.resetPassword.url, {
          method: this.$api.systemSet.resetPassword.method,
          data: {userid: row.UserId}
        }).then(res => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消重置'
        })
      })
    },
    bindRoles () { // 绑定角色
      const roleids = this.returnRoles()
      if (roleids === '') {
        this.$message({
          type: 'error',
          message: '请先选择角色！'
        })
        return false
      }
      this.$ajax(this.$api.systemSet.bindRoles.url, {
        method: this.$api.systemSet.bindRoles.method,
        queryData: {
          userid: this.currentEditItem.UserId,
          roles: roleids
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.dialogTableVisible = false
        this.postData.name = ''
        this.tags = []
        this.searchTagList = []
      })
    },
    returnRoles () {
      var arr = []
      for (var n = 0; n < this.tags.length; n++) {
        arr.push(this.tags[n].RoleId)
      }
      return arr.join(',')
    },
    search () { // 搜索
      this.postData.page = 1
      this.currentList = []
      this.getList()
    },
    getList () { // 获取列表
      this.$ajax(this.$api.systemSet.getUserList.url, {
        method: this.$api.systemSet.getUserList.method,
        queryData: { ...this.postData, caseid: this.CaseId, typeid: this.usertype, username: this.name }
      }).then(res => {
        for (var n = 0; n < (res.list || []).length; n++) {
          res.list[n].CreateDate = this.returnTime(res.list[n].CreateDate)
        }
        this.currentList = res.list
        this.postData.page = res.page
        this.total = res.pagenum
      })
    },
    returnTime (val) {
      val = new Date(val)
      return val.getFullYear() + '-' + this.returnNum(val.getMonth() + 1) + '-' + this.returnNum(val.getDate()) + ' ' + this.returnNum(val.getHours()) + ':' + this.returnNum(val.getMinutes()) + ':' + this.returnNum(val.getSeconds())
    },
    returnNum (num) {
      return num > 9 ? num : '0' + num
    },
    handleCurrentChange (val) { // 跳转到分页
      this.getList()
    },
    handleEdit (index, row) { // 编辑
      this.$router.push({ name: 'editUser', query: { id: row.UserId } })
    },
    handleDelete (index, row) { // 删除
      this.$confirm('确认删除此用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$ajax(this.$api.systemSet.deleteUser.url, {
          method: this.$api.systemSet.deleteUser.method,
          urlData: { id: row.UserId }
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleBind (index, row) {
      this.$ajax(this.$api.systemSet.getUserRoles.url, {
        method: this.$api.systemSet.getUserRoles.method,
        queryData: { userid: row.UserId }
      }).then(res => {
        if (res !== null) this.tags = res
        this.currentEditItem = row
        this.getRole()
        this.dialogTableVisible = true
      })
    },
    addUser () {
      this.$router.push({ name: 'addUser' })
    },
    handleClose (tag) {
      this.tags.splice(this.tags.indexOf(tag), 1)
    },
    addTag (tag) { // 调用添加绑定角色接口
      if (!this.tags.filter(x => x.RoleId === tag.RoleId)[0]) {
        this.tags.push({
          RoleId: tag.RoleId,
          RoleName: tag.RoleName
        })
      }
    },
    getRole () { // 绑定角色搜索事件，发送请求搜索角色列表
      this.$ajax(this.$api.caseManager.getRolesList.url, {
        method: this.$api.caseManager.getRolesList.method,
        queryData: this.postData
      }).then(res => {
        this.searchTagList = res.list
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
</style>
