<template>
  <div class="layout-no-cols right-list-toolbar">
    <el-toolbar>
      <el-button @click="addClick" priv="Platform.User.Add">
        <i class="fa fa-plus"></i>新建
      </el-button>
      <!-- <el-dropdown @command="handleCommand">
        <el-button>
          <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="editClick" :disabled="selectedRows.length !== 1" priv="Platform.User.Edit">
            <i class="fa fa-edit" aria-hidden="true"></i>编辑
          </el-dropdown-item>
          <el-dropdown-item command="disableOrEnableClickHandler" :disabled="!(selectedRows.length === 1 && selectedRows[0].status)" priv="Platform.User.Disable">
            <i class="fa fa-ban" aria-hidden="true"></i>停用
          </el-dropdown-item>
          <el-dropdown-item command="disableOrEnableClickHandler" :disabled="!(selectedRows.length === 1 && !selectedRows[0].status)" priv="Platform.User.Enable">
            <i class="fa fa-check-circle" aria-hidden="true"></i>启用
          </el-dropdown-item>
          <el-dropdown-item command="deleteClickHandler"  :disabled="selectedRows.length === 0" @click="deleteClickHandler" priv="Platform.User.Delete">
            <i class="fa fa-remove" aria-hidden="true"></i>删除
          </el-dropdown-item>
          <el-dropdown-item command="modifyPasswordClick" :disabled="selectedRows.length !== 1" priv="Platform.User.ChangePassword">
            <i class="fa fa-key" aria-hidden="true"></i>修改密码
          </el-dropdown-item>
          <el-dropdown-item command="noticeClickHandler" :disabled="selectedRows.length === 0" priv="Platform.User.LastLoginUpdatePwd">
            <i class="fa fa-envelope" aria-hidden="true"></i>通知修改密码
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown> -->
    </el-toolbar>

    <div>
      <div class="tar">
        <el-row type="flex" class="row-bg" justify="end" v-if="!isComplexSearch">
          <el-col :span="6" >
            <el-input v-model="userNameSearch" placeholder="请输入用户名" @keyup.enter.native="searchClickHandlder"></el-input>
          </el-col>
          <el-col :span="4">
            <el-button-group>
              <el-button @click="searchClickHandlder" type="primary">
                <i class="fa fa-search"></i>搜索
              </el-button>
              <el-button @click="searchTypeChange">高级搜索 ...</el-button>
            </el-button-group>
          </el-col>
        </el-row>
        <template v-else>
          <el-row type="flex" class="row-bg" justify="space-around" align="middle">
            <el-col :span="7">
              <el-input v-model="userNameSearch" placeholder="请输入用户名" @keyup.enter.native="searchClickHandlder"></el-input>
            </el-col>
            <el-col :span="7">
              <el-input v-model="realNameSearch" placeholder="请输入真实姓名" @keyup.enter.native="searchClickHandlder"></el-input>
            </el-col>
            <el-col :span="7">
              <tree-select class="layout-select" clearable :value.sync="branchValue" :items="branches" :itemsOptions="treeItemsOptions"  placeholder="请选择所属机构" @click-change="searchClickHandlder">
              </tree-select>
            </el-col>
          </el-row>
          <div style="padding:3px"></div>
          <el-row type="flex" class="row-bg" justify="space-around">
            <el-col :span="7">
              <el-select class="layout-select" v-model="userStatus" placeholder="请选择用户状态" clearable @change="searchClickHandlder">
                <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-select class="layout-select" v-model="changePasswordType" placeholder="请选择密码变更时间" clearable @change="searchClickHandlder">
                <el-option v-for="item in optionsPasswordType" :key="item.key" :label="item.value" :value="item.key">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-button-group style="float:left">
                <el-button  type="primary" @click="searchClickHandlder">
                  <i class="fa fa-search"></i>高级搜索
                </el-button>
                <el-button @click="searchTypeChange">搜索 ...</el-button>
              </el-button-group>
            </el-col>
          </el-row>
        </template>
      </div>

      <el-table :data="users"  ref="userDataTable" tooltip-effect="dark" style="width: 100%;margin-top:10px;" @selection-change="onSelectionChange" :data-read-url="getUsersURL" :page-size="10">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column label="用户名" min-width="15%">
          <template slot-scope="scope">
            <a class="list-card-title" href="javascript:void(0)" @click.stop="editClick(scope.row)">
              {{scope.row.userName}}
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" min-width="15%"></el-table-column>
        <el-table-column label="用户状态" min-width="12%">
          <template slot-scope="scope">
            <i class="fa fa-check icon-success" v-if="scope.row.status"></i>
            <i class="fa fa-times icon-danger" v-else></i>
          </template>
        </el-table-column>
        <el-table-column label="所属机构" min-width="15%">
          <template slot-scope="scope">
            <span>{{scope.row.branch.name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属角色" min-width="18%" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-for="role in scope.row.roles" :key="role.roleCode">{{role.name}} </span>
          </template>
        </el-table-column>
        <el-table-column prop="lastModifyPassTime" label="最后修改密码时间" min-width="20%">
          <template slot-scope="scope">
            {{scope.row.lastModifyPassTime | fixDateTime}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right" width="170">
          <template slot-scope="scope">
            <el-button @click.stop="editClick(scope.row)" priv="Platform.User.Edit" type="text" title="编辑" class="table-operate-icon">
              <i class="fa fa-edit f16"></i>
            </el-button>
            <el-button v-if="scope.row.status" @click.stop="disableOrEnableClickHandler(scope.row)" priv="Platform.User.Disable" type="text" :title="scope.row.status?'停用':'启用'" class="table-operate-icon">
              <i class="fa fa-ban f16"></i>
            </el-button>
            <el-button v-else @click.stop="disableOrEnableClickHandler(scope.row)" priv="Platform.User.Enable" type="text" :title="scope.row.status?'停用':'启用'" class="table-operate-icon">
              <i class="fa fa-check-circle f16"></i>
            </el-button>
            <el-button @click.stop="deleteClickHandler(scope.row)" priv="Platform.User.Delete" type="text" title="删除" class="table-operate-icon">
              <i class="fa fa-remove f16"></i>
            </el-button>
            <el-button @click.stop="modifyPasswordClick(scope.row)" priv="Platform.User.ChangePassword" type="text" title="修改密码" class="table-operate-icon">
              <i class="fa fa-key f16"></i>
            </el-button>
            <el-button @click.stop="noticeClickHandler(scope.row)" priv="Platform.User.LastLoginUpdatePwd" type="text" title="通知修改密码" class="table-operate-icon">
              <i class="fa fa-envelope f16"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--修改密码框-->
    <el-dialog title="修改密码" :visible.sync="modifyPasswordModal" class="user-modify-password-dialog" @open="beforeChangePwdOpen">
      <el-form :model="tmpUser" :rules="userRules" ref="modifyPasswordForm" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input type="text" v-model="tmpUser.userName" :readonly="true" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="tmpUser.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="repeatPassword">
          <el-input type="password" v-model="tmpUser.repeatPassword" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="modifyPasswordModal = false">取 消</el-button>
        <el-button type="primary" @click="modifyPasswordHandler" :loading="handlerLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TreeSelect from '@src/components/TreeSelect.vue'
import util from '@src/common/util.js'
export default {
  components: {
    'tree-select': TreeSelect
  },
  filters: {
    fixDateTime: function(val) {
      if (!val) {
        return ''
      }
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      isComplexSearch: false,
      users: [],
      selectedRows: [],
      handlerLoading: false,
      modifyPasswordModal: false,
      passwordVeriry: {
        maxLen: 18,
        minLen: 5
      },
      branches: [],
      userStatus: '', // 用户状态
      changePasswordType: '', // 用户更改密码时间类型
      optionsPasswordType: [],
      userNameSearch: '',
      realNameSearch: '',
      branchValue: '',
      optionsStatus: [
        {
          value: 'Y',
          label: '启用'
        },
        {
          value: 'N',
          label: '停用'
        }
      ], // 查询会员状态
      treeItemsOptions: {
        children: 'children',
        label: 'name',
        key: 'branchInnerCode'
      },
      tmpUser: {userName: '', password: '', repeatPassword: ''},
      userRules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value.length < this.passwordVeriry.minLen || value.length > this.passwordVeriry.maxLen) {
                callback(new Error(`必须是${this.passwordVeriry.minLen}-${this.passwordVeriry.maxLen}位的字符`))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        repeatPassword: [
          { required: true, message: '请重复输入一次密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.tmpUser.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    disableOrEnable: function() {
      if (this.selectedRows.length !== 1) {
        return ''
      }
      return this.selectedRows[0].status ? '停用' : '启用'
    }
  },
  created() {
    this.changePasswordMethod() // 获取密码变更时间类型数据
    this.getBranches() // 机构数据
  },
  methods: {
    async initPwdCheck() {
      let res = await axios.get('/ui/users/initpwdcheck')
      if (res.data.status === 1) {
        this.passwordVeriry = {maxLen: res.data.maxLen, minLen: res.data.minLen}
      }
    },
    beforeChangePwdOpen() {
      this.initPwdCheck()
    },
    async getBranches() {
      let data = await axios.get('/ui/branches')
      this.branches = data.data.data
    },
    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },
    onSelectionChange(selection) {
      this.selectedRows = selection
    },
    async changePasswordMethod() {
      let data = await axios.get('/ui/users/changepasswordtype')
      this.optionsPasswordType = data.data.data
    },
    searchClickHandlder() {
      this.$refs.userDataTable.getData()
    },
    // 高级检索切换
    searchTypeChange() {
      this.userNameSearch = ''
      this.realNameSearch = ''
      this.userStatus = ''
      this.changePasswordType = ''
      this.isComplexSearch = !this.isComplexSearch
    },
    getUsersURL() {
      return [
        '/ui/users',
        {
          params: {
            userName: this.userNameSearch,
            realName: encodeURIComponent(this.realNameSearch),
            branchInnerCode: this.branchValue,
            status: this.userStatus,
            changePasswordType: this.changePasswordType
          }
        }
      ]
    },
    async addClick() {
      this.$router.push({path: '/platform/user/new'})
    },
    editClick(row) {
      if (!row || !row.userName) {
        return
      }
      this.$router.push({path: `/platform/user/${row.userName}`})
    },
    async deleteClickHandler(row) {
      let rowIds = []
      if (row && row.userName) {
        rowIds.push(row.userName)
      } else {
        this.selectedRows.forEach(function(row) {
          rowIds.push(row.userName)
        })
      }

      try {
        await this.$confirm('确定删除吗？删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete('/ui/users/' + rowIds.join(','))
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.$refs.userDataTable.getData()
        }
      } catch (e) {

      }
    },
    async noticeClickHandler(row) {
      let rowIds = []

      let rowUsers = []
      if (row && row.userName) {
        rowIds.push(row.userName) && rowUsers.push(row.userName)
      } else {
        this.selectedRows.forEach(function(row) {
          rowIds.push(row.userName)
          rowUsers.push(row.userName)
        })
      }

      try {
        await this.$confirm('这些用户：' + rowUsers.join('、') + '，下次登录时修改密码吗?', '确认通知', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let ids = rowIds.join(',')
      let res = await axios.post('/ui/message', {
        toUser: `${ids}`,
        subject: '密码长时间未修改通知',
        content: '您的密码由于长时间未修改，请您及时修改密码！'
      })
      util.showResponseMessage(res.data)
    },
    async disableOrEnableClickHandler(row) {
      let userName = row && row.userName ? row.userName : this.selectedRows[0].userName
      let status = row ? row.status : this.selectedRows[0].status
      let statusName = status ? '停用' : '启用'
      try {
        await this.$confirm('确定' + statusName + '这个用户吗？', '确认' + statusName, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let handle
      if (status) {
        handle = async () => {
          let res = await axios.put(`/ui/users/disable/${userName}`)
          return res.data
          // TODO: 请检查测试该处逻辑
        }
      } else {
        handle = async () => {
          let res = await axios.put(`/ui/users/enable/${userName}`)
          return res.data
          // TODO: 请检查测试该处逻辑
        }
      }
      let data = await handle(userName)
      util.showResponseMessage(data)
      if (data.status !== 1) {
        return
      }
      let index = this.users.findIndex(val => {
        return val.userName === userName
      })
      this.users[index].status = !this.users[index].status
    },
    modifyPasswordClick(row) {
      this.tmpUser.userName = row && row.userName ? row.userName : this.selectedRows[0].userName
      this.tmpUser.password = ''
      this.tmpUser.repeatPassword = ''

      this.modifyPasswordModal = true
    },
    async modifyPasswordHandler() {
      this.handlerLoading = true
      try {
        await util.validateForm(this.$refs['modifyPasswordForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        this.handlerLoading = false
        return
      }

      let res = await axios.put('/ui/users/password', {
        userName: this.tmpUser.userName,
        password: this.tmpUser.password
      })
      this.handlerLoading = false
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.modifyPasswordModal = false
      }
    }
  }
}
</script>

<style scoped>
.pane-btns {
  text-align: right;
}
.tree-class {
  width: 180px;
}
</style>
<style>
.user-modify-password-dialog .el-dialog {
  width:400px;
}
@media (max-width: 480px){
  .user-modify-password-dialog .el-dialog{
    width:96%;
  }
}
</style>
