<template>
  <div id="main" class="h-all">
    <el-container class="h-all">
      <el-header height="auto">
        <!-- 条件筛选工具栏 -->
        <div class="header-button-box">
          <el-button v-if="createCommand.visible" size='mini' icon="el-icon-circle-plus-outline" type="primary"
                     @click="createUser">{{$t("common.createBtn")}}</el-button>
          <el-button v-if="deleteUserCommand.visible" size='mini' icon="el-icon-delete" type="danger"
                     @click="deleteUser">{{$t("common.deleteBtn")}}</el-button>
<!--          <el-button v-if="updateUserCommand.visible" size='mini' icon="el-icon-edit" type="primary"-->
<!--                     @click="updateUser">{{$t("common.updateBtn")}}</el-button>-->
<!--          <el-button size='mini' icon="el-icon-refresh" type="primary"-->
<!--                     @click="resetUserPassword">{{$t("Security.resetPassword")}}</el-button>-->
        </div>
        <div class="header-search">
          <div class="search-input-box">
            <label>{{$t("Security.userName")+'：'}}</label>
            <!--<el-select v-model="selectedUserKey" size="mini" :placeholder="$t('common.selectOption')" :clearable="true">-->
              <!--<el-option-->
                <!--v-for="item in userCollection"-->
                <!--:key="item.userKey"-->
                <!--:label="item.userName"-->
                <!--:value="item.userKey">-->
              <!--</el-option>-->
            <!--</el-select>-->
            <el-input size = 'mini' :placeholder="$t('common.placeholder')"  v-model="selectedUserKey" clearable></el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t("Security.userGroup")+'：'}}</label>
            <el-select v-model="selectedUserGroup" size="mini"
                       :placeholder="$t('common.selectOption')"
                       @visible-change="getAllUserGroupsChange"
                       :clearable="true">
              <el-option
                v-for="item in userGroupList"
                :key="item.usergroupKey"
                :label="item.usergroupName"
                :value="item.usergroupKey">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <label>{{$t("Security.userStatus")+'：'}}</label>
            <el-select v-model="selectedLockFlag" size="mini" :placeholder="$t('common.selectOption')" :clearable="true">
              <el-option
                v-for="item in userLockFlag"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <el-button size='mini' icon="el-icon-search" type="primary"
                     @click="queryUser">{{$t("common.queryBtn")}}</el-button>
        </div>
      </el-header>
      <!-- table数据表格 -->
      <el-main class="adapt-height-box">
        <el-table
          :empty-text="$t('common.noData')"
          ref="multipleTable"
          :data="userList"
          header-row-class-name="table-header"
          cell-class-name="table-cell"
          class="adapt-height"
          height="auto"
          border
          stripe
          tooltip-effect="dark"
          :highlight-current-row="true"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            :selectable='checkboxDisabled'
            width="28">
          </el-table-column>
          <el-table-column
            type="index"
            v-if="false"
            :label="$t('Performance.index')"
            width="50">
          </el-table-column>
          <el-table-column
            prop="userName"
            :label="$t('Security.userName')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="usergroupKey"
            :label="$t('Security.userGroup')"
            :formatter="formatUserGroupKey"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="phone"
            :label="$t('Security.userTelephone')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="address"
            :label="$t('Security.userAddress')"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="lockFlag"
            :label="$t('Security.userStatus')"
            :formatter="formatStatus"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            width="106px"
            v-if="updateUserCommand.visible"
            :label="$t('common.operation')">
            <template slot-scope="scope">
              <el-button
                size="mini"
                v-if="scope.row.userName === 'admin' ? false : true"
                style="background: #008000"
                :title="$t('common.updateBtn')"
                @click="updateUser(scope.row)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-bianji"></use>
                </svg>
              </el-button>
              <el-button
                size="mini"
                v-if="scope.row.userName === 'admin' ? false : true"
                style="background: #008000"
                :title="$t('Security.resetPassword')"
                @click="resetUserPassword(scope.row)">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-bianji"></use>
                </svg>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <CommandExecuteContext v-bind:commands="commandContext"></CommandExecuteContext>
  </div>
</template>

<script>

import UserService from '../../domain/services/UserService'
import UserGroupService from '../../domain/services/UserGroupService'
import CommandExecuteContext from '../../commands/CommandExecuteContext'
import UserCommands from '../../commands/UserCommands'
import HelperUtil from '../../utils/HelperUtil'

