<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.userName"
        placeholder="用户名"
        style="width: 200px"
        class="filter-item"
        :maxlength="30"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.loginName"
        placeholder="用户昵称"
        style="width: 200px"
        class="filter-item ml-20"
        :maxlength="30"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.phone"
        placeholder="手机号"
        style="width: 200px"
        class="filter-item ml-20"
        :maxlength="11"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        style="margin-left: 40px"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-plus" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :max-height="tableHeight"
    >
      <el-table-column label="序号" align="center" width="80" type="index">
        <template scope="scope">
          <span>{{ (listQuery.pageNum - 1) * 10 + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="40px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.userName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column key="nickName" label="登录名" prop="loginName" min-width="40px" align="center" />
      <el-table-column key="phone" label="手机号码" align="center" prop="phone" :show-overflow-tooltip="true" />
      <el-table-column prop="delFlag" label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.delFlag === 0 ? 'primary' : 'danger'" disable-transitions>{{ scope.row.delFlag === 0 ?
            '在用' : '注销' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" plain icon="el-icon-edit" title="修改" @click="handleUpdate(row)" />
          <el-button
            v-if="row.status != 'deleted'"
            plain
            size="mini"
            type="danger"
            icon="el-icon-delete"
            title="删除"
            @click="handleDelete(row, $index)"
          />
          <el-button size="mini" type="warning" plain icon="el-icon-user" title="重置密码" @click="editPwd(row, $index)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="600px">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="80px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="temp.userName" placeholder="用户名" :maxlength="30" />
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="temp.loginName" placeholder="登录名" :maxlength="30" :disabled="dialogStatus === 'update'" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" placeholder="手机号" :maxlength="11" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'create'" label="密码" prop="password">
          <el-input v-model="temp.password" type="password" placeholder="请输入密码" show-password :maxlength="16" />
        </el-form-item>
        <el-form-item label="组织机构" prop="orgId">
          <treeselect v-model="temp.orgId" :options="orgOptions" :show-count="true" placeholder="请选择组织机构" />
        </el-form-item>
        <!-- <el-form-item label="组织机构" prop="orgId">
          <el-select v-model="temp.orgId" placeholder="请选择组织机构" class="filter-item" style="width: 100%">
            <el-option v-for="item in buildArr" :key="item.orgId" :label="item.orgId">{{item.name}}</el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="登录权限" prop="loginType">
          <el-checkbox-group v-model="loginType">
            <el-checkbox v-for="item in loginTypeArr" :key="item.value" :label="item.value">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="账号类型" prop="userType">
          <el-radio-group v-model="temp.userType">
            <el-radio v-for="item in userTypeArr" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色类型" prop="roleId">
          <el-select
            v-model="temp.roleId"
            class="filter-item"
            placeholder="请选择角色类型"
            style="width: 100%"
            @change="roleChange"
          >
            <el-option v-for="item in roleArr" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="accountStatus">
          <el-radio-group v-model="temp.accountStatus">
            <el-radio v-for="item in accountStatusArr" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 关闭 </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="dialogFormVisible2" width="600px">
      <el-form
        ref="dataForm2"
        :rules="rules2"
        :model="pwdForm"
        label-position="right"
        label-width="80px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="密码" prop="password">
          <el-input v-model="pwdForm.password" type="password" placeholder="请输入密码" show-password :maxlength="16" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false"> 关闭 </el-button>
        <el-button type="primary" @click="editPwdData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, addUser, getUserById, editUser, delUser, editPwd } from '@/api/user'
import { fetchOrgList, fetchRoleList,fetchBuildList } from '@/api/select'
import { validPhone, validPwd } from '@/utils/validate'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

const loginTypeArr = [
  {
    value: '1',
    name: 'app'
  },
  {
    value: '2',
    name: '大屏'
  },
  {
    value: '3',
    name: '后台'
  }
]
const userTypeArr = [
  {
    value: '0',
    name: '内部账号'
  },
  {
    value: '1',
    name: '外部账号'
  }
]
const accountStatusArr = [
  {
    value: '0',
    name: '正常'
  },
  {
    value: '1',
    name: '锁定'
  },
  {
    value: '2',
    name: '停用'
  }
]
export default {
  components: { Pagination, Treeselect },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      loginTypeArr: loginTypeArr,
      userTypeArr: userTypeArr,
      orgOptions: [],
      roleArr: [],
      buildArr: [],
      accountStatusArr: accountStatusArr,
      loginType: [],
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      tableHeight: 650,
      showReviewer: false,
      temp: {
        userId: null,
        userName: '',
        loginName: '',
        phone: '',
        password: '',
        orgId: null,
        loginType: null,
        userType: null,
        roleId: null,
        roleName: null,
        accountStatus: null
      },
      pwdForm: {
        userId: null,
        password: ''
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: '',
      downloadLoading: false,
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      rules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '登录名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: this.validatePhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 8, max: 16, message: '密码长度在8到16个字符', trigger: 'blur' },
          { validator: this.validatePwd, trigger: 'blur' }
        ],
        orgId: [
          { required: true, message: '请选择组织机构' }
        ],
        loginType: [
          { required: true, validator: this.validateLoginType, trigger: 'change' }
        ],
        userType: [
          { required: true, message: '请选择账号类型', trigger: 'change' }
        ],
        roleId: [
          { required: true, message: '请选择角色类型', trigger: 'change' }
        ],
        accountStatus: [
          { required: true, message: '请选择账号状态', trigger: 'change' }
        ]
      },
      rules2: {
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 8, max: 16, message: '密码长度在8到16个字符', trigger: 'blur' },
          { validator: this.validatePwd, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getOrgList()
    this.getRoleList()
    this.getBuildList()
  },
  methods: {
    validateLoginType(rule, value, callback) {
      if (this.loginType.length > 0) {
        callback()
      } else {
        callback(new Error('请至少选择一个登录权限'))
      }
    },
    validatePhone(rule, value, callback) {
      if (validPhone(value)) {
        callback()
      } else {
        callback(new Error('手机号格式不正确'))
      }
    },
    validatePwd(rule, value, callback) {
      if (validPwd(value)) {
        callback()
      } else {
        callback(new Error('密码规则为：至少一个字母，一个数字和一个特殊字符'))
      }
    },
    roleChange(roleId) {
      var obj = {}
      obj = this.roleArr.find(function(i) {
        return i.id === roleId
      })
      this.temp.roleName = obj.name
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then((response) => {
        this.list = response.rows
        this.total = response.total
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 500)
      })
    },
    getOrgList() {
      fetchOrgList().then((response) => {
        this.orgOptions = response.data
      })
    },
    getRoleList() {
      fetchRoleList().then((response) => {
        this.roleArr = response.data
      })
    },
    getBuildList() {
      fetchBuildList().then((response) => {
        this.buildArr = response.data
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleCreate() {
      this.loginType = this.loginType.slice(0, 0)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.temp.roleId = null
        this.$refs['dataForm'].resetFields()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          this.temp.loginType = this.loginType.toString()
          addUser(this.temp).then((response) => {
            this.dialogFormVisible = false
            this.$message({
              showClose: true,
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      getUserById({ userId: row.userId }).then((response) => {
        this.temp = Object.assign({}, response.data)
        this.loginType = response.data.loginType.split(',')
        this.temp.userType = response.data.userType + ''
        this.temp.accountStatus = response.data.accountStatus + ''
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.temp.roleId = null
        this.$refs['dataForm'].resetFields()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          this.temp.loginType = this.loginType.toString()
          editUser(this.temp).then((response) => {
            this.dialogFormVisible = false
            this.$message({
              showClose: true,
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm(`确定要删除该数据吗？`, {
        type: 'warning',
        title: '操作提示',
        beforeClose: async(action, instance, done) => {
          if (action === 'confirm') {
            delUser({ userId: row.userId }).then((response) => {
              done()
              this.$message({
                showClose: true,
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          } else {
            done()
          }
        }
      })
    },
    editPwd(row, index) {
      this.dialogFormVisible2 = true
      this.pwdForm.userId = row.userId
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    editPwdData() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          editPwd(this.pwdForm).then((response) => {
            this.dialogFormVisible2 = false
            this.$message({
              showClose: true,
              message: response.msg,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
