<!--  -->
<template>
  <div>
    <main-top :crumb="crumbData"></main-top>
    <div class="table-interface">
      <div class="top-body">
        <div class="info-top">
          <div class="info-left">
            <span>按用户状态查看：</span>
            <el-select
              style="width: 90px"
              v-model="region"
              placeholder="请选择"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" :value="0"></el-option>
              <el-option label="停用" :value="1"></el-option>
            </el-select>
            <el-input
              style="width: 220px; margin: 0 20px"
              v-model="inputKey"
              placeholder="请输入关键字搜索"
            ></el-input>
            <el-button type="primary" @click="getInformation">查找</el-button>
            <el-button @click="inputKey = ''">重置</el-button>
          </div>
          <div class="info-right">
            <el-button type="primary" @click="show('', 'add')"
              >新增用户</el-button
            >
          </div>
        </div>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column
            v-for="(item, idx) in data"
            :key="idx"
            :prop="item.prop"
            :label="item.label"
          >
            <template slot-scope="scope">
              <img
                style="width: 80px; height: 80px; border-radius: 50%"
                v-if="item.prop === 'head'"
                :src="scope.row[item.prop]"
                alt
              />
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template
              slot-scope="scope"
              v-if="scope.row.roleName !== '超级管理员'"
            >
              <span class="o-span" @click="show(scope.row, 'edit')">修改</span>
              <span class="o-span" @click="changeState(scope.row)">{{
                scope.row.qiyong === "启用" ? "停用" : "启用"
              }}</span>
              <span class="o-span" @click="del(scope.row)">注销</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="e-pagination">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="size"
            layout="prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog :title="editTitle" :visible.sync="dialogFormVisible" width="40%">
      <div class="add-con">
        <div class="add-left">
          <el-form :model="form" :rules="rules" ref="form">
            <el-form-item
              required
              prop="userName"
              label="用户账号："
              :label-width="formLabelWidth"
            >
              <el-input
                :disabled="type === 'edit'"
                v-model="form.userName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              required
              label="用户角色："
              :label-width="formLabelWidth"
            >
              <el-select v-model="form.roleId" placeholder="请选择角色">
                <el-option
                  v-for="item in roleList"
                  :label="item.roleName"
                  :key="item.id"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              required
              label="手机号码："
              :label-width="formLabelWidth"
              prop="phone"
            >
              <el-input v-model="form.phone" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="是否启用：" :label-width="formLabelWidth">
              <el-radio-group v-model="form.state">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <div
              class="passTxt"
              v-show="type === 'add'"
              style="color: #f56c6c; padding: 0 0 0 40px"
            >
              初始密码：123456
            </div>
          </el-form>
        </div>
        <!-- <div class="add-right">
          <el-upload
            class="avatar-uploader"
            :action='uploadUrl'
            :headers="{
              token,
            }"
            :show-file-list="false"
            :on-success="upload_success"
            >
            <img v-if="form.head" :src="form.head" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="avatar-img">用户头像</div>
          <div class="avatar-img">
            <el-button v-if="type==='edit'" @click="reset">重置密码</el-button>
          </div>
        </div> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save">保 存</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

import MainTop from '@/components/main-top'
const crumbData = [
  {
    name: '用户管理',
    id: 6
  }
]
let juese = {
  0: '高级管理员',
  1: '普通管理员'
}

let zt = {
  0: '启用',
  1: '停用'
}

