/**
 * 系统管理 用户管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>服务管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-select size="small" v-model="formInline.onOff" placeholder="请选择">
          <el-option label="全部" value=""></el-option>
          <el-option label="运行中" value='true'></el-option>
          <el-option label="未运行" value='false'></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formInline.name" placeholder="输入服务名"></el-input>
      </el-form-item>
      <!-- <el-form-item label="">
        <el-input size="small" v-model="formInline.userMobile" placeholder="输入手机号"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="selectAppData">查找</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="small" type="primary" @click="searchServers()">服务搜索</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" @selection-change="selectChange" :data="userData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>
      <el-table-column align="center" sortable prop="script" label="脚本" width="100">
      </el-table-column>
      <el-table-column align="center" sortable prop="name" label="服务名" width="200">
      </el-table-column>
      <el-table-column align="center" sortable prop="onOff" label="状态" width="100">
        <template slot-scope="scope">
          <span v-show="!scope.row.iseditor">{{scope.row.onOff ? '运行':'停止'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="pid" label="pid" width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="ram" label="内存使用" width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="startTime" label="启动时间" min-width="110">
      </el-table-column>
      <!-- <el-table-column align="center" sortable prop="editTime" label="修改时间" min-width="100">
        <template slot-scope="scope">
          <div>{{scope.row.editTime|timestampToTime}}</div>
        </template>
      </el-table-column> -->
      <el-table-column align="center" sortable prop="onOff" label="状态" min-width="50">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.onOff?nshow:fshow" active-color="#13ce66" inactive-color="#ff4949" @change="editType(scope.$index, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="230">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteServe(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="danger" @click="removeServe(scope.$index, scope.row)">去除</el-button>
          <el-button size="mini" type="success" @click="start(scope.$index, scope.row)">启动</el-button>
          <el-button size="mini" type="success" @click="restart(scope.$index, scope.row)">重启</el-button>
          <el-button size="mini" type="success" @click="stop(scope.$index, scope.row)">停止</el-button>
          <el-button size="mini" type="success" @click="getLog(scope.$index, scope.row)">查看log</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination> -->
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
        <el-form-item label="path" prop="path">
          <el-input size="small" v-model="editForm.path" auto-complete="off" placeholder="请输入路径"></el-input>
        </el-form-item>
        <el-form-item label="参数" prop="args">
          <el-input size="small" v-model="editForm.argsString" auto-complete="off" placeholder="请输入参数逗号隔开"></el-input>
        </el-form-item>

        <el-form-item label="服务名" prop="name">
          <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入服务名"></el-input>
        </el-form-item>
        <el-form-item label="脚本" prop="script">
          <el-input size="small" v-model="editForm.script" auto-complete="off" placeholder="请输入脚本"></el-input>
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input size="small" v-model="editForm.port" auto-complete="off" placeholder="请输入端口号"></el-input>
        </el-form-item>
        <el-form-item label="自启动" prop="enable">
            <el-switch v-model="editForm.enable"></el-switch>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
   
  </div>
</template>

<script>
// 导入请求方法
import {
  selectApp,
  saveApp,
  deleteApp,
  searchApp,
  startServer,
  stopServer,
  restartServer,
  userSave,
  userDelete,
  userPwd,
  userExpireToken,
  userFlashCache,
  userLock,
  UserDeptTree,
  UserDeptSave,
  UserDeptdeptTree,
  UserChangeDept
} from '../../api/userMG'
import Pagination from '../../components/Pagination'
export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      title: '添加用户',
      editFormVisible: false, //控制编辑页面显示与隐藏
      dataAccessshow: false, //控制数据权限显示与隐藏
      unitAccessshow: false, //控制所属单位隐藏与显示
      // 编辑与添加
      editForm: {
        path: '',
        argsString: '',
        name: '',
        script: '',
        port: '',
        enable: false
      },
      // 部门参数
      unitparm: {
        userIds: '',
        deptId: '',
        deptName: ''
      },
      // 选择数据
      selectdata: [],
      // rules表单验证
      rules: {
      },
      // 删除用户
      seletedata: {
        ids: '',
        token: localStorage.getItem('logintoken')
      },
      // 重置密码
      resetpsd: {
        userId: '',
        token: localStorage.getItem('logintoken')
      },
      // 用户下线
      offline: {
        token: localStorage.getItem('logintoken')
      },
      // 请求数据参数
      formInline: {
        onOff:"",
        name:""
      },
      //用户数据
      userData: [],
      // 数据权限
      UserDept: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 选中
      checkmenu: [],
      //参数role
      saveroleId: '',
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },

  /**
   * 数据发生改变
   */
  watch: {},

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取数据方法
    getdata(parameter) {
      this.loading = true
      // 模拟数据开始
      let res = {
        code: 0,
        msg: null,
        count: 12,
        data: [
          // {
          //   addUser: null,
          //   editUser: null,
          //   addTime: 1526452756000,
          //   editTime: 1527128981000,
          //   userId: 62,
          //   systemNo: null,
          //   userName: '211111111', 
          //   userPassword: 'e10adc3949ba59abbe56e057f20f883e',
          //   userRealName: '21111111111',
          //   userSex: '男',
          //   userMobile: '13601478451',
          //   userEmail: '222222@qq.com',
          //   isLock: 'N',
          //   deptId: 17,
          //   deptName: 'v',
          //   roleId: 2
          // }
        ]
      }
      this.loading = false
      this.userData = res.data
      // // 分页赋值
      // this.pageparm.currentPage = this.formInline.page
      // this.pageparm.pageSize = this.formInline.limit
      // this.pageparm.total = res.count
      // 模拟数据结束

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      // 获取服务
      selectApp(parameter).then(res => {
        this.loading = false
        if (res.success == false) {
          this.$message({
            type: 'info',
            message: res.msg
          })
        } else {
          this.userData = res.data
        }
      })
    },
    //搜索服务事件
    searchServers() {
      searchApp(this.formInline).then(res => {
        this.loading = false
        if (res.success == false) {
          this.$message({
            type: 'info',
            message: res.msg
          })
        } else {
          this.userData = res.data
        }
      })
    },
    //查找事件
    selectAppData() {
      selectApp(this.formInline).then(res =>{
          this.userData = res.data

      })
    },
    
    //查找事件
    updateOrInstall(index, row) {
      saveApp(row).then(res =>{
          this.userData = res.data

      })
    },
    // 修改type
    editType(index, row) {
      this.loading = true
      let parm = {
        lock: '',
        userId: '',
        token: localStorage.getItem('logintoken')
      }
      parm.userId = row.userId
      let lock = row.onOff
      
      if (lock ) {
        this.stop(index,row).then(res => {this.getdata(row)})
      
      } else {
        this.start(index,row).then(res => {
          console.log("1111");
          this.getdata(row)})
      }
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改'
        this.editForm.path= 			row.path
        this.editForm.argsString= 		row.argsString
        this.editForm.name= 			row.name
        this.editForm.script= 			row.script
        this.editForm.port= 			row.port
        this.editForm.enable= 			row.enable

      } else {
        this.title = '添加'
        this.editForm.path= ''
        this.editForm.argsString= ''
        this.editForm.name= ''
        this.editForm.script= ''
        this.editForm.port= ''
        this.editForm.enable= false
      }
    },
    // // 编辑、添加提交方法
    submitForm(editData) {
        console.log(this.editForm);
        saveApp(this.editForm).then(res => {
            this.$message.info('保存！')
        })
        .catch(err => {
          this.loading = false
          this.$message.error('保存失败！')
        })
      
    },
    // 显示部门设置
    handleunit: function(index, row) {
      this.unitAccessshow = true
      let parms = 0
      UserDeptdeptTree(parms)
        .then(res => {
          if (res.data.success) {
            this.UserDept = this.changeArr(res.data.data)
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('配置权限失败,请稍后再试！')
        })
    },
    handleClick(data, checked, node) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([])
        this.$refs.tree.setCheckedNodes([data])
        this.unitparm.deptId = data.id
        this.unitparm.deptName = data.name
        //交叉点击节点
      } else {
      }
    },
    // 选择复选框事件
    selectChange(val) {
      this.selectdata = val
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == 'edit') {
        this.editFormVisible = false
      } else if (dialog == 'perm') {
        this.dataAccessshow = false
      } else if (dialog == 'unit') {
        this.unitAccessshow = false
      }
    },
    // 删除服务
    deleteServe(index, row) {
      this.$confirm('确定要删除服务及其记录吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          row.permanentlyDelete = true
          // 删除
          userDelete(row)
            .then(res => {
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '数据已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('数据删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除！'
          })
        })
    },
    
    // 去除用户
    removeServe(index, row) {
      this.$confirm('确定要去除服务吗?，可以通过搜索服务重新找回记录', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          row.permanentlyDelete = false
          // 删除
          userDelete(row)
            .then(res => {
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '数据已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('数据删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除！'
          })
        })
    },
    // 启动服务
    start(index, row) {
     
          startServer(row)
            .then(res => {
              if (res.message == "SUCCESS")  {
                this.$message({
                  type: 'success',
                  message: '启动服务成功'
                })
                this.selectAppData()
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('启动服务失败')
            })
    },
    // 重置密码
    stop(index, row) {
     
        stopServer(row)
            .then(res => {
              if (res.message == "SUCCESS") {
                this.$message({
                  type: 'success',
                  message: '启动服务成功'
                })
                this.selectAppData()
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('启动服务失败')
            })
    },
    // 重启服务
    restart(index, row) {
     
          restartServer(row)
            .then(res => {
              if (res.message == "SUCCESS") {
                this.$message({
                  type: 'success',
                  message: '启动服务成功'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('启动服务失败')
            })
    },
    // 数据权限
    dataAccess: function(index, row) {
      this.dataAccessshow = true
      this.saveroleId = row.userId
      UserDeptTree(row.userId)
        .then(res => {
          if (res.data.success) {
            this.checkmenu = this.changemenu(res.data.data)
            this.UserDept = this.changeArr(res.data.data)
          } else {
            this.$message({
              type: 'info',
              message: res.data.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取权限失败，请稍后再试！')
        })
    },
    //数据格式化
    changeArr(data) {
      var pos = {}
      var tree = []
      var i = 0
      while (data.length != 0) {
        if (data[i].pId == 0) {
          tree.push({
            id: data[i].id,
            name: data[i].name,
            pId: data[i].pId,
            open: data[i].open,
            checked: data[i].checked,
            children: []
          })
          pos[data[i].id] = [tree.length - 1]
          data.splice(i, 1)
          i--
        } else {
          var posArr = pos[data[i].pId]
          if (posArr != undefined) {
            var obj = tree[posArr[0]]
            for (var j = 1; j < posArr.length; j++) {
              obj = obj.children[posArr[j]]
            }

            obj.children.push({
              id: data[i].id,
              name: data[i].name,
              pId: data[i].pId,
              open: data[i].open,
              checked: data[i].checked,
              children: []
            })
            pos[data[i].id] = posArr.concat([obj.children.length - 1])
            data.splice(i, 1)
            i--
          }
        }
        i++
        if (i > data.length - 1) {
          i = 0
        }
      }
      return tree
    },
    // 选中菜单
    changemenu(arr) {
      let change = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
          change.push(arr[i].id)
        }
      }
      return change
    },
    // 菜单权限-保存
    menuPermSave() {
      let parm = {
        userId: this.saveroleId,
        deptIds: ''
      }
      let node = this.$refs.tree.getCheckedNodes()
      let moduleIds = []
      if (node.length != 0) {
        for (let i = 0; i < node.length; i++) {
          moduleIds.push(node[i].id)
        }
        parm.deptIds = JSON.stringify(moduleIds)
      }
      UserDeptSave(parm)
        .then(res => {
          if (res.success) {
            this.$message({
              type: 'success',
              message: '权限保存成功'
            })
            this.dataAccessshow = false
            this.getdata(this.formInline)
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('权限保存失败，请稍后再试！')
        })
    },
    // // 下线用户
    // offlineUser(index, row) {
    //   this.$confirm('确定要让' + row.userName + '用户下线吗?', '信息', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       userExpireToken(row.userName)
    //         .then(res => {
    //           if (res.success) {
    //             this.$message({
    //               type: 'success',
    //               message: '用户' + row.userName + '强制下线成功！'
    //             })
    //             this.getdata(this.formInline)
    //           } else {
    //             this.$message({
    //               type: 'info',
    //               message: res.msg
    //             })
    //           }
    //         })
    //         .catch(err => {
    //           this.loading = false
    //           this.$message.error('用户下线失败，请稍后再试！')
    //         })
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '已取消'
    //       })
    //     })
    // },
    // 刷新缓存
    // refreshCache(index, row) {
    //   userFlashCache(row.userName)
    //     .then(res => {
    //       if (res.success) {
    //         this.$message({
    //           type: 'success',
    //           message: '刷新成功！'
    //         })
    //         this.getdata(this.formInline)
    //       } else {
    //         this.$message({
    //           type: 'info',
    //           message: res.msg
    //         })
    //       }
    //     })
    //     .catch(err => {
    //       this.loading = false
    //       this.$message.error('刷新失败，请稍后再试！')
    //     })
    // }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 