<template>
  <div class="pb_content myd_content">
    <div class="pb_head">
      <van-icon
        name="arrow-left"
        color="#fff"
        class="pb_back"
        size="1.2rem"
        @click="goBack"
      />
      <span>个人资料</span>
    </div>
    <div class="pb_content_body">
      <div class="myd_head">
        <div class="myd_head_title"><span>头像</span></div>

        <div class="li_head_portal">
          <van-uploader
            v-model="fileList"
            :after-read="afterRead"
            preview-size="5rem"
            accept="image/*"
            capture="camera"
            preview-full-image="preview-full-image"
            v-loading="photoLoading"
            :limit="1"
          >
            <img
              v-lazy="
                this.userinfo.smailheadportrait
                  ? this.userinfo.smailheadportrait
                  : require('../../assets/icon/portal.png')
              "
              alt=""
            />
          </van-uploader>
        </div>
        <van-icon
          name="arrow"
          color="#d9d9d9"
          size="1.2rem"
          class="arrow_right"
        />
      </div>
      <div class="myd_content_body">
        <van-cell-group>
          <van-cell
            title="真实姓名:"
            size="large"
            :value="userinfo.name"
            @click="updateInfo()"
            is-link
          >
            <template #right-icon>
              <van-icon
                name="arrow"
                color="#d9d9d9"
                size="1.2rem"
                class="arrow_left"
              />
            </template>
          </van-cell>
          <van-cell
            title="绑定手机号:"
            size="large"
            :value="userinfo.phonenumber"
          >
            <template #right-icon>
              <van-icon
                name="arrow"
                color="#d9d9d9"
                size="1.2rem"
                class="arrow_left"
              />
            </template>
          </van-cell>
          <van-cell
            title="地区:"
            size="large"
            is-link
            :value="userinfo.dest"
            @click="popShow = true"
          >
            <template #right-icon>
              <van-icon
                name="arrow"
                color="#d9d9d9"
                size="1.2rem"
                class="arrow_left"
              />
            </template>
          </van-cell>
          <van-cell title="学校:" size="large" :value="userinfo.schoolName">
            <template #right-icon>
              <van-icon
                name="arrow"
                color="#d9d9d9"
                size="1.2rem"
                class="arrow_left"
              />
            </template>
          </van-cell>
          <van-cell
            title="家长姓名:"
            size="large"
            :value="userinfo.parentname"
            is-link
            @click="updateParent()"
          >
          <!-- v-if="!(this.$store.state.userInfo.type == '1')" -->
            <template #right-icon>
              <van-icon
                name="arrow"
                color="#d9d9d9"
                size="1.2rem"
                class="arrow_left"
              />
            </template>
          </van-cell>
          <!-- <van-cell
            title="老师:"
            size="large"
            :value="userinfo.teacherName"
            is-link
            @click="popShowA = true"
            v-if="!(this.$store.state.userInfo.type == '1')"
          >
            <template #right-icon>
              <van-icon
                name="arrow"
                color="#d9d9d9"
                size="1.2rem"
                class="arrow_left"
              />
            </template>
          </van-cell> -->
          <van-cell
            title="班级:"
            size="large"
            is-link
            :value="userinfo.classnameA"
            @click="updateGrade"
          >
          <!-- v-if="!(this.$store.state.userInfo.type == '1')" -->
            <template #right-icon>
              <van-icon
                name="arrow"
                color="#d9d9d9"
                size="1.2rem"
                class="arrow_left"
              />
            </template>
          </van-cell>
          <!-- <van-cell
            title="班级:"
            size="large"
            :value="userinfo.classname"
            is-link
            @click="updateClass()"
            v-if="!(this.$store.state.userInfo.type == '1')"
          >
            <template #right-icon>
              <van-icon
                name="arrow"
                color="#d9d9d9"
                size="1.2rem"
                class="arrow_left"
              />
            </template>
          </van-cell> -->
        </van-cell-group>
      </div>
      <div class="exitButton">
        <button @click="exit">退出登录</button>
      </div>
      <van-popup v-model="popShow" position="bottom">
        <van-picker
          show-toolbar
          title="请选择您所在的地区"
          :columns="fromJson"
          @cancel="popShow = false"
          @confirm="onConfirm"
        />
      </van-popup>
      <van-popup v-model="popShowA" position="bottom">
        <van-picker
          show-toolbar
          title="请选择老师"
          :columns="teacherList"
          @cancel="popShowA = false"
          @confirm="onConfirmA"
        />
      </van-popup>
      <van-popup v-model="popShowB" position="bottom">
        <van-picker
          show-toolbar
          title="请选择年级"
          :columns="classList"
          @cancel="popShowB = false"
          @confirm="onConfirmB"
          v-if="classList.length>0"
        />
        <van-picker
          v-else
          show-toolbar
          title="请选择年级"
          :columns="classList1"
          @cancel="popShowB = false"
          @confirm="onConfirmB"
        />
      </van-popup>
    </div>
    <transition-group name="van-slide-right">
      <div class="md_upadate_bod" v-show="showUpdateName" key="showUpdateName">
        <div class="pb_head">
          <van-icon
            name="arrow-left"
            color="#fff"
            class="pb_back"
            size="1.2rem"
            @click="cancelUpdate"
          />
          <span>编辑信息</span>
          <div class="pb_left"><span>保存</span></div>
        </div>
        <div class="md_panel_update">
          <van-field v-model="updateName" placeholder="请输入修改的名字" />
        </div>
      </div>
      <div
        class="md_upadate_bod"
        v-show="showUpdateParent"
        key="showUpdateParent"
      >
        <div class="pb_head">
          <van-icon
            name="arrow-left"
            color="#fff"
            class="pb_back"
            size="1.2rem"
            @click="cancelUpdate"
          />
          <span>编辑信息</span>
          <div class="pb_left"><span>保存</span></div>
        </div>
        <div class="md_panel_update">
          <van-field
            v-model="UpdateParentName"
            placeholder="请输入修改的家长名字"
          />
        </div>
      </div>
      <div
        class="md_upadate_bod"
        v-show="showUpdateClass"
        key="showUpdateClass"
      >
        <div class="pb_head">
          <van-icon
            name="arrow-left"
            color="#fff"
            class="pb_back"
            size="1.2rem"
            @click="cancelUpdate"
          />
          <span>编辑信息</span>
          <div class="pb_left"><span>保存</span></div>
        </div>
        <div class="md_panel_update">
          <van-field v-model="UpdateClassName" placeholder="请输入修改的班级" />
        </div>
      </div>
    </transition-group>
  </div>
