<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-item">

        <account-input v-model="listQuery.userId" :sys-origin="listQuery.sysOrigin" placeholder="用户ID" />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>
    <el-alert
      title="提示"
      type="warning"
      :closable="false"
    >
      使用站内注册账号关联后台PC端IM登录授权，登录账号 “短id” 初始密码 “88888888”
    </el-alert>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column label="头像" align="center" width="150">
        <template slot-scope="scope">
          <div v-if="scope.row.userBaseInfo">
            <avatar :url="scope.row.userBaseInfo.userAvatar" :gender="scope.row.userBaseInfo.userSex" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.userBaseInfo"
            style="width:100%;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
          >
            <el-link @click="queryUserDetails(scope.row)"><a :title="scope.row.userBaseInfo.userNickname"> {{ scope.row.userBaseInfo.userNickname }} </a></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="IM用户名" width="110" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.userBaseInfo">
            <div
              style="width:100%;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
            >
              <gender :gender="scope.row.userBaseInfo.userSex" :gender-name="scope.row.userBaseInfo.userSexName" :desc="scope.row.userBaseInfo.account" />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="text" size="small" @click="handleRestPwd(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <el-dialog
      v-loading="submitLoading"
      title="添加"
      width="400px"
      :visible.sync="dialogFormVisible"
      :modal-append-to-body="true"
      :append-to-body="true"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="formData"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="formData.userId"
            v-number
            placeholder="请输入用户ID"
          />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入登录密码"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="addSubmit()"
        >
          提交
        </el-button>
      </div>
    </el-dialog>
    <user-deatils-drawer
      v-if="userDeatilsDrawer"
      :user-id="thatSelectedUserId"
      @close="userDeatilsDrawer=false"
    />

  </div>
</template>

<script>
import { pageSysImAccount, addSysImAccount, resetSysImAccountPassword, delSysImAccountPassword } from '@/api/im-account'
import Pagination from '@/components/Pagination'
import Gender from '@/components/data/Gender'
import Avatar from '@/components/data/Avatar'

export default {
  name: 'UserManager',
  components: { Pagination, Gender, Avatar },
  filters: {
    joinRolesFilter(roles) {
      if (!roles || roles.length <= 0) {
        return ''
      }
      return roles.map(role => role.roleName).join(',')
    },
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      searchDisabled: false,
      thatSelectedUserId: '',
      userDeatilsDrawer: false,
      dialogFormVisible: false,
      submitLoading: false,
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        userId: ''
      },
      listLoading: true,
      formData: {
        userId: '',
        password: '88888888'
      },
      rules: {
        userId: [{ required: true, message: '必填参数不可为空', trigger: 'blur' }],
        password: [{ required: true, message: '必填参数不可为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.renderData()
  },
  methods: {
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.listQuery.cursor = 1
        that.list = []
      }
      that.listLoading = true
      pageSysImAccount(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
    },
    handleCreate() {
      const that = this
      that.dialogFormVisible = true
    },
    handleDelete(row) {
      const that = this
      that.$confirm(`是否确认删除 "${row.userBaseInfo.userNickname}" ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delSysImAccountPassword({ userId: row.userBaseInfo.id }).then(res => {
          that.$opsMessage.success()
          that.renderData()
        })
      }).catch(() => {})
    },
    handleSearch() {
      this.renderData(true)
    },
    handleRestPwd(row) {
      const that = this
      that.$confirm(`是否确认重置 "${row.userBaseInfo.userNickname}" 登陆密码?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetSysImAccountPassword(row.userBaseInfo.id).then(res => {
          that.$opsMessage.success()
        })
      }).catch(() => {})
    },
    addSubmit() {
      const that = this
      that.$refs.dataForm.validate(valid => {
        if (!valid) {
          console.error('submit fial!')
          return false
        }
        that.submitLoading = true
        addSysImAccount(that.formData).then(res => {
          that.submitLoading = false
          that.handleClose()
          that.$opsMessage.success()
          that.renderData()
        }).catch(er => { that.submitLoading = false })
      })
    },
    handleClose() {
      this.formData.userId = ''
      this.formData.password = '88888888'
      this.dialogFormVisible = false
    },
    queryUserDetails(row) {
      this.thatSelectedUserId = row.userId
      this.userDeatilsDrawer = true
    }
  }
}
</script>
