111
litian
2024-03-20 0555dd7dc2edc553030b7a6d03d6a1cda4b1e336
packageDomain/pages/teacherCertification/index.js
@@ -1,17 +1,56 @@
const app = getApp();
import tool from "../../../assets/js/toolClass.js";
import { getTopicMsgCmsItemFile } from '../../../assets/js/middleGround/tool.js';
import FormData from '../../../utils/formdata/index.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    teacherInfo: {
      schoolName: '', //学校名称
      fullName: '', //姓名
      positionalTitle: '', //职称
      courseName: '', //任课教程
      phone: '', //联系电话
      telphone: '', //座机
      email: '', //联系邮箱
      detailedAddress: '', //通讯地址
      relevantCertificates: [], //相关证件
      state: '', //审核状态默认待审核
      agree: false
    },
    teachPosts: [],
    teachText: '',
    teachVisible: false,
    phoneError: false,
    telphoneError: false,
    emailError: false,
    topicMessageList: [],
    topicId: "",
    worksInfo: [],
    userId: '',
    imgPics: [],
    file: "",
    imgs: [],
    protocolTxt: '', //教师协议
    protocolShow: false,
    editState: true,
    reasonTxt: "",
    reasonTxtShow: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
  onLoad() {
    this.getpositionalTitle();
    this.getAgreement();
    if (wx.getStorageSync(app.config.tokenKey)) {
      this.getUserRole()
    }
  },
  /**
@@ -41,12 +80,547 @@
  onUnload() {
  },
  getUserRole() {
    app.MG.identity.getCurrentAppUser().then((res) => {
      if (res) {
        this.getType()
        this.setData({
          userId: res.userId
        })
        let teacherRole = res.roleLinks.find((item) => item.role.refCode == 'teacher')
        let teacherInfos = res.infoList.find((item) => item.type == 'teacherInfo')
        let wechatInfo = res.infoList.find((item) => item.type == 'WeChat')
        let studentInfo = res.infoList.find((item) => item.type == 'Default')
        let phoneInfo = res.secretList.find((item) => item.type == 'MobilePhone')
        let emailInfo = res.secretList.find((item) => item.type == 'EMail')
        let defaultUser = {};
        if (teacherRole && teacherInfos) {
          defaultUser = {
            ...teacherInfos,
            nickName: teacherInfos.fullName,
            avatarUrl: teacherInfos.icon,
            userId: res.userId,
            phoneNumber: phoneInfo?.credential,
            Email: emailInfo ? emailInfo.credential : JSON.parse(teacherInfos.data).email,
            role: 'Teacher',
            roleId: teacherRole.role.id
          }
        } else if (wechatInfo) {
          defaultUser = {
            ...wechatInfo,
            nickName: wechatInfo.name,
            avatarUrl: wechatInfo.icon,
            userId: res.userId,
            phoneNumber: phoneInfo?.credential,
            Email: emailInfo?.credential,
            role: 'Student'
          }
        } else if (studentInfo) {
          defaultUser = {
            ...studentInfo,
            nickName: wechatInfo.name,
            avatarUrl: wechatInfo.icon,
            userId: res.userId,
            phoneNumber: phoneInfo?.credential,
            Email: emailInfo?.credential,
            role: 'Student'
          }
        }
        wx.setStorageSync(app.config.userInfoKey, JSON.stringify(defaultUser));
      }
    })
  },
  getType() {
    app.MG.resource.getCmsTypeByRefCode({
      refCodes: ['jsek_teacherCertification']
    }).then((res) => {
      console.log(res)
      this.setData({
        worksInfo: res[0].cmsTypeLinks[0].children,
      })
      this.newGetTeacherInfo()
    })
  },
  newGetTeacherInfo() {
    const data = {
      start: 0,
      size: 10,
      topicIdOrRefCode: 'teacherRoleApproval',
      appRefCode: app.config.appRefCode,
      sort: {
        type: 'Desc',
        field: 'CreateDate'
      }
    }
    app.MG.ugc.getTopicMessageList(data).then((res) => {
      try {
        this.setData({
          imgPics: [],
        })
        const resData = res.datas.find((i) => i.appUserCreator.userId === this.data.userId)
        if (resData) {
          if (resData.state == 'WaitAudit') {
            this.setData({
              editState: false,
            })
          } else {
            this.setData({
              editState: true,
            })
          }
          let info = getTopicMsgCmsItemFile(this.data.worksInfo, resData.cmsItemDataList)
          console.log(info)
          this.setData({
            'teacherInfo.fullName': info.fullName,
            'teacherInfo.schoolName': info.schoolName,
            'teacherInfo.positionalTitle': info.positionalTitle,
            'teacherInfo.courseName': info.courseName,
            'teacherInfo.phone': info.phone,
            'teacherInfo.telphone': info.telphone ? info.telphone : '',
            'teacherInfo.email': info.email,
            'teacherInfo.detailedAddress': info.detailedAddress ? info.detailedAddress : '',
            'teacherInfo.relevantCertificates': info.relevantCertificates,
            'teacherInfo.agree': true,
            'teacherInfo.state': resData.state,
            topicId: resData.id,
            topicMessageList: resData.cmsItemDataList,
            teachText: info.positionalTitle,
          })
          if (resData.feedBack != null) {
            this.setData({
              reasonTxt: JSON.parse(resData.feedBack).reason,
            })
          }
          if (this.data.teacherInfo.relevantCertificates.length > 0) {
            let arr = [];
            if (typeof this.data.teacherInfo.relevantCertificates == 'object') {
              this.data.teacherInfo.relevantCertificates.forEach((ele) => {
                let imgObj = {
                  md5: ele.file.md5,
                  linkType: 'LinkFile',
                  linkProtectType: 'Public',
                  url: app.config.requestCtx + `/file/GetPreViewImage?md5=` + ele.md5
                }
                arr.push(imgObj);
                this.setData({
                  imgPics: arr,
                });
              })
            } else {
              let imgObj = {
                md5: this.data.teacherInfo.relevantCertificates,
                linkType: 'LinkFile',
                linkProtectType: 'Public',
                url:
                  app.config.requestCtx + `/file/GetPreViewImage?md5=` + this.data.teacherInfo.relevantCertificates
              }
              arr.push(imgObj);
              this.setData({
                imgPics: arr,
              });
            }
          }
        }
      } catch (error) {
      }
    })
  },
  getpositionalTitle() {
    const data = {
      refCodes: ['positionalTitle']
    }
    app.MG.store.getProductTypeField(data).then((res) => {
      try {
        let list = res[0]
        let options = JSON.parse(list.config).option
        options.forEach((item) => {
          item.label = item.name;
        })
        this.setData({
          teachPosts: options,
        })
      } catch (error) {
      }
    })
  },
  getAgreement() {
    let query = {
      path: 'jsek_protocol',
      fields: {
        content: []
      }
    }
    app.MG.resource.getItem(query).then((res) => {
      try {
        const data = res.datas.find((e) => e.refCode == 'jsek_teacherCertificationAgreement')
        this.setData({
          protocolTxt: data ? data.content : '暂无协议',
        })
      } catch (error) {
        this.setData({
          protocolTxt: '暂无协议',
        })
      }
    })
  },
  //学校名称
  onSchoolNameInput(e) {
    this.setData({
      "teacherInfo.schoolName": e.detail.value,
    });
  },
  //姓名
  onFullNameInput(e) {
    this.setData({
      "teacherInfo.fullName": e.detail.value,
    });
  },
  // 任教课程
  onCourseNameInput(e) {
    this.setData({
      "teacherInfo.courseName": e.detail.value,
    });
  },
  //详细地址
  onAddressInput(e) {
    this.setData({
      "teacherInfo.detailedAddress": e.detail.value,
    });
  },
  //选择职称
  onTeachPicker() {
    this.setData({ teachVisible: true });
  },
  onPickerChange(e) {
    const { value, label } = e.detail;
    this.setData({
      teachVisible: false,
      teachText: label[0],
      'teacherInfo.positionalTitle': value.join[0],
    });
  },
  onPickerCancel(e) {
    this.setData({
      'teacherInfo.positionalTitle': '',
      teachVisible: false,
    });
  },
  //输入手机号
  onPhoneInput(e) {
    const { phoneError } = this.data;
    const isPhoneNumber = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(e.detail.value);
    if (phoneError === isPhoneNumber) {
      this.setData({
        phoneError: !isPhoneNumber,
        "teacherInfo.phone": e.detail.value,
      });
    }
  },
  //输入座机
  onTelphoneInput(e) {
    const { telphoneError } = this.data;
    const isPhoneNumber = /^0\d{2}-\d{8}$|^0\d{3}-\d{7}$/.test(e.detail.value);
    if (telphoneError === isPhoneNumber) {
      this.setData({
        telphoneError: !isPhoneNumber,
        "teacherInfo.telphone": e.detail.value,
      });
    }
  },
  onEmailInput(e) {
    const { emailError } = this.data;
    const isPhoneNumber = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(e.detail.value);
    if (emailError === isPhoneNumber) {
      this.setData({
        emailError: !isPhoneNumber,
        "teacherInfo.email": e.detail.value,
      });
    }
  },
  // 上传图片事件
  chooseImg(e) {
    var that = this;
    wx.chooseMedia({
      // count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath也可以作为img标签的src属性显示图片
        console.log(res.tempFiles[0])
        tool.getFileMd5(res.tempFiles[0]).then((e) => {
          console.log(e, 4)
          if (!that.data.imgPics.find((item) => item.md5 == e)) {
            let formData = new FormData();
            formData.append('Md5', e);
            formData.append('FileName', e);
            formData.append('FileType', res.tempFiles[0].fileType);
            formData.appendFile("file", res.tempFiles[0].tempFilePath);
            const data = formData.getData();
            let _token = wx.getStorageSync(app.config.tokenKey);
            let header = {};
            if (_token == null) {
              header["Authorization"] = `Basic ${Base64.encode(website.clientId + ":" + website.clientSecret)}`;
            } else {
              header["Authorization"] = `Bearer ` + _token;
            }
            new Promise((resolve, reject) => {
              wx.request({
                url: app.config.requestCtx + '/file/api/ApiUpload',
                method: 'POST',
                header: {
                  'content-type': data.contentType,
                  ...header
                },
                data: data.buffer,
                success(res) {
                  if (res.statusCode == 200) {
                    resolve(res.data); if (res.data) {
                      let arr = [];
                      let imgObj = {
                        md5: e,
                        linkType: 'LinkFile',
                        linkProtectType: 'Public',
                        url:
                          app.config.requestCtx + `/file/GetPreViewImage?md5=` + e
                      }
                      arr = [...that.data.imgPics, ...[imgObj]];
                      that.setData({
                        imgPics: arr,
                      });
                    }
                  } else {
                    reject('运行时错误,请稍后再试');
                  }
                }
              })
            })
          } else {
            wx.showToast({
              title: "当前文件已上传,请勿重复操作!",
              icon: 'none',
              duration: 1000,
            })
          }
        })
      }
    });
  },
  // 删除图片
  deleteImg(e) {
    var imgs = this.data.imgPics;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgPics: imgs
    });
  },
  // 预览现场图片
  previewImg(e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    let imgs = [];
    this.data.imgPics.forEach(item => {
      imgs.push(item.url)
    })
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },
  onChange() {
    console.log(this.data.teacherInfo.agree, 12)
    if (this.data.teacherInfo.agree) {
      this.setData({
        'teacherInfo.agree': false,
      });
    } else {
      this.setData({
        'teacherInfo.agree': true,
      });
    }
  },
  //查看教师认证服务
  viewContent() {
    this.setData({
      protocolShow: true,
    });
  },
  onVisibleChange(e) {
    this.setData({
      protocolShow: e.detail.visible,
      reasonTxtShow: e.detail.visible
    });
  },
  //查看为通过原因
  previewReason() {
    this.setData({
      reasonTxtShow: true,
    });
  },
  submit() {
    let that = this;
    if (!that.data.teacherInfo.schoolName) {
      wx.showToast({
        title: "请填写学校名称!",
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (!that.data.teacherInfo.fullName) {
      wx.showToast({
        title: "请填写真实姓名!",
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (!that.data.teacherInfo.courseName) {
      wx.showToast({
        title: "请填写任教课程!",
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (!that.data.teacherInfo.phone) {
      wx.showToast({
        title: "请填写联系电话!",
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (!that.data.teacherInfo.email) {
      wx.showToast({
        title: "请填写邮箱!",
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (that.data.teacherInfo.relevantCertificates.length == 0) {
      wx.showToast({
        title: "请上传工作证!",
        icon: 'none',
        duration: 1000,
      })
      return
    }
    console.log(that.data.teacherInfo.fullName)
    if (that.data.teacherInfo.agree) {
      if (that.data.topicMessageList.length > 0) {
        let dataRequests = tool.UpdateworksDataBytool(
          that.data.worksInfo,
          that.data.topicMessageList,
          that.data.teacherInfo,
          that.data.imgPics
        );
        console.log(dataRequests, 4)
        const data = {
          description: '',
          icon: '',
          id: that.data.topicId,
          topicIdOrRefCode: 'teacherRoleApproval',
          name: that.data.teacherInfo.fullName + '',
          content: '',
          state: 'WaitAudit',
          type: 'teacherRegister',
          newDataRequests: dataRequests.newData,
          updateDataRequests: dataRequests.updateData,
          delDataRequest: {
            ids: []
          }
        }
        let basicInfo = JSON.parse(JSON.stringify(that.data.teacherInfo))
        delete basicInfo.worksInfo
        delete basicInfo.state
        const userInfo = {
          requests: [
            {
              data: JSON.stringify(basicInfo),
              name: that.data.teacherInfo.fullName + '',
              type: 'newTeacherInfo'
            }
          ]
        }
        app.MG.identity.setAppUserInfo(userInfo).then((res) => {
          if (res) {
            app.MG.ugc.updateTopicMessage(data).then(() => {
              if (res !== false) {
                wx.showToast({
                  title: "提交成功!请等待审核...",
                  icon: 'none',
                  duration: 1000,
                })
                that.newGetTeacherInfo()
              }
            })
          }
        })
      } else {
        const data = {
          topicIdOrRefCode: 'teacherRoleApproval',
          name: that.data.teacherInfo.fullName + '',
          content: '',
          state: 'WaitAudit',
          type: 'teacherRegister',
          cmsTypeRefCode: 'jsek_teacherCertification',
          newDataListRequest: tool.worksDataBytool(that.data.worksInfo, that.data.teacherInfo, that.data.imgPics)
        }
        let basicInfo = JSON.parse(JSON.stringify(that.data.teacherInfo))
        delete basicInfo.worksInfo
        delete basicInfo.state
        const userInfo = {
          requests: [
            {
              data: JSON.stringify(basicInfo),
              name: that.data.teacherInfo.fullName + '',
              type: 'teacherInfo'
            }
          ]
        }
        app.MG.identity.setAppUserInfo(userInfo).then((res) => {
          app.MG.ugc.newTopicMessage(data).then(() => {
            if (res !== false) {
              wx.showToast({
                title: "提交成功!请等待审核...",
                icon: 'none',
                duration: 1000,
              })
              that.newGetTeacherInfo()
            }
          })
        })
      }
    } else {
      wx.showToast({
        title: "请同意《教师认证服务条款》!",
        icon: 'none',
        duration: 1000,
      })
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },
  /**