<template>
  <div style="min-width: 1190px">
    <el-main>
      <div class="tou">用户管理</div>
      <div>
        <div class="student_head">
          <div class="student_search">
            <div style="color: #ababab; font-size: 15px; min-width: 70px">
              条件筛选
            </div>
            <el-select
              v-model="schoolX"
              placeholder="筛选的学校"
              @change="getClassX"
              style="margin-right: 5px; width: 150px"
            >
              <el-option label="所有学校" value=""></el-option>
              <el-option
                v-for="item in schoolList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-select
              v-model="classX"
              placeholder="筛选的班级"
              no-data-text="此学校暂无班级"
              @change="search"
              style="margin-right: 5px; width: 150px"
            >
              <el-option label="所有班级" value=""></el-option>
              <el-option
                v-for="item in classListX"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-select
              v-model="typeX"
              placeholder="角色"
              @change="search"
              style="margin-right: 5px; width: 80px"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="老师" value="1"></el-option>
              <el-option label="学生" value="2"></el-option>
            </el-select>
            <span>
              <el-input
                placeholder="请输入手机号或用户名"
                v-model="studentnameA"
                clearable
              >
              </el-input>
            </span>
            <el-button type="primary" @click="search">查询</el-button>
          </div>
          <div class="student_button">
            <el-button type="primary" @click="search1">{{
              cclass ? "返回列表" : "班级修改申请"
            }}</el-button>
            <el-upload
              class="upload-demo"
              :http-request="handleChange"
              :on-remove="handleRemove"
              action="#"
              :file-list="fileListUpload"
              accept=".xlsx"
            >
              <el-button size="primary" type="primary" style="margin-right: 0px"
                >点击上传</el-button
              >
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
            <el-button type="text" class="xls_button" @click="getExcel"
              >xls上传样例</el-button
            >
            <div style="margin-left: 5px; min-width: 90px">共{{ total }}人</div>
          </div>
        </div>
        <div class="student_table">
          <el-table
            ref="table"
            :data="tableData"
            border
            :height="tableHeight"
            stripe
            :fit="true"
            style="width: 100%"
            :header-cell-style="{ background: '#f1f1f1' }"
            v-loading="isLoading"
          >
            <el-table-column prop="name" label="姓名" min-width="5">
              <template slot-scope="scope">
                <span>{{
                  scope.row.state
                    ? scope.row.name
                    : scope.row.name + "(已被屏蔽)"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="phonenumber" label="电话" min-width="5">
            </el-table-column>
            <el-table-column prop="school" label="学校" min-width="10">
            </el-table-column>
            <el-table-column prop="class" label="班级" min-width="10">
              <template slot-scope="scope">
                <span>{{ scope.row.class || "暂无班级" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="身份" min-width="5">
              <template slot-scope="scope">
                <span>{{ scope.row.type == "1" ? "老师" : "学生" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="20">
              <template slot-scope="scope">
                <div class="pb_buttonBox" style="justify-content: left">
                  <el-button
                    @click="handleDelete(scope.row.userid, scope.row.state)"
                    type="primary"
                    size="small"
                    >{{ scope.row.state ? "屏蔽" : "恢复" }}</el-button
                  ><el-button
                    @click="updateUserType(scope.row.type, scope.row.userid)"
                    type="primary"
                    size="small"
                    >修改成{{
                      scope.row.type == "1" ? "学生" : "老师"
                    }}</el-button
                  ><el-button
                    @click="changePPop(scope.row.userid)"
                    type="primary"
                    size="small"
                    >修改密码</el-button
                  >
                  <el-button
                    @click="
                      changeCPop(
                        scope.row.userid,
                        scope.row.organizeid,
                        scope.row.school,
                        scope.row.classid
                      )
                    "
                    type="primary"
                    size="small"
                    >修改班级</el-button
                  >
                  <!-- v-if="scope.row.type == '2'" -->
                  <el-button
                    type="primary"
                    size="small"
                    v-if="scope.row.cclassid"
                    @click="
                      agreeUpdate(
                        scope.row.cclassid,
                        scope.row.userid,
                        scope.row.cclass
                      )
                    "
                    >同意修改班级申请</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="student_page">
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="10"
            :total="total"
            v-if="!isListAjax && page"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>
    </el-main>
    <el-dialog
      title="修改密码"
      :visible.sync="userPasswordDialog"
      width="500px"
      :before-close="handleClose"
      class="dialog_diy"
      center
    >
      <div>
        <div class="upBox">
          <span>密码</span>
          <el-input
            v-model="updatePassword"
            style="width: 250px; margin: 15px 0px"
            placeholder="请输入需要修改的密码"
          ></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userPasswordDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateUserPassword">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改班级"
      :visible.sync="updateClassDialog"
      :append-to-body="true"
      width="450px"
      :before-close="handleClose1"
      class="dialog_diy"
    >
      <el-form>
        <el-form-item label="所属学校" :label-width="formLabelWidth">
          <el-input :value="schoolName" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="班级" :label-width="formLabelWidth">
          <el-select
            v-model="classA"
            placeholder="请选择学生所属的班级"
            no-data-text="此学校暂无班级"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateClassDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateClass">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import "../../common/aws-sdk-2.235.1.min";
import $ from "jquery";
export default {
  data() {
    return {
      tableData: [],
      page: 1,
      total: 0,
      tableHeight: 500,
      isLoading: false,
      studentnameA: "",
      type: "",
      userPasswordDialog: false,
      uid: "",
      updatePassword: "",
      fileListUpload: [],
      updateClassDialog: false,
      schoolName: "",
      oid: "",
      formLabelWidth: "100px",
      classA: "",
      classList: [],
      cclass: "",
      schoolList: [],
      schoolX: "",
      classX: "",
      classListX: [],
      typeX: "",
      isListAjax: false,
    };
  },
  methods: {
    //搜索学生
    search() {
      this.isListAjax = true;
      this.page = 1;
      this.getUser();
    },
    search1() {
      this.isListAjax = true;
      this.page = 1;
      this.cclass == 1 ? (this.cclass = "") : (this.cclass = 1);
      this.getUser();
    },
    handleDelete(id, state) {
      let params = [{ uid: id, state: state == 1 ? "0" : "1" }];
      this.$confirm("确定" + (state ? "屏蔽" : "恢复") + "此用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "deleteStudent", params)
            .then((res) => {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              // if (this.page != 1 && this.tableData.length == 1) {
              //   this.page--;
              // }
              this.getUser();
            })
            .catch((err) => {
              this.$message.error("操作失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    //获取班级
    getClass() {
      let params = { cid: this.oid };
      this.ajax
        .get(this.$store.state.api + "findClassByTeacher", params)
        .then((res) => {
          this.classList = res.data[0];
          console.log(res.data[0][0]);
          this.updateClassDialog = true;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    getClassX() {
      let params = { cid: this.schoolX };
      this.ajax
        .get(this.$store.state.api + "findClassByTeacher", params)
        .then((res) => {
          this.classListX = res.data[0];
        })
        .catch((err) => {
          console.error(err);
        });
      this.isListAjax = true;
      this.classX = "";
      this.page = 1;
      this.getUser();
    },
    //查询学校
    getOrg() {
      this.ajax
        .get(this.$store.state.api + "getAllOrg", "")
        .then((res) => {
          this.schoolList = res.data[0];
          console.log(res.data[0]);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getUser();
    },
    handleClose(done) {
      done();
    },
    handleClose1(done) {
      this.oid = "";
      this.schoolName = "";
      this.classList = [];
      done();
    },
    //获取所有用户
    getUser() {
      this.isLoading = true;
      let params = {
        cn: this.studentnameA,
        cclass: this.cclass,
        school: this.schoolX,
        class: this.classX,
        type: this.typeX,
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "getAllUser", params)
        .then((res) => {
          this.isListAjax = false;
          this.isLoading = false;
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          this.tableData = res.data[0];
        })
        .catch((err) => {
          this.isLoading = false;
          console.error(err);
        });
    },
    //修改用户角色
    updateUserType(type, id) {
      let params = [{ type: type == "1" ? "2" : "1", uid: id }];
      this.$confirm("确定修改此用户角色吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "updateUserType", params)
            .then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.getUser();
            })
            .catch((err) => {
              this.$message.error("修改失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    changePPop(uid) {
      this.userPasswordDialog = true;
      this.uid = uid;
    },
    changeCPop(uid, oid, school, classid) {
      this.uid = uid;
      this.oid = oid;
      this.schoolName = school;
      this.classA = classid;
      this.getClass();
    },
    updateClass() {
      if (this.classA == "") {
        this.$message.error("请选择班级");
        return;
      }
      let params = [
        {
          uid: this.uid,
          cid: this.classA,
          t: "",
          nc: "",
          s: 0,
        },
      ];
      this.ajax
        .post(this.$store.state.api + "UpdateSClass", params)
        .then((res) => {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.updateClassDialog = false;
          this.getUser();
        })
        .catch((err) => {
          this.$message.error("修改失败");
          console.error(err);
        });
    },
    agreeUpdate(cid, uid, classA) {
      this.$confirm("同意此用户修改成班级为" + classA + "吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = [
            {
              uid: uid,
              cid: cid,
              t: "修改班级",
              nc: "管理员已通过你的班级修改申请",
              s: 0,
            },
          ];
          this.ajax
            .post(this.$store.state.api + "UpdateSClass", params)
            .then((res) => {
              this.$message({
                message: "同意修改成功",
                type: "success",
              });
              this.getUser();
              this.getnCount();
            })
            .catch((err) => {
              this.$message.error("同意修改失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    getnCount() {
      this.ajax
        .get(this.$store.state.api + "getClassC")
        .then((res) => {
          console.log(res);
          if (res.data[0].length > 0) {
            this.$store.commit("update", ["nCount", res.data[0][0].num]);
          } else {
            this.$store.commit("update", ["nCount", 0]);
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    updateUserPassword() {
      if (this.updatePassword.length == 0) {
        this.$message.error("请输入需要修改的密码");
        return;
      } else if (this.updatePassword.length < 6) {
        this.$message.error("密码必须大于六位");
        return;
      }
      let params = [{ p: this.updatePassword, uid: this.uid }];
      this.$confirm("确定此用户的密码吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "updateUserPassword", params)
            .then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.userPasswordDialog = false;
              this.getUser();
            })
            .catch((err) => {
              this.$message.error("修改失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    //导出上传样例
    getExcel(res) {
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../common/Export2Excel");
        const tHeader = [
          "用户名称",
          "用户角色(填老师或学生)",
          "用户手机号码",
          "用户密码",
          "所属学校",
        ];
        // const filterVal = ["name", "phone", "school", "grade"];
        // const list = [
        //   {
        //     name: "6",
        //     phone: "su",
        //     school: "sue",
        //     grade: 3423,
        //   },
        // ];
        // this.formatJson(filterVal, list)
        const data = [];
        export_json_to_excel(tHeader, data, "上传用户样例");
      });
    },
    handleChange(file) {
      this.fileTemp = file.file;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          this.importCount = 1;
          this.importfxx(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    //导入
    importfxx(obj) {
      const loading = this.$loading.service({
        background: "rgba(255, 255, 255, 0.7)",
        target: document.body,
      });
      var _$ = $;
      this.importCount++;
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          this.da = [...outdata];
          let arr = [];
          this.da.map((v) => {
            let obj = {};
            obj.name = v["用户名称"];
            obj.type = v["用户角色(填老师或学生)"];
            obj.phone = v["用户手机号码"];
            obj.password = v["用户密码"];
            obj.school = v["所属学校"];
            arr.push(obj);
          });
          console.log(arr);
          let _b = 1;
          for (var i = 0; i < arr.length; i++) {
            let item = arr[i];
            if (item.name === "") {
              _b = 1;
              _this.$message.error("用户名称不能为空,请重新上传");
              break;
            } else if (item.type === "") {
              _b = 1;
              _this.$message.error("用户角色不能为空,请重新上传");
              break;
            } else if (item.password === "") {
              _b = 1;
              _this.$message.error("用户密码不能为空,请重新上传");
              break;
            } else if (!/^1\d{10}$/.test(item.phone)) {
              _b = 1;
              _this.$message.error("有用户手机号格式不正确,请重新上传");
              break;
            } else if (item.school === "") {
              _b = 1;
              _this.$message.error("用户所属学校不能为空,请重新上传");
              break;
            } else if (item.phone === "") {
              _b = 1;
              _this.$message.error("用户手机号不能为空,请重新上传");
              break;
            } else if (
              !(
                (item.type == "学生" && item.type != "老师") ||
                (item.type != "学生" && item.type == "老师")
              )
            ) {
              _b = 1;
              _this.$message.error("请按规定填写用户角色,只能填写老师或学生");
              break;
            }

            if (item.type == "学生") {
              item.type = "2";
            } else {
              item.type = "1";
            }

            if (item.school != "") {
              let params = { n: item.school };
              let _a;
              _$.ajax({
                url: _this.$store.state.api + "findSchool", //url路径
                type: "GET", //GET
                async: false, //或false,是否异步
                data: params,
                timeout: 5000, //超时时间
                dataType: "json", //返回的数据格式：
                beforeSend: function (xhr) {},
                success: function (res, textStatus, jqXHR) {
                  if (res[0][0].num == 0) {
                    _this.$message.error(
                      item.school + "此学校未被添加,请去组织管理添加"
                    );
                    _a = 1;
                  } else {
                    item.school = res[0][0].id;
                  }
                  console.log(res);
                },
                error: function (xhr, textStatus) {
                  console.log(textStatus);
                },
                complete: function () {},
              });
              if (_a == 1) {
                _b = 1;
                break;
              }
            }
            // if (item.phone != "") {
            //   let params = { un: item.phone };
            //   let _a;
            //   _$.ajax({
            //     url: _this.$store.state.api + "findPhoneBoolean", //url路径
            //     type: "GET", //GET
            //     async: false, //或false,是否异步
            //     data: params,
            //     timeout: 5000, //超时时间
            //     dataType: "json", //返回的数据格式：
            //     beforeSend: function (xhr) {},
            //     success: function (res, textStatus, jqXHR) {
            //       if (res[0].length > 0) {
            //         _this.$message.error(item.phone + "此手机号码已被注册");
            //         _a = 1;
            //       }
            //     },
            //     error: function (xhr, textStatus) {
            //       console.log(textStatus);
            //     },
            //     complete: function () {},
            //   });
            //   if (_a == 1) {
            //     _b = 1;
            //     break;
            //   }
            // }
            _b = 2;
          }

          if (_b == 2) {
            console.log("11111111111111111111");
            for (var i = 0; i < arr.length; i++) {
              let _i = i;
              let item = arr[i];
              let params = {
                uname: item.phone,
                upassword: item.password,
                t: item.type,
                oid: item.school,
                n: item.name,
              };
              // _this.ajax
              //   .post(_this.$store.state.api + "addUser", params)
              //   .then((res) => {
              //     if (_i == arr.length - 1) {
              //       loading.close();
              //       _this.$message({
              //         message: "上传成功",
              //         type: "success",
              //       });
              //       _this.getUser();
              //     }
              //   })
              //   .catch((err) => {
              //     _this.$message.error("添加失败");
              //     console.error(err);
              //   });
              _$.ajax({
                url: _this.$store.state.api + "addUser", //url路径
                type: "GET", //GET
                async: false, //或false,是否异步
                data: params,
                timeout: 5000, //超时时间
                dataType: "json", //返回的数据格式：
                beforeSend: function (xhr) {},
                success: function (res, textStatus, jqXHR) {
                  if (_i == arr.length - 1) {
                    loading.close();
                    _this.$message({
                      message: "上传成功",
                      type: "success",
                    });
                    _this.getUser();
                  }
                },
                error: function (xhr, textStatus) {
                  _this.$message.error("添加失败");
                  console.log(textStatus);
                },
                complete: function () {},
              });
            }
          } else {
            loading.close();
          }

          _this.fileListUpload = [];
        };
        reader.readAsArrayBuffer(f);
      };

      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    changeHeight() {
      this.tableHeight =
        window.innerHeight - this.$refs.table.$el.offsetTop - 200;
      if (this.tableHeight <= 530) {
        this.tableHeight = 530;
      }
      // 监听窗口大小变化
      let self = this;
      window.onresize = function () {
        self.tableHeight =
          window.innerHeight - self.$refs.table.$el.offsetTop - 200;
        if (self.tableHeight <= 530) {
          self.tableHeight = 530;
        }
      };
      // this.$refs.table.$el.offsetTop：表格距离浏览器的高度 //200表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
    },
  },
  created() {
    this.$nextTick(function () {
      if (this.$route.query.cclass) {
        this.cclass = this.$route.query.cclass;
      }
      this.page = 1;
      this.getUser();
      this.changeHeight();
      this.getOrg();
    });
  },
};
</script>


<style scoped>
.dialog_diy >>> .el-dialog__header {
  background: #3d67bc !important;
  padding: 15px 20px;
}
.dialog_diy >>> .el-dialog__title {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn {
  top: 19px;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}

.tou {
  border-bottom: 1px solid #c9c9c9;
  height: 50px;
  font-size: 30px;
}
.student_head >>> .el-button--primary {
  background-color: #2268bc;
}
.student_head {
  margin: 10px 0 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.student_search {
  display: flex;
  width: 900px;
  overflow: hidden;
  height: 40px;
  align-items: center;
}
.student_search span {
  margin: 0 10px 0 0;
}
.upload-demo {
  display: flex;
  flex-direction: column;
  align-items: end;
  /* position: relative; */
  width: 100px;
  min-width: 100px;
  margin-left: 5px;
  overflow: hidden;
}
.student_button {
  display: flex;
  overflow: hidden;
  height: 40px;
  align-items: center;
  min-width: 430px;
  justify-content: flex-end;
}
.student_button .el-button--primary {
  margin-right: 10px;
}
.student_table {
  margin: 20px 0;
}
.upBox {
  display: flex;
  justify-content: center;
  align-items: center;
}
.upBox span {
  margin-right: 5px;
}
</style>