</template>

<script>
import { Toast } from "vant";
import areaList from "../../config/area";
import "../../common/aws-sdk-2.235.1.min";
export default {
  data() {
    return {
      showUpdateName: false,
      showUpdateParent: false,
      showUpdateClass: false,
      updateName: "",
      UpdateParentName: "",
      UpdateClassName: "",
      userinfo: this.$store.state.userInfo,
      fromJson: areaList,
      popShow: false,
      fileList: [],
      photoLoading: false,
      teacherList: [],
      classList: [],
      classList1: [{text:"此学校没有设置班级",id:""}],
      popShowA: false,
      popShowB: false,
    };
  },
  methods: {
    getUser() {
      let params = { uid: this.userinfo.userid };
      this.ajax
        .get(this.$store.state.api + "getUser", params)
        .then((res) => {
          this.userinfo = res.data[0][0];
          // window.sessionStorage.setItem(
          //   "userInfo",
          //   JSON.stringify(this.userinfo)
          // );
          this.$cookies.set("userInfo",this.userinfo,-1)
          this.$store.commit("update", ["userInfo", this.userinfo]);
          this.getClass();
          console.log(res.data[0][0]);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    getTeacher() {
      let params = { oid: this.$store.state.userInfo.organizeid };
      this.ajax
        .get(this.$store.state.api + "findTeacher", params)
        .then((res) => {
          this.teacherList = []
          res.data[0].filter((element) => {
            this.teacherList.push({ text: element.name, id: element.userid });
          });
          console.log(res.data[0][0]);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    updateGrade() {
      // if (!this.$store.state.userInfo.tid) {
      //   this.$toast.fail("请选择老师后在选择年级");
      //   return;
      // }
      this.popShowB = true;
    },
    getClass() {
      // if (this.$store.state.userInfo.tid) {
        let params = { cid: this.$store.state.userInfo.organizeid };
        this.ajax
          .get(this.$store.state.api + "findClassByTeacher", params)
          .then((res) => {
            this.classList = [];
            res.data[0].filter((element) => {
              this.classList.push({ text: element.name, id: element.id });
            });
            console.log(res.data[0][0]);
          })
          .catch((err) => {
            console.error(err);
          });
      // }
    },
    goBack() {
      this.$router.isBack = true;
      if (window.history.length <= 1) {
        this.$router.push({ path: "/" });
        return false;
      } else {
        this.$router.go(-1);
      }
    },
    cancelUpdate() {
      this.showUpdateName = false;
      this.showUpdateParent = false;
      this.showUpdateClass = false;
    },
    updateInfo(type) {
      this.showUpdateName = true;
      this.updateName = this.userinfo.name;
      document
        .getElementsByClassName("pb_left")[0]
        .addEventListener("click", (e) => {
          if (this.updateName === "") {
            this.$toast.fail("姓名不能修改为空！");
            return;
          }
          let params = [
            {
              n: this.updateName,
              uid: this.$store.state.userInfo.userid,
            },
          ];
          this.ajax
            .post(this.$store.state.api + "UpdateUserName", params)
            .then((res) => {
              this.$toast.success("修改成功");
              this.userinfo.name = this.updateName;
              this.showUpdateName = false;
              this.getUser();
            })
            .catch((err) => {
              this.userinfo.smailheadportrait = "";
              this.fileList = [];
              this.$toast.success("修改失败");
              console.error(err);
            });
        });
    },
    updateParent() {
      this.showUpdateParent = true;
      this.UpdateParentName = this.userinfo.parentname;
      document
        .getElementsByClassName("pb_left")[1]
        .addEventListener("click", (e) => {
          if (this.UpdateParentName === "") {
            this.$toast.fail("家长姓名不能修改为空！");
            return;
          }
          let params = [
            {
              n: this.UpdateParentName,
              uid: this.$store.state.userInfo.userid,
            },
          ];
          this.ajax
            .post(this.$store.state.api + "UpdateUserParent", params)
            .then((res) => {
              this.$toast.success("修改成功");
              this.userinfo.parentname = this.UpdateParentName;
              this.showUpdateParent = false;
              this.getUser();
            })
            .catch((err) => {
              this.userinfo.smailheadportrait = "";
              this.fileList = [];
              this.$toast.success("修改失败");
              console.error(err);
            });
        });
    },
    updateClass() {
      this.showUpdateClass = true;
      this.UpdateClassName = this.userinfo.classname;
      document
        .getElementsByClassName("pb_left")[2]
        .addEventListener("click", (e) => {
          if (this.UpdateClassName === "") {
            this.$toast.fail("班级不能修改为空！");
            return;
          }
          let params = [
            {
              n: this.UpdateClassName,
              uid: this.$store.state.userInfo.userid,
            },
          ];
          this.ajax
            .post(this.$store.state.api + "UpdateUserClassName", params)
            .then((res) => {
              this.$toast.success("修改成功");
              this.userinfo.classname = this.UpdateClassName;
              this.showUpdateClass = false;
              this.getUser();
            })
            .catch((err) => {
              this.userinfo.smailheadportrait = "";
              this.fileList = [];
              this.$toast.success("修改失败");
              console.error(err);
            });
        });
    },
    exit() {
      sessionStorage.clear();
      this.$cookies.remove('login')
      this.$cookies.remove('userInfo')
      this.$store.commit("update", ["isLogin", false]);
      this.$store.commit("update", ["userInfo", {}]);
      Toast.success("退出成功");
      this.$router.push("/login");
    },
    //修改地区
    onConfirm(value) {
      let params = [
        {
          d: value.join(""),
          uid: this.$store.state.userInfo.userid,
        },
      ];
      this.ajax
        .post(this.$store.state.api + "UpdateUserDest", params)
        .then((res) => {
          this.$toast.success("修改成功");
          this.userinfo.dest = value.join("");
          this.popShow = false;
          this.getUser();
        })
        .catch((err) => {
          this.$toast.success("修改失败");
          console.error(err);
        });
    },
    //修改老师
    onConfirmA(value) {
      if (value.id == this.$store.state.userInfo.tid) {
        this.$toast.fail("您已经是这个老师的学生了");
        retrun;
      }
      let params = [
        {
          uid: this.$store.state.userInfo.userid,
          tid: value.id,
        },
      ];
      // this.$Dialog
        // .confirm({
        //   title: "修改老师",
        //   message: "确认修改老师嘛，修改了就要重新选择年级了！",
        // })
        // .then(() => {
          this.ajax
            .post(this.$store.state.api + "UpdateTeacher", params)
            .then((res) => {
              this.$toast.success("修改成功");
              this.popShowA = false;
              this.getUser();
            })
            .catch((err) => {
              this.$toast.success("修改失败");
              console.error(err);
            });
        // })
        // .catch(() => {
        //   // on cancel
        // });
    },
    //修改年级
    onConfirmB(value) {
      if (value.id == this.$store.state.userInfo.classid) {
        this.$toast.fail("您已经是这个年级的了");
        retrun;
      }
      let params = [
        {
          uid: this.$store.state.userInfo.userid,
          cid: value.id,
        },
      ];

      this.ajax
        .post(this.$store.state.api + "UpdateSClassC", params)
        .then((res) => {
          this.$toast.success("提交申请成功，请等待管理员同意");
          this.popShowB = false;
          this.getUser();
        })
        .catch((err) => {
          this.$toast.success("申请失败");
          console.error(err);
        });
    },
    //上传头像
    afterRead(file) {
      this.photoLoading = true;

      var _file = file.file;
      file.status = "uploading";
      file.message = "上传中...";

      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域

      var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
      var _this = this;

      var mediaFormatList = ["png", "jpg", "jpeg"];

      if (mediaFormatList.indexOf(_file.name.split(".")[1]) == "-1") {
        _this.$toast.fail("请上传jpg或者png的图片格式文件");
        _this.fileList = _this.fileList.filter((fileA) => {
          return fileA.file.lastModified != file.file.lastModified;
        });

        file.status = "failed";
        file.message = "上传失败";
        return;
      }

      if (_file) {
        var params = {
          Key: _file.name,
          ContentType: _file.type,
          Body: _file,
          "Access-Control-Allow-Credentials": "*",
          ACL: "public-read",
        }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          partSize: 2048 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true,
        };
        bucket
          .upload(params, options)
          .on("httpUploadProgress", function (evt) {
            //这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
          })
          .send(function (err, data) {
            _this.photoLoading = false;
            if (err) {
              _this.$toast.fail("上传失败");
              file.status = "failed";
              file.message = "修改失败";
              //上传错误处理
              _this.fileList = _this.fileList.filter((fileA) => {
                return fileA.file.lastModified != _file.lastModified;
              });
            } else {
              //上传成功处理
              file.status = "success";
              // _this.fileList = _this.fileList.filter((fileA) => {
              //   if (fileA.file.lastModified == _file.lastModified) {
              //     fileA.url = data.Location;
              //     return fileA;
              //   } else {
              //     return fileA;
              //   }
              // });
              // UpdateUserS
              let params = [
                {
                  s: data.Location,
                  uid: _this.$store.state.userInfo.userid,
                },
              ];
              _this.ajax
                .post(_this.$store.state.api + "UpdateUserS", params)
                .then((res) => {
                  _this.$toast.success("修改头像成功");
                  _this.userinfo.smailheadportrait = data.Location;
                  _this.fileList = [];
                  _this.getUser();
                })
                .catch((err) => {
                  _this.userinfo.smailheadportrait = "";
                  _this.fileList = [];
                  this.$toast.success("修改头像失败");
                  console.error(err);
                });
              console.log(data.Location);
            }
          });
      }
    },
  },
  created() {
    console.log(!(this.$store.state.userInfo.type=="1"));
    this.getTeacher();
    this.getUser();
  },
};
</script>

<style scoped>
.van-cell {
  width: 100%;
  margin: 0 auto;
}
.myd_content {
  height: 100%;
}
.li_head_portal {
  height: 2.8rem;
  width: 2.8rem;
  overflow: hidden;
  border-radius: 10rem;
  margin: 0 0.5rem 0 0rem;
}
.li_head_portal >>> img {
  height: 2.8rem;
  width: 2.8rem;
}
.myd_content_body {
  margin-top: 0.6rem;
}
.myd_head {
  background: #fff;
  width: 100%;
  display: flex;
  padding: 1rem 0;
  justify-content: flex-end;
  align-items: center;
}
.myd_head_title {
  flex: 1 1 auto;
  margin-left: 0.8rem;
  font-size: 16px;
}
.arrow_right {
  margin-right: 0.7rem;
}
.arrow_left {
  margin-left: 0.7rem;
}
.md_upadate_bod {
  width: 100%;
  height: 100%;
  background: rgba(243, 243, 243);
  position: absolute;
  top: 0;
  z-index: 99999;
}
.exitButton {
  display: flex;
  align-items: center;
  justify-content: center;
  /* margin-top: 1rem; */
  /* position: absolute;
  width: 100%;
  bottom: 1rem; */
  margin: 1rem 0;
}
.exitButton button {
  color: white;
  background: red;
  border: none;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-size: 1rem;
  text-align: center;
  border-radius: 10rem;
  cursor: pointer;
  transition: opacity 0.2s;
  height: 2rem;
  width: 90%;
  font-size: 0.8rem;
  line-height: 1.5rem;
}
</style>
