<template>
  <div>
    <Panel title="用户管理">
      <template slot="buttons">
        <el-button class="blue" @click="queryUserData" icon="el-icon-fa-search">查询</el-button>
        <el-button class="yellow" @click="pageTable.handleReset()" icon="el-icon-fa-reply-all">重置</el-button>
      </template>
      <el-form label-position="top" :model="pageTable.param" ref="queryform">
        <el-row>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="实际姓名" prop="username">
              <el-input v-model="pageTable.param.username" @keyup.native.enter="queryUserData"/>
            </el-form-item>
          </el-col>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="用户工号" prop="usercode">
              <el-input v-model="pageTable.param.usercode" @keyup.native.enter="queryUserData"/>
            </el-form-item>
          </el-col>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="状态" prop="userstat">
              <el-select placeholder="状态" v-sys-code="'userstat'" v-model="pageTable.param.userstat" clearable>
                <el-option label="启用" value="5"></el-option>
                <el-option label="禁用" value="6"></el-option>
                <el-option label="注销" value="9"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="隶属机构" prop="orgId">
              <Selector v-model="pageTable.param.orgId" :clearable="true" label-key="label" value-key="id"
                        placeholder="隶属组织机构">
                <SelectorTree tree-key="orgTree" searchField="ORG_NAME" rootLabel="组织机构"/>
              </Selector>
            </el-form-item>
          </el-col>

          <el-col :lg='4' :sm='12'>
            <el-form-item label="范围开始时间" prop="startTime">
              <el-date-picker v-model="pageTable.param.startTime" type="datetime" placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="范围结束时间" prop="endTime">
              <el-date-picker v-model="pageTable.param.endTime" type="datetime" placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </Panel>
    <Panel title="用户列表">
      <template slot="buttons">
        <el-button class="red" :disabled="!multipleSelection.length>0" icon="el-icon-fa-lock" @click="lockAndOpenUsers(true)"
                   title="批量禁用">禁用
        </el-button>
        <el-button class="blue" :disabled="!multipleSelection.length>0" icon="el-icon-fa-unlock" @click="lockAndOpenUsers(false)"
                   title="批量启用">启用
        </el-button>
        <el-button class="yellow" :disabled="!multipleSelection.length>0" icon="el-icon-fa-key" @click="resetUserPw" title="批量重置密码">
          重置密码
        </el-button>
        <el-button class="green" @click="doAdd()" icon="el-icon-fa-plus">新增</el-button>
      </template>

      <el-table border :data="pageTable.data" element-loading-spinner="el-icon-loading" v-loading="pageTable.isLoading" ref="table"
                element-loading-text="数据加载中" height="calc(100vh - 280px)" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align='center' width="55" fixed='left'/>
        <!--                <el-table-column prop="$rownum" label="NO." show-overflow-tooltip/>-->
        <el-table-column prop="userid" label="用户名称" show-overflow-tooltip/>
        <el-table-column prop="username" label="实际姓名" show-overflow-tooltip/>
        <!-- <el-table-column prop="usercode" label="用户工号" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="userstat" dict='userstat' label="状态" show-overflow-tooltip>
          <template slot-scope="scope">
