<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-control">
        <span style="width: auto;">姓名:</span>
        <el-input v-model="listQuery.accountName" placeholder="请输入机构名称" clearable @keyup.enter.native="getList" @clear="getList" />
      </div>
      <div class="filter-control">
        <span style="width: auto;">手机号:</span>
        <el-input v-model="listQuery.account" placeholder="请输入手机号" clearable @keyup.enter.native="getList" @clear="getList" />
      </div>
      <div class="filter-control">
        <span style="width: auto;">状态:</span>
        <el-select v-model="listQuery.status" style="width:120px;" clearable @change="getList">
          <el-option value="" label="全部" />
          <el-option label="已上线" :value="1" />
          <el-option label="已下线" :value="2" />
        </el-select>
      </div>
      <div class="filter-control">
        <span>添加时间:</span>
        <el-date-picker
          v-model="registTime"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="getList"
        />
      </div>
      <div class="filter-control">
        <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd(1)">添加用户</el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <el-table-column label="姓名" align="center" prop="accountName" />
      <el-table-column label="手机号" align="center" prop="account" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="{row}">
          <el-tag v-if="row.status===2" type="danger" size="small">已下线</el-tag>
          <el-tag v-else type="success" size="small">已上线</el-tag>
          <el-button v-if="row.status === 2" type="primary" size="mini" @click="handOnline(row)">上线</el-button>
          <el-button v-else type="primary" size="mini" @click="handOffline(row)">下线</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="添加时间" prop="newAddTime">
        <template slot-scope="{row}">
          <span>{{ row.newAddTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleAdd(2,row)">编辑</el-button>
          <el-button type="warning" size="mini" @click="hanleVerify(row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>20" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <el-dialog title="重置密码" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :rules="rules" :model="repeatFrom" label-position="right" label-width="120px">
        <el-form-item label="新密码:" prop="password">
          <el-input v-model="repeatFrom.password" placeholder="请输入8-16位数字和字母的组合" maxlength="50" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="确认密码:" prop="oldPassword">
          <el-input v-model="repeatFrom.oldPassword" placeholder="请输入8-16位数字和字母的组合" maxlength="50" style="width: 250px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRepeatPassword">确定</el-button>
      </div>
    </el-dialog>
    <template>
      <el-backtop style="right: 40px; bottom: 40px;">
        <i class="el-icon-upload2" />
      </el-backtop>
    </template>
  </div>
</template>

<script>
import { getUserList, updateUser, repeatPassword } from '@/api/sys'
import pickerOptions from '@/utils/time-picker.js'
export default {
  data() {
    const picValidator = (rule, value, callback) => {
      if (!this.repeatFrom.oldPassword) {
        callback(new Error('请再次确认密码'))
      } else if (this.repeatFrom.oldPassword !== this.repeatFrom.password) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    }
    return {
      registTime: '',
      pickerOptions,
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        organizeId: this.$store.getters.organizeId,
        account: '',
        status: '',
        accountName: '',
        startTime: '',
        endTime: ''
      },
      startTime: '',
      endTime: '',
      repeatFrom: {
        password: '',
        oldPassword: '',
        id: ''
      },
      updateTemp: {},
      updateTatusType: '',
      dialogVisible: false,
      dialogVisibleText: '',
      dialogFormVisible: false,
      dialogStatus: '',
      loadingbut: false,
      rules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, max: 16, message: '密码长度在8到16个字符', trigger: 'blur' },
          {
            required: true,
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/,
            message: '密码组合应为8-16位数字和字母组合',
            trigger: 'blur'
          }
        ],
        oldPassword: [{ required: true, validator: picValidator, trigger: 'blur' }]
      }
    }
  },
  computed: {
    disabled() {
      return !this.addPeople.status
    },
    organizeId() {
      return this.$store.getters.organizeId
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 初始化获取时间筛选值
    initTime() {
      if (this.registTime && this.registTime.length > 0) {
        this.listQuery.startTime = this.registTime[0]
        this.listQuery.endTime = this.registTime[1]
      } else {
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
    },
    // 获取列表
    async getList() {
      this.listLoading = true
      try {
        this.initTime()
        const res = await getUserList(this.listQuery)
        this.list = res.data.results
        this.total = res.data.totalRecord
        this.listLoading = false
      } catch (error) {
        console.log('error', error)
        this.listLoading = false
      }
    },
    // 重置密码
    hanleVerify(row) {
      this.repeatFrom.id = row.id
      this.dialogFormVisible = true
    },
    // 确认重置密码
    handleRepeatPassword() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.repeatPassword(this.repeatFrom)
        } else {
          return false
        }
      })
    },
    // 接口
    async repeatPassword(params) {
      try {
        const res = await repeatPassword(params)
        this.$message.success(res.msg)
        this.getList()
        this.dialogFormVisible = false
      } catch (error) {
        console.log('error', error)
      }
    },
    // 上线用户
    handOnline(row) {
      this.$confirm('确定上线该用户吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = { status: 1, id: row.id }
        this.updateUser(params)
      }).catch(() => {
      })
    },
    // 下线用户
    handOffline(row) {
      this.$confirm('确定下线该用户吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = { status: 2, id: row.id }
        this.updateUser(params)
      }).catch(() => {
      })
    },
    // 上下线接口
    async updateUser(params) {
      try {
        const res = await updateUser(params)
        this.$message.success(res.msg)
        this.getList()
      } catch (error) {
        this.$message.error(error.msg)
      }
    },
    // 跳转添加编辑页
    handleAdd(type, row) {
      if (type === 1) {
        this.$router.push({ path: '/sys/edit' })
      } else {
        this.$router.push({ path: '/sys/edit', query: { type: 'edit', id: row.id }})
      }
    }
  }
}

</script>
<style scoped>
  .el-dialog{
    width: 600px;
  }
</style>
