const util = require("../../../utils/util");
const api = require('../../../api/api.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorService: '#85868A',
    colorChange: '#85868A',
    name: '',
    problem: {
      id: 0,
			name: '',
			tempMobile:'',
      mobile: '',
      remark: '',
      picUrls: [],
      bookTime: "选择服务日期-时间",
      changeTime: '选择服务日期-时间',
      city: '',
      bookTradeNo: ''
    },
    problemInfo: {},
    files: [],
    date: [
      ["2021-02-01", "2021-02-02", "2021-02-03"],
      ["2021-02-04", "2021-02-05", "2021-02-06"]
    ],
    multiIndex: [0, 2, 0],
    multiChangeIndex: 0,
    oneHour: ["08:30-09:30", "10:45-11:45", "13:00-14:00", "14:45-15:45", "17:30-18:30", "17:30-19:30", "20:00-21:00"],
    twoHour: ["08:00-10:00", "13:00-15:00", "16:00-18:00"],
    threeHour: ["08:00-11:00", "12:00-15:00", "13:00-16:00", "17:00-20:00", "17:30-20:30"],
    fourHour: ["08:00-12:00", "13:45-17:45", "14:00-18:00", "17:00-21:00", "18:00-22:00"],
    sixHour: ["08:00-14:00", "13:00-19:00"],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.info(options)
    let that = this
    that.setData({
      'problem.id': options.id,
      name: options.name,
    })
    that.initServiceDate();
    that.getProblemInfo(options.id);

    if (options.bookTradeNo) {
      that.setData({
        'problem.bookTradeNo': options.bookTradeNo
      })
      that.getBookTradeInfo();
    }
  },
  getProblemInfo(id) {
    let that = this
    wx.showLoading();
    util.request(api.ProblemInfo, {
      id: id
    }).then(function (res) {
      wx.hideLoading();
      console.info(res.data)
      if (res.errno === 0) {
        that.setData({
          problemInfo: res.data
        });
      }
    });
	},
	maskPhone(phone) {
		if (!phone || phone.length !== 11) return phone; // 确保电话号码有效且长度为11位
		return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
	},
  getBookTradeInfo() {
    let that = this
    if (that.data.problem.bookTradeNo) {
      util.request(api.BookHmTradeInfo, {
        bookTradeNo: that.data.problem.bookTradeNo
      }).then(function (res) {
        if (res.errno === 0) {
          var p = that.data.problem;
          p.name = res.data.userName;
					p.mobile = res.data.userPhone;
					p.tempMobile=res.data.userPhone;//that.maskPhone(res.data.userPhone);
					if(that.data.problem.bookTradeNo.indexOf("JZ")==-1){
						p.tempMobile=that.maskPhone(res.data.userPhone);
					}
          p.bookTime = res.data.bookTime;
          p.changeTime = '选择服务日期-时间',
            that.setData({
              problem: p,
              colorService: '#333'
            });
        }
      });
    }
  },
  initServiceDate() { //构造服务日期及时间段
    var date = [];
    var now = util.formatDate(new Date());
    for (var i = 0; i < 7; i++) {
      date.push(util.mathChangeDate(now, '+', i, true));
    }
    var data = [];
    data.push(date, ['1小时', '2小时', '3小时', '4小时', '6小时'], this.data.threeHour);
    console.info(data)
    this.setData({
      date: data
    })

  },

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

  },
  //服务时间段
  bindMultiPickerChange(e) {
    console.info(e)
    var date = this.data.date[0][e.detail.value[0]]
    var time = this.data.date[2][e.detail.value[2]]
    this.setData({
      'problem.bookTime': date + ' ' + time,
      colorService: '#333'
    })
  },
  bindMultiPickerColumnChange(e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let that = this
    var data = that.data.date;
    if (e.detail.column == 1) { //修改时间段列
      switch (e.detail.value) {
        case 0: //"1小时"
          data[2] = that.data.oneHour;
          break;
        case 1: //"2小时"
          data[2] = that.data.twoHour;
          break;
        case 2: //"3小时"
          data[2] = that.data.threeHour;
          break;
        case 3: //"4小时"
          data[2] = that.data.fourHour;
          break;
        case 4: //"6小时"
          data[2] = that.data.sixHour;
          break;
      }

      this.setData({
        date: data
      })
    }

  },
  bindNeedFollowed(e){//是否需要客服介入
    console.info(e.detail.value)
    this.setData({
      'problem.isNeedFollowed': e.detail.value
    })
  },
  //期望服务时间
  bindChangePickerChange(e) {
    var date = this.data.date[0][e.detail.value[0]]
    var time = this.data.date[2][e.detail.value[2]]
    this.setData({
      'problem.changeTime': date + ' ' + time,
      colorChange: '#333'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      'problem.city': app.globalData.city
    })

  },
  saveProblem() {
    console.info("handle saveProblem")
    let that = this
    if (that.data.problem.tempMobile.length != 11 || that.data.problem.tempMobile.startsWith("1") == false) {
      wx.showToast({
        title: '请输入正确手机号',
        duration: 3000,
        icon:'none'
      });
      return;
		}
		if(that.data.problem.tempMobile.indexOf("*")==-1){//用输入后的手机
			this.setData({
				'problem.mobile': that.data.problem.tempMobile
			})
		}

    if (that.data.problem.bookTime == '选择服务日期-时间') {
      wx.showToast({
        title: '请选择服务时间',
        duration: 3000,
        icon:'none'
      });
      return;
    }

    if (that.data.problemInfo.isChangeTime && that.data.problem.changeTime == '选择服务日期-时间') {
      wx.showToast({
        title: '请选择期望改约的服务时间',
        duration: 3000,
        icon:'none'
      });
      return;
    }
    if (that.data.problemInfo.isNeedPic && that.data.problem.picUrls.length == 0) {
      wx.showToast({
        title: '请上传照片',
        duration: 3000,
        icon:'none'
      });
      return;
    } 
console.log(that.data.problem);
 
    wx.showModal({
      title: '提示',
      content: '确定要报备此问题吗？',
      success: function (sm) {
        if (sm.confirm) {
          wx.showLoading();
          util.request(api.ProblemAdd, that.data.problem, "POST").then(function (res) {
            wx.hideLoading();
            let msg=typeof that.data.problemInfo.alertMsg=='undefined'? '问题报备成功':that.data.problemInfo.alertMsg;
            if (res.errno === 0) { 
              wx.showModal({
                title: '报备成功',
                content: msg,
                showCancel: false,//是否显示取消按钮 
                confirmText:"确定",//默认是“确定”
                confirmColor: 'skyblue',//确定文字的颜色
                success: function (res) {
                   if (res.cancel) {
                      //点击取消,默认隐藏弹框
                   } else {
                      //点击确定
                      // wx.switchTab({
                      //   url: '/pages/problem/index',
                      // }) 
                      // wx.navigateTo({
                      //   url: '/pages/new/ticketDetail/ticketDetail?bookTradeNo=' + that.data.problem.bookTradeNo,
                      // })
                      wx.navigateBack({
                        delta: 2,
                      })
                   }
                }, 
             })  
            } else {
              wx.showToast({
                title: res.errmsg,
                duration: 3000
              });
            }
          });

        } 
      }
    })

  },
  bindRemark(e) {
    this.setData({
      'problem.remark': e.detail.value
    })
  },
  bindName(e) {
    this.setData({
      'problem.name': e.detail.value
    })
  },
  bindMobile(e) {
    this.setData({
      'problem.tempMobile': e.detail.value
    })
  },
  chooseImage: function (e) {
    if (this.data.files.length >= 5) {
      util.showErrorToast('只能上传五张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
        console.info(res.tempFilePaths[0])
        //that.compressImage(res.tempFilePaths[0], (res1) => {
        that.upload(res)
        //})

      }
    })
  },
  upload: function (res) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload(),
      filePath: res.tempFilePaths[0],
      name: 'file',
      success: function (res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          var url = _res.data.fileUrl
          var pics = that.data.problem.picUrls;
          pics.push(url);
          that.setData({
            hasPicture: true,
            'problem.picUrls': pics
          })
        }
      },
      fail: function (e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })

  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  compressImage(path, callback) {
    var that = this;
    //获取图片信息
    wx.getImageInfo({
      src: path,
      success: function (res) {
        //如果图片小于1200宽度 不压缩 
        if (res.width < 1200) {
          callback(res.path);
          return
        }
        console.info("开始压缩")
        var ctx = wx.createCanvasContext('photo_canvas'); // 创建画布
        var towidth = 1200; //设置canvas尺寸，按宽度500px的比例压缩
        var toheight = Math.trunc(1200 * res.height / res.width); //根据图片比例换算出图片高度
        that.setData({
          canvasHeight: toheight
        });
        console.info("开始压缩2")
        ctx.drawImage(path, 0, 0, res.width, res.height, 0, 0, towidth, toheight);

        console.info("开始压缩3")
        ctx.draw(false, function () {
          wx.canvasToTempFilePath({
            canvasId: 'photo_canvas',
            fileType: "jpg",
            quality: 0.8,
            success: function (res) {
              console.log(res.tempFilePath);
              callback(res.tempFilePath);
            },
            fail: function (res) {
              console.info(res)
            }
          }, this)
        })

        console.info("开始压缩4")
      }
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

  },

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

  }
})