<!--            <SysCode type="userstat" :value="scope.row.userstat"/>-->
            <span v-if="scope.row.userstat=== '5'">启用</span>
            <span v-if="scope.row.userstat=== '6'">禁用</span>
            <span v-if="scope.row.userstat=== '9'">注销</span>
          </template>
        </el-table-column>
        <el-table-column prop="orgname" label="隶属机构" show-overflow-tooltip/>
        <el-table-column prop="crtime" :formatter="formatterDateTime" label="创建时间" show-overflow-tooltip/>
        <el-table-column prop="optime" :formatter="formatterDateTime" label="最后修改时间" show-overflow-tooltip/>
        <el-table-column label="操作" fixed='right' width="200" align="center">
          <template slot-scope="scope">
            <el-button class="blue" icon="el-icon-fa-edit" @click="doEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button class="blue" title="登陆时间轴" icon="el-icon-location" @click="showTimeLine(scope.row)">时间轴</el-button>
            <el-button class="red" icon="el-icon-fa-trash" @click="doDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <export-ctrl class="pull-left" @export="pageTable.handleExport($event, $refs.table)"/>
      <el-pagination background :page-size.sync="pageTable.size" :current-page.sync="pageTable.curr" :total="pageTable.total"/>
    </Panel>

    <el-dialog close-on-press-escape append-to-body v-draggable :visible.sync="editor.show" title="用户管理" width="60%">
      <div class="dialog-button">
        <el-button class="blue " plain icon="el-icon-fa-save" @click="doSubmit()" :disabled="editor.stat==='6' ||editor.stat==='9'">
          保存
        </el-button>
        <el-button class="yellow" plain icon="el-icon-fa-key" @click="resetPwd()" :disabled="!editor.uuid||editor.stat!=='5'">重置密码
        </el-button>
        <el-button class="red" plain icon="el-icon-fa-trash" @click="doShut()" :disabled="!editor.uuid||editor.stat==='9'">注销
        </el-button>
        <el-button class="red" plain icon="el-icon-fa-lock" @click="doClose()" title="禁用"
                   v-if="editor.uuid && (editor.stat==='5' || editor.stat==='9')">禁用
        </el-button>
        <el-button class="blue" plain icon="el-icon-fa-unlock" @click="doOpen()" title="启用"
                   v-if="editor.uuid && (editor.stat==='6' || editor.stat==='9')">启用
        </el-button>
      </div>
      <UserEditor style="min-height:250px" v-if="editor.show" ref="userEditor" :uuid="editor.uuid" @submit="saveUser"/>
    </el-dialog>

    <el-dialog close-on-press-escape append-to-body v-draggable :visible.sync="timeLine.visible" title="用户登录时间轴" width="500px">
      <div v-if="timeLine.visible">
        <UserTimeLine @closeDia='timeLine.visible = false' :user-uuid='timeLine.uuid'/>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import UserEditor from "./UserEditor";
  import SelectorTree from "@/common/SelectorTree";
  import UserAPI from "@/api/base/usrm/UserAPI";
  import UserTimeLine from "./UserTimeLine.vue";
  import PageTable from "@/libs/PageTable";

  export default {
    name: "UserMgr",
    components: {UserEditor, SelectorTree, UserTimeLine},
    data() {
      return {
        pageTable: new PageTable({
          autoLoad: true,
          doLoad: UserAPI.queryUser,
          param: {},
          log: false
        }),
        timeLine: {
          visible: false,
          uuid: "",
          username: '',
        },
        queryform: {
          usercode: null,
          username: null,
          userstat: null,
          orgId: null,
          startTime: null,
          endTime: null
        },
        table: {
          data: []
        },
        editor: {
          show: false,
          uuid: null,
          visible: false, // 编辑器-显示
          loading: false,
          stat: ""
        },
        multipleSelection: []
      };
    },
    methods: {
      //批量重置用户密码
      async resetUserPw() {
        await this.confirm();
        let uuids = [];
        this.multipleSelection.forEach((value, index) => {
          uuids.push(value.uuid);
        });
        if (uuids.length > 0) {
          await UserAPI.resetUserPw({uuids: uuids});
          await this.pageTable.handleLoad();
        }
      },
      //显示登陆时间轴
      showTimeLine(row) {
        this.timeLine.username = row.username;
        this.timeLine.uuid = row.uuid;
        this.timeLine.visible = true;
      },
       //删除用户
       async doDel(row) {
         console.log("12222222222222222",row)
        await this.confirm(null, "是否删除该用户");
        await UserAPI.userdel({uuid:row.uuid});
        await this.pageTable.handleLoad(); // 查询数据
        this.cancelEditorLoading(); // 最终要取消loading
      },
      // 重置密码
      async resetPwd(data) {
        await this.confirm(null, "是否重置该用户密码");
        this.editor.loading = true;
        this.editor.error = {}; // 还原错误信息(必须先还原)
        await UserAPI.resetPwd(this.$refs.userEditor.data);
        await this.pageTable.handleLoad();
        this.cancelEditorLoading(); // 最终要取消loading
      },
      // 注销
      async doShut(data) {
        await this.confirm(null, "是否注销该用户");
        this.editor.loading = true;
        this.editor.error = {}; // 还原错误信息(必须先还原)
        await UserAPI.shutUser(this.$refs.userEditor.data);
        await this.pageTable.handleLoad(); // 查询数据
        this.cancelEditorLoading(); // 最终要取消loading
      },
      // 解锁
      async doOpen(data) {
        await this.confirm(null, "是否启用该用户");
        this.editor.loading = true;
        this.editor.error = {}; // 还原错误信息(必须先还原)
        await UserAPI.openUser(this.$refs.userEditor.data);
        await this.pageTable.handleLoad(); // 查询数据
        this.cancelEditorLoading(); // 最终要取消loading
      },
      // 锁定
      async doClose(data) {
        await this.confirm(null, "是否禁用该用户");
        this.editor.loading = true;
        this.editor.error = {}; // 还原错误信息(必须先还原)
        await UserAPI.lockUser(this.$refs.userEditor.data);
        await this.pageTable.handleLoad(); // 查询数据
        this.cancelEditorLoading(); // 最终要取消loading
      },
      // 打开编辑页面
      doEdit(index, rowData) {
        this.editor.show = true;
        this.editor.uuid = rowData.uuid;
        this.editor.stat = rowData.userstat;
      },
      // 打开新建画面
      doAdd() {
        this.editor.show = true;
        this.editor.uuid = null;
        this.editor.stat = "";
      },
      async doSubmit() {
        await this.confirm();
        this.$refs.userEditor.submitForm();
      },
      async saveUser(data) {
        this.editor.loading = true;
        let resp = await UserAPI.saveUser(data)
        if (resp.newuser === "true") {
          this.$alert("该用户的默认密码是: " + resp.password, {
            showConfirmButton: false,
            type: "info"
          });
        }
        await this.pageTable.handleLoad(); // 查询数据
        this.cancelEditorLoading(); // 最终要取消loading
      },
      cancelEditorLoading() {
        this.editor.show = false;
        this.editor.loading = false;
      },
      queryUserData() {
        if (this.pageTable.param.endTime < this.pageTable.param.startTime) {
          this.$message.error("开始时间不能大于结束时间");
          return;
        }
        this.pageTable.handleLoad();
      },
      resetquery() {
        this.$refs.queryform.resetFields();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //批量解锁或锁定用户
      async lockAndOpenUsers(b) {
        await this.confirm();
        let uuids = [];
        this.multipleSelection.forEach((value, index) => {
          uuids.push(value.uuid);
        });
        if (uuids.length > 0)
          if (b) {
            await UserAPI.lockAndOpenUsers({uuids: uuids, opType: "1"});
            await this.pageTable.handleLoad();
          } else {
            await UserAPI.lockAndOpenUsers({uuids: uuids, opType: "0"});
            await this.pageTable.handleLoad();
          }
      }
    }
  };
</script>
