<!--
  revit扫楼人员管理
 -->
<template>
  <div id="build_user">
    <div class="search_header">
      <build-input :placeholder="placeholder" @search="search"></build-input>
      <div class="inline_block" @click="tableAddUser">
        <i class="iconfont icon-addpeople_fill"></i>
        <i>添加扫楼人员</i>
      </div>
      <div class="inline_block" @click="undo">
        <i class="iconfont icon-undo"></i>
        <i>撤回</i>
      </div>
      <div class="inline_block" @click="refresh">
        <i class="iconfont icon-shuaxin"></i>
        <i>刷新</i>
      </div>
    </div>
    <div class="user_view" v-loading="loading">
      <div id="user"></div>
      <div class="no_data" v-show="noData">暂无数据</div>
    </div>
    <div class="user_page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="pageSizeArr"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageCount"
      ></el-pagination>
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" :before-close="handleClose">
      <span>{{msg}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="deldialog">
      <span>你确定删除用户{{delString}}吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="refresh">取 消</el-button>
        <el-button type="primary" @click="delTrue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import buildInput from "@/components/input";
import buildTime from "@/components/selectTime";

import {
  getUser, //获取扫楼用户
  loadUser, //修改
  delUser, //删除
  addUser //添加
} from "../api/request";

export default {
  components: {
    "build-input": buildInput,
    "build-time": buildTime
  },
  data() {
    return {
      placeholder: "请输入姓名、联系电话、登录名、备注等关键字搜索",
      checkTimeArr: [], //选择到的时间周期
      myHot: "", //表格实例
      row: "",
      col: "",
      dialogVisible: false,
      deldialog: false,
      msg: "",
      pageNum: 1,
      pageSize: 10,
      pageSizeArr: [5, 10, 20, 30, 50],
      pageCount: 0,
      currentPage: 1,
      filter: "",
      userData: [],
      delString: "",
      delArr: [],
      noData: false,
      ProjId: this.$route.query.projId, //url获取项目id this.$route.query.projId /Pj1101080047/Pj1101080001
      UserId: this.$route.query.userId, //url获取用户id this.$route.query.userId/25518428919955458
      loading: false, //loading动画
      deepArr: [] //删除时使用的数组
    };
  },
  mounted() {
    this.getUserTable();
    //   this.populateHot()
  },
  methods: {
    //获取用户表格
    getUserTable() {
      let param = {
        filter: this.filter,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ProjId: this.ProjId,
        UserId: this.UserId
      };

      getUser(param).then(result => {
        this.userData = result.data.UserList;
        this.pageCount = result.data.Count;
        this.loading = false;
        //存储一个数组防止删除操作找寻不到删除的该数组
        this.deepArr = this.deepCopy(result.data.UserList);
        if (this.userData.length) {
          this.noData = false;
          if (this.myHot) {
            this.myHot.loadData(result.data.UserList);
          } else {
            this.populateHot();
          }
        } else {
          this.noData = true;
          if (this.myHot) {
            this.myHot.destroy();
            this.myHot = "";
          }
        }
      });
    },

    //删除用户
    delUser(UserList) {
      let param = {
        ProjId: this.ProjId,
        UserId: this.UserId,
        UserList: UserList
      };
      delUser(param).then(result => {
        if (result.data.Result == "success") {
          this.getUserTable();
          return;
        } else {
          this.msg = "请求出错";
          this.dialogVisible = true;
        }
      });
    },

    //更新用户
    loadUser(UserList) {
      let param = {
        ProjId: this.ProjId,
        UserId: this.UserId,
        UserList: UserList
      };
      loadUser(param).then(result => {
        if (result.data.Result == "success") {
          return;
        } else {
          this.msg = "请求出错";
          this.dialogVisible = true;
        }
      });
    },

    //请求接口添加用户
    addUser(User) {
      let param = {
        ProjId: this.ProjId,
        UserId: this.UserId,
        User: User
      };
      addUser(param).then(result => {
        if (result.data.Result == "success") {
          this.userData[0].UserId = result.data.UserId;
          this.userData[0].ProjId = this.ProjId;
          return;
        } else {
          this.msg = "请确定手机号码未重复";
          this.dialogVisible = true;
        }
      });
    },

    //表格添加用户
    tableAddUser() {
      let param = {
        Note: "",
        Phone: "",
        UserName: ""
      };
      //判断是否有第一个用户
      if (this.userData[0]) {
        //有的话判断第一个用户是否是空值，空值禁止再次添加
        if (this.userData[0].Phone && this.userData[0].UserName) {
          this.userData.unshift(param);
          this.deepArr.unshift(param);
          this.pageCount += 1;
          this.myHot.destroy();
          this.myHot = "";
          this.populateHot();
          this.noData = false;
        } else {
          return;
        }
      } else {
        //没有第一个用户再次生成表格
        this.userData.unshift(param);
        this.deepArr.unshift(param);
        this.pageCount += 1;
        this.myHot = "";
        this.populateHot();
        this.noData = false;
      }
    },

    //撤回
    undo() {
      this.myHot.undo();
    },

    //搜索
    search(val) {
      this.loading = true;
      if (this.myHot) {
        this.myHot.destroy();
        this.myHot = "";
      }
      this.filter = val;
      this.pageNum = this.currentPage = 1;
      this.getUserTable();
    },

    //一页的个数
    handleSizeChange(val) {
      this.loading = true;
      this.pageSize = val;
      this.myHot.destroy();
      this.myHot = "";
      this.getUserTable();
    },

    //当前页
    handleCurrentChange(val) {
      this.loading = true;
      this.pageNum = val;
      this.myHot.destroy();
      this.myHot = "";
      this.getUserTable();
    },

    //刷新
    refresh() {
      this.loading = true;
      this.myHot.destroy();
      this.myHot = "";
      this.deldialog = false;
      this.getUserTable();
    },

    //弹窗关闭
    handleClose(done) { },

    //表格单元格单击时触发
    callBack(event, coords, td) {
      var row = coords.row;
      var col = coords.col;
      if (row != 0 && col != 0) {
        var ss = this.myHot.getCell(row, col, true); //取出点击Cell
        (this.row = row), (this.col = col);
      }
    },

    //单元格修改内容触发
    tdClick(changeData, source) {
      // changeData 是一个数组，第一个元素(数组)，记录所有修改信息
      if (!changeData) return;
      let rep = /^1(3|4|5|7|8)\d{9}$/;
      let indexArr = changeData.map(item => {
        return item[0];
      });
      // let dataArr
      let param = indexArr.map((item, index) => {
        if (
          !rep.test(this.userData[item].Phone) &&
          this.userData[item].ProjId
        ) {
          this.msg = "手机号码格式错误";
          this.dialogVisible = true;
          return this.userData[item];
        } else if (this.userData[item].UserName.length < 0) {
          this.msg = "姓名不可少于一个字符";
          this.dialogVisible = true;
          return this.userData[item];
        } else {
          return this.userData[item];
        }
      });

      //处理好数据，请求接口
      if (param[0].ProjId) {
        this.loadUser(param);
      } else {
        //当数据没有projId时走添加接口
        if (param[0].Phone != "" && param[0].UserName.length > 2) {
          if (rep.test(param[0].Phone)) {
            this.addUser(param[0]);
          } else {
            this.msg = "手机号码格式错误";
            this.dialogVisible = true;
            return;
          }
        } else {
          return;
        }
      }
    },

    delTrue() {
      this.delUser(this.delArr);
      this.deldialog = false;
    },

    //处理右键删除
    removeUser(index, amout) {
      this.deldialog = true;
      this.delString = "";
      this.delArr = [];
      let i = index + amout;
      for (; index < i; index++) {
        if (index + 1 == i) {
          this.delString += this.deepArr[index].UserName;
        } else {
          this.delString += this.deepArr[index].UserName + "、";
        }
        this.delArr.push(this.deepArr[index].UserId);
      }
    },

    //表格渲染生成
    populateHot() {
      var container1 = document.getElementById("user");
      let maxRow = "";
      //当当前页数*当前页个数小于总个数时，当前表格行数为当前页数
      if (this.pageCount >= this.pageSize * this.currentPage) {
        maxRow = this.pageSize;
      } else {
        maxRow = this.pageCount % this.pageSize;
      }
      var options = {
        data: this.userData,
        colHeaders: ["姓名", "联系电话/登录名", "备注"],
        manualColumnResize: true, //允许改变表头宽度
        manualColumnMove: true, //允许拉动表头
        stretchH: "last", //最后一行填充
        maxRows: maxRow,
        contextMenu: {
          items: {
            remove_row: {
              name: "删除用户"
            }
          }
        },
        columns: [
          {
            data: "UserName"
          },
          {
            data: "Phone",
            type: "numeric"
          },
          {
            data: "Note"
          }
        ],
        // beforeRemoveRow: this.removeUser,
        afterRemoveRow: this.removeUser
      };
      this.myHot = new Handsontable(container1, options);
      //表格数据发生改变
      this.myHot.addHook("afterChange", this.tdClick);
      // this.myHot.afterRemoveRow()

      //删除前
      // this.myHot.removeHook('beforeInit', this.removeUser);
      //添加单击事件
      // Handsontable.hooks.add('afterOnCellMouseDown',this.callBack,this.myHot)
      document.getElementById("hot-display-license-info").style.display =
        "none";
    },

    //工具函数浅复制深拷贝，防止共用存储空间
    deepCopy(obj) {
      var out = [],
        i = 0,
        len = obj.length;
      for (; i < len; i++) {
        if (obj[i] instanceof Array) {
          out[i] = deepcopy(obj[i]);
        } else out[i] = obj[i];
      }
      return out;
    }
  }
};
</script>

<style lang="less" scoped>
#app {
  min-width: 1098px;
  min-height: 767px;
  position: relative;
  overflow-x: auto;
}
#build_user {
  width: 100%;
  // padding-top: .4rem;
  // padding-left: 1rem;
  // padding-right: 1rem;
  box-sizing: border-box;
  .search_header {
    position: fixed;
    min-width: 1098px;
    top: 0;
    left: 0;
    right: 0;
    height: 3rem;
    padding-top: 0.4rem;
    box-sizing: border-box;
    padding-left: 1rem;
    padding-right: 1rem;
    background-color: #eee;
    width: 100%;
    .derived_btn {
      width: 8rem;
      border: 1px solid #777;
      text-align: center;
      font-size: 0.6rem;
      height: 1.6rem;
      line-height: 1.6rem;
      cursor: pointer;
      background-color: #ccc;
      border-radius: 0.1rem;
      float: right;
      margin-right: 3rem;
      margin-top: 0.2rem;
      .icon-excelwenjian {
        font-size: 1rem;
        margin-bottom: -0.1rem;
      }
    }
    .inline_block {
      float: right;
      margin-left: 3rem;
      padding: 0 0.8rem;
      font-size: 0.8rem;
      height: 2rem;
      line-height: 2rem;
      color: #000;
      text-align: center;
      border-radius: 0.8rem;
      cursor: pointer;
      .iconfont {
        font-size: 1rem;
      }
    }
  }
  .user_view {
    position: absolute;
    width: 100%;
    top: 3.5rem;
    left: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
    // #user{
    //     table{
    //         tr{
    //             td:first-child{
    //                 text-align: center;
    //             }
    //         }
    //     }
    // }
  }
  .user_page {
    position: fixed;
    height: 3rem;
    left: 0;
    bottom: 0;
    right: 0;
    width: 100%;
  }
}
</style>