let urlType = {
  add: '/user/addUser',
  edit: '/user/updateUser'
}

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    MainTop
  },
  data () {
    // 这里存放数据
    let data = [
      {
        prop: 'idx',
        label: '序号'
      },
      {
        prop: 'userName',
        label: '账号'
      },
      {
        prop: 'roleName',
        label: '角色'
      },
      {
        prop: 'phone',
        label: '手机号'
      },
      {
        prop: 'qiyong',
        label: '状态'
      }
    ]

    return {
      crumbData,
      data,
      region: '',
      infoName: '',
      tableData: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        userName: '',
        roleId: 16,
        phone: '',
        head: '',
        password: '',
        repeatPassword: '',
        state: 0
      },
      total: 0,
      inputKey: '',
      currentPage: 1,
      size: 10,
      formLabelWidth: '120px',
      imageUrl: '',
      type: 'add',
      editTitle: '新增用户',
      uploadUrl: `${this.$serverName}/user/uploadHead`,
      token: window.localStorage.getItem('token'),
      roleList: [],
      rules: {
        userName: [
          { required: true, message: '用户账号不能为空' },
          { max: 20, message: '用户账号不能大于20个字符' }
        ],
        phone: [
          { required: true, message: '手机号不能为空' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }
        ]
      }
    }
  },
  watch: {
    currentPage () {
      this.refresh()
    },
    size () {
      this.refresh()
    },
    region () {
      this.refresh()
    },
    inputKey () {
      this.currentPage = 1
      this.refresh()
    },
    type (newVal) {
      this.editTitle = newVal === 'add' ? '新增用户' : '修改用户信息'
    }
  },
  mounted () {
    this.refresh()
    this.getRole()
  },
  methods: {
    reset () {
      let data = {
        id: this.form.id
      }
      this.$confirm('此操作将重置该用户密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.post('/user/resetPassword', data).then((res) => {
            if (res.code === 0) {
              this.$alert('重置成功', '提示', {
                confirmButtonText: '确定',
                callback: (action) => {}
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: res.msg,
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    goto (item) {
      window.localStorage.setItem('editInfo', JSON.stringify(item))
      this.$router.push({ name: 'edit-information', params: { type: 1 } })
      this.$bus.$emit('editinfo', item)
    },
    upload_success (data) {
      this.form.head = data.data
    },
    refresh () {
      this.loading = true
      this.getInformation()
      this.loading = false
    },
    handleCurrentChange (val) {
      this.currentPage = val
    },
    del (item) {
      let data = {
        id: item.id
      }
      this.$confirm('此操作将注销并删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.post('/user/deleteUser', data).then((res) => {
            if (res.code === 0) {
              this.$alert('注销成功', '提示', {
                confirmButtonText: '确定',
                callback: (action) => {
                  this.refresh()
                }
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: res.msg,
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    save () {
      this.$refs['form'].validate().then((res) => {
        let { userName, roleId, phone, head, state } = this.form
        let data = { userName, roleId, phone, head, state }

        this.$http
          .post(urlType[this.type], data)
          .then((res) => {
            if (res.code === 0) {
              this.$alert('操作成功', '提示', {
                confirmButtonText: '确定',
                callback: (action) => {
                  this.dialogFormVisible = false
                  this.refresh()
                }
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: res.message,
                duration: 2000
              })
            }
          })
          .catch(() => {
            this.$notify.error({
              title: '错误',
              message: '添加失败',
              duration: 2000
            })
          })
      })
    },

    show (item = '', type) {
      this.dialogFormVisible = true
      this.type = type
      this.form = {
        userName: '',
        roleId: 16,
        phone: '',
        head: '',
        password: '',
        repeatPassword: '',
        state: 0
      }

      if (type === 'edit') {
        this.form = item
      }
    },
    changeState (item) {
      let state = item.state === 1 ? 0 : 1
      let data = {
        id: item.id,
        state
      }

      this.$confirm('此操作将导致用户状态发生改变, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.post('/user/updateState', data).then((res) => {
            if (res.code === 0) {
              this.$alert('修改成功', '提示', {
                confirmButtonText: '确定',
                callback: (action) => {
                  this.refresh()
                }
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: res.msg,
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    async getInformation () {
      let params = {
        state: this.region,
        searchKey: this.inputKey,
        pageNum: this.currentPage,
        pageSize: this.size
      }

      let result = await this.$http({
        method: 'post',
        data: params,
        url: '/user/list'
      })

      if (result.code !== 0) {
        return
      }
      this.tableData = result.data.list
      this.total = result.data.total
      this.tableData.forEach((item, i) => {
        item['date'] =
          this.$base.timestampToTime(item['startTime']) +
          '至' +
          this.$base.timestampToTime(item['endTime'])
        item['role'] = juese[item['roleId']]
        item['qiyong'] = zt[item['state']]
        item['idx'] = i + 1 + (this.currentPage - 1) * this.size
      })
    },
    // 获取角色列表
    async getRole () {
      let res = await this.$http({
        method: 'post',
        data: {
          state: 1
        },
        url: '/user/roleList'
      })
      this.roleList = res.data.filter((item) => item.roleName !== '超级管理员')
    },
    handleSearchBtnClick () {
      this.params.pageNum = 1
      // this.getLogs()
    }
  }
}
</script>

<style scoped>
/* 引入公共css类 */
@import url(./style);
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