export default {
  name: 'UserManagement',

  components: {
    CommandExecuteContext
  },

  // 创建期间
  beforeCreate () {

  },

  // vue加载初始化函数，加载数据
  created: function () {
    this.getAllUsers()
    //      this.getAllUserGroups();
  },

  data () {
    return {
      // 命令
      commandContext: {},

      // 删除相关
      deleteList: [],

      // 为修改传参数
      updateInitList: [],

      // 查询条件
      queryList: [],

      multipleSelection: [],

      // form参数
      formLabelWidth: '120px',

      // 用户名
      userCollection: {},
      userList: [],
      selectedUserKey: '',

      // 用户组
      userGroupCollection: {},
      userGroupList: [],
      selectedUserGroup: '', // 用户组查询条件

      // 用户状态
      userLockFlag: [{
        value: 0,
        label: this.$t('Security.unlocked')
      }, {
        value: 1,
        label: this.$t('Security.locked')
      }],
      selectedLockFlag: '',

      // 用户实体类
      userKey: '',
      userName: '',
      usergroupKey: '',
      editFlag: 0, // 0可编辑；1不可编辑
      password: '',
      phone: '',
      address: '',
      modifyTime: '',
      delFlag: 0,
      lockFlag: 0, // 0：未锁定 1：已锁定

      // 弹出框双向绑定
      form: {
        userName: '',
        userKey: '',
        usergroupName: '',
        usergroupKey: '',
        editFlag: 0,
        password: '123456',
        phone: '',
        address: '',
        modifyTime: '',
        delFlag: 0,
        lockFlag: 0,
        enableChecked: false
      }

    }
  },

  computed: {
    // 命令
    createCommand () {
      return UserCommands.createUserCommand(this.commandContext)
    },
    deleteUserCommand () {
      return UserCommands.deleteUserCommand(this.deleteList, this.commandContext)
    },
    updateUserCommand () {
      return UserCommands.updateUserCommand(this.updateInitList, this.commandContext)
    }
  },

  methods: {
    /* ---------------------------页面显示--------------------------- */

    /***
       * @Description  : 获取全部用户，初始化表格+用户下拉菜单
       * @author       : zf
       * @date         : 2019/03/13 11:01
       */
    getAllUsers: function () {
      let _this = this
      _this.getAllUserGroups()
      UserService.getAllUserCollection().then(result => {
        // 成功
        _this.userCollection = result
        _this.userList = Object.values(result)
      }).catch(err => {
        // 失败
        _this.InfoTip.errorTip(_this, err)
      })
    },

    /***
       * @Description  : 获取全部用户组
       * @author       : zf
       * @date         : 2019/03/13 16:00
       */
    getAllUserGroups: function () {
      let _this = this
      UserGroupService.getAllUserGroups().then(result => {
        // 成功
        _this.userGroupCollection = result
        _this.userGroupList = Object.values(result)
      }).catch(err => {
        // 失败
        _this.InfoTip.errorTip(_this, err)
      })
    },

    /***
      * @Description  : 用户组改变
      * @author       : zf
      * @date         : 2019/06/20 17:52
      */
    getAllUserGroupsChange: function (visible) {
      if (visible) {
        this.getAllUserGroups()
      }
    },

    /***
       * @Description  : 超级用户不能被删除修改
       * @author       : zf
       * @date         : 2019/04/01 15:09
       */
    checkboxDisabled: function (row, rowIndex) {
      let currentIndex
      for (let i = 0; i < this.userList.length; i++) {
        if (this.userList[i].editFlag === 1) {
          currentIndex = i
        }
      }
      if (rowIndex === currentIndex) {
        return false
      } else {
        return true
      }
    },

    /***
       * @Description  : 表格过滤用户锁定状态
       * @author       : zf
       * @date         : 2019/02/25 15:54
       */
    formatStatus: function (row, column) {
      let result = row.lockFlag
      if (row.lockFlag === 0) {
        result = this.$t('Security.unlocked')
      } else if (row.lockFlag === 1) {
        result = this.$t('Security.locked')
      }
      return result
    },

    /***
       * @Description  : 表格过滤用户组名称
       * @author       : zf
       * @date         : 2019/03/13 09:51
       */
    formatUserGroupKey: function (row, column) {
      if (this.userGroupCollection[row.usergroupKey] !== undefined) {
        return this.userGroupCollection[row.usergroupKey].usergroupName
      } else {
        return row.usergroupKey
      }
    },

    /* ---------------------------Table选择--------------------------- */

    /**
       * @Description  :选择行
       * @author       :zf
       * @date         :2019/2/25
       */
    handleSelectionChange (val) {
      this.multipleSelection = val
    },

    /**
       * @Description  :单选一行选中checkbox
       * @author       :zf
       * @date         :2019/2/25
       */
    clickRow (val) {
      let currentRow
      for (let i = 0; i < this.userList.length; i++) {
        if (val.userKey === this.userList[i].userKey) {
          currentRow = i
        }
      }
      if (this.userList[currentRow].editFlag !== 1) {
        this.$refs.multipleTable.toggleRowSelection(val)
      }
    },

    /* ---------------------------新建用户--------------------------- */

    /***
       * @Description  : 点击创建按钮
       * @author       : zf
       * @date         : 2019/03/13 10:37
       */
    createUser: function () {
      this.createCommand.execute()
    },

    /* ---------------------------删除用户--------------------------- */

    /***
       * @Description  : 删除选中用户
       * @author       : zf
       * @date         : 2019/03/13 13:40
       */
    deleteUser: function () {
      if (this.multipleSelection.length === 0) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.DELETE_SELECT_CODE))
      } else {
        this.deleteList = new Array()
        for (let i = 0; i < this.multipleSelection.length; i++) {
          var obj = {'userKey': this.multipleSelection[i]['userKey']}
          this.deleteList.push(obj)
        }
        this.deleteUserCommand.execute()
      }
    },

    /* ---------------------------修改选择--------------------------- */

    /***
       * @Description  : 点击修改按钮
       * @author       : zf
       * @date         : 2019/03/08 16:29
       */
    updateUser: function (row) {
      let currentUser = {}
      currentUser['userKey'] = row.userKey
      currentUser['userName'] = row.userName
      currentUser['usergroupKey'] = row.usergroupKey
      currentUser['password'] = row.password
      currentUser['phone'] = row.phone
      currentUser['address'] = row.address
      currentUser['modifyTime'] = row.modifyTime
      currentUser['delFlag'] = row.delFlag
      currentUser['lockFlag'] = row.lockFlag
      if (currentUser['lockFlag'] === 1) {
        currentUser['enableChecked'] = true
      } else {
        currentUser['enableChecked'] = false
      }

      this.updateInitList = currentUser
      this.updateUserCommand.execute()


      // if (this.multipleSelection.length === 0 || this.multipleSelection.length > 1) {
      //   this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.UPDATE_SELECT_CODE))
      // } else {
      //   let currentUser = {}
      //   currentUser['userKey'] = this.multipleSelection[0].userKey
      //   currentUser['userName'] = this.multipleSelection[0].userName
      //   currentUser['usergroupKey'] = this.multipleSelection[0].usergroupKey
      //   currentUser['password'] = this.multipleSelection[0].password
      //   currentUser['phone'] = this.multipleSelection[0].phone
      //   currentUser['address'] = this.multipleSelection[0].address
      //   currentUser['modifyTime'] = this.multipleSelection[0].modifyTime
      //   currentUser['delFlag'] = this.multipleSelection[0].delFlag
      //   currentUser['lockFlag'] = this.multipleSelection[0].lockFlag
      //   if (currentUser['lockFlag'] === 1) {
      //     currentUser['enableChecked'] = true
      //   } else {
      //     currentUser['enableChecked'] = false
      //   }
      //
      //   this.updateInitList = currentUser
      //   this.updateUserCommand.execute()
      // }
    },

    /* ---------------------------查询用户--------------------------- */

    /***
       * @Description  : 获取查询条件
       * @author       : zf
       * @date         : 2019/05/21 13:14
       */
    getQueryList: function () {
      this.queryList = []
      if (this.selectedUserKey !== '' && this.selectedUserKey !== null) {
        this.queryList.push({
          quaryAttribute: 'userName',
          compareSymbol: 'like',
          compareValue: this.selectedUserKey
        })
      }
      if (this.selectedUserGroup !== '' && this.selectedUserGroup !== null) {
        this.queryList.push({
          quaryAttribute: 'usergroupKey',
          compareSymbol: '=',
          compareValue: this.selectedUserGroup
        })
      }
      if (this.selectedLockFlag !== '' && this.selectedLockFlag !== null) {
        this.queryList.push({
          quaryAttribute: 'lockFlag',
          compareSymbol: '=',
          compareValue: this.selectedLockFlag
        })
      }
    },

    /***
       * @Description  : 按条件查询用户
       * @author       : zf
       * @date         : 2019/03/13 14:13
       */
    queryUser: function () {
      let _this = this
      _this.getQueryList()
      //        _this.getAllUserGroups(); //同步用户组信息
      let loadingInstance = _this.Loading.openLoading()
      UserService.conditionQueryUser(this.queryList).then(result => {
        // 成功
        _this.Loading.closeLoading(loadingInstance)
        _this.userList = Object.values(result)
        if (_this.userList.length === 0) {
          _this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.QUERY_NULL_CODE))
        } else {
          _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.QUERY_CODE))
        }
      }).catch(err => {
        // 失败
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },

    /* ---------------------------重置密码--------------------------- */

    /***
       * @Description  : 重置用户密码为初始密码
       * @author       : zf
       * @date         : 2019/03/18 15:26
       */
    resetUserPassword: function (row) {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      UserService.resetUserPassword(row).then(result => {
        // 成功
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.OTHERS_CODE))
      }).catch(err => {
        // 失败
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    }

  },

  watch: {
    commandContext (newVal, oldVal) {
      if (JSON.stringify(newVal) === '{}') {
        this.selectedUserKey = ''
        this.selectedUserGroup = ''
        this.selectedLockFlag = ''
        this.getAllUsers()
        this.$refs.multipleTable.clearSelection()
      }
      deep: true
    },

    '$i18n.locale' () {
      this.userLockFlag[0].label = this.$t('Security.unlocked')
      this.userLockFlag[1].label = this.$t('Security.locked')
    }
  }
}
</script>

<style scoped>
</style>
