// pageage/project_checking/info/index.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id:"",
        infoData:{}, 
        loadShow:false,
        auditInfo:{},
        opinion:"",
        imageInfoData:[],
        loadShow:false,
        loginName:"",
        status:"0",
        imageList:[],
        minImageList:[],
        request:app.globalData.reqUrl 
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {id} = options
        //获取缓存数据
        wx.getStorage({
        key: 'userinfo',
        success:res=>{
          this.setData({
            id,
            loginName:res.data.loginName
          }) 
          this.getInfo(); 
          this.getAuditinfo();
        }  
        }) 
    },


    /**
     * 获取安全检查详情信息
     * 
     */
    getInfo(){
        let {id} = this.data
        let that = this
        wx.request({
          url: app.globalData.reqUrl+'/wechat/projectProblemmodify/info',
          method:"get",
          data:{
              id:id          
          },
          success(res){
            res = res.data
            if(res.code == 200){
                let urls = [];
                let minUrls = [];
                if(res.data.smarkUrl){
                    res.data.smarkUrl.split(',').forEach(element => {
                        urls.push(that.data.request+element);
                        minUrls.push(that.data.request+element+'.min.jpg');
                      });
                }
                that.setData({
                    infoData:res.data,
                    imageList:urls,
                    minImageList:minUrls,
                    loadShow:false
                })
            }
          }
        })
    },

    getAuditinfo(){
      let {id} = this.data
      let that = this
      wx.request({
        url: app.globalData.reqUrl+'/wechat/projectProblemmodify/queryAuditInfo',
        method:"get",
        data:{
            id:id          
        },
        success(res){
          res = res.data
          if(res.code == 200 && res.data){
              let urls = [];
              if(res.data.fileUrls){
                res.data.fileUrls.split(',').forEach(element => {
                    urls.push(element+'.min.jpg');
                  });
              }
              that.setData({
                auditInfo:res.data,
                auditImgs:urls
              })
          }
        }
      })
    },

    //取消页面
    cancelSaveView(){
      this.returnToPage()
  },

  //保存
  onSubmitSave(){
      this.setData({
          loadShow:true
      })
      let that = this
      let {id,opinion,status,imageInfoData,loginName} =  that.data;
      //数据效验
      if(id==""){
          app.toast("数据异常，请刷新页面重试!")
          that.setData({
              loadShow:false
          })
          return;
      }
      if(opinion==""){
          app.toast("请填写整改说明!")
          that.setData({
              loadShow:false
          })
          return;
      }
      if(imageInfoData.length==0){
          app.toast("请上传整改后图片!")
          that.setData({
              loadShow:false
          })
          return;
      }
      
      let fileUrls = [];
      imageInfoData.forEach(async (item)=>{
          let uploadUrl = app.globalData.uploadUrl+'/common/upload'
          let name = "file" 
          //这里复杂的图片上传，改为同步上传，因为小程序只能上传一张图片
          let obj = await that.syncUploadImage(uploadUrl,item,name);
          fileUrls.push(obj.data.fileName);
          //验证图片上传完毕
          if(fileUrls.length == imageInfoData.length){
              let params = {
                  mainId:id,
                  processState:status,
                  opinion,
                  createUser:loginName,
                  fileUrls:fileUrls.toString()
              }
              wx.request({
                  url: app.globalData.reqUrl + '/wechat/projectProblemmodify/modifyProblem',
                  method:"POST",
                  data:params,
                  header: {
                      "Username": loginName,
                      "Content-Type": "application/json"
                  },
                  success(res){
                      that.setData({
                          loadShow:false
                      })
                      res =res.data
                      if(res.code == 200){
                          app.toast("提交成功!")
                          setTimeout(()=>{
                          wx.redirectTo({
                              url: '../list/index',
                          })
                          },200)
                      }
                  }
                  })
              }
          })
  },

  /**
   * 这里考虑上传图片异步问题，封装为同步
   */
  syncUploadImage(url,uploadFile,name) {
      return new Promise((resolve, reject) => {
          wx.uploadFile({
          url, // 上传的服务器接口地址
          filePath: uploadFile,
          header: {
              "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"      
          },
          name, //上传的所需字段，后端提供
          formData: { user: 'test' },
          success: (res) => {
              // 上传完成操作
              const data = JSON.parse(res.data)
              resolve({
                  data: data
              })
          },
          fail: (err) => {
              //上传失败：修改pedding为reject
              console.log("访问接口失败", err);
              wx.showToast({
              title: "网络出错,上传失败",
              icon: 'none',
              duration: 1000
              });
              reject(err)
          }
          });
      })
  },

      //展示图片
      showImg:function(e){
        var that=this;
        wx.previewImage({
            urls: that.data.imageList,
            current: that.data.imageList[e.currentTarget.dataset.index]
        })
    },

    returnToPage: function () {
        /*关闭当前页面，跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面*/
        wx.redirectTo({
            url: '../list/index',
        })
      },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    //验收描述
    onInputOpinion(e){
      let opinion = e.detail.value
      this.setData({
        opinion
      })
    },

    // list  上传图片
    onImagesArr(e){
      var data = this.data.imageInfoData
      data = e.detail
      this.setData({
          imageInfoData:data
      })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})