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


Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEdit: false,
    editBookNo: '',
    canvasHeight: 0,
    base: {
      category: [],
      device: [],
      position: [],
      problem: []
    }, //基础数据 
    selected: {
      device: [],
      position: [],
      problem: [],
    },
    isShow: false,
    pres: [],
    //本次新增 临时选中项
    id: '',
    categoryId: {
      id: 0,
      name: ''
    },
    deviceId: {
      id: 0,
      name: ''
    },
    positionId: {
      id: 0,
      name: ''
    },
    problem: [],
    picUrls: [],
    files: [],
    memo: '',
    bookNo: '',
		mobile: '',
		tempMobile:'',
    captcha: '',
    opeate: 'add',
    isConfirm: false, //是否为用户确认界面
    isAgree: false, //是否同意以上条款
    userInfo: {},
    servantName:''//计师名称
  },
  getCategory() {
    let that = this
    util.request(api.PreCategory, {}, "GET").then(res => {
      that.setData({
        base: res.data
      })
    })

  },
  bindCategory(e) {
    let that = this
    that.setData({
      categoryId: {
        id: e.currentTarget.dataset.id,
        name: e.currentTarget.dataset.name
      }
    })
    //筛选设备
    var device = [];
    that.data.base.device.forEach(item => {
      if (item.categoryId == that.data.categoryId.id)
        device.push(item)
    })
    //位置
    var position = that.data.base.position;
    console.info(position)
    // that.data.base.position.forEach(item => {
    //   if (item.categoryId == that.data.categoryId.id)
    //     position.push(item)
    // })
    //问题
    var problem = [];
    that.data.base.problem.forEach(item => {
      if (item.categoryId == that.data.categoryId.id) {
        item.checked = false
        problem.push(item)
      }
    })

    that.setData({
      'selected.device': device,
      'selected.position': position,
      'selected.problem': problem,
      deviceId: {},
      positionId: {},
      problem: []
    })

  },
  bindDevice(e) {
    let that = this
    that.setData({
      deviceId: {
        id: e.currentTarget.dataset.id,
        name: e.currentTarget.dataset.name
      }
    })
  },
  bindPosition(e) {
    let that = this
    that.setData({
      positionId: {
        id: e.currentTarget.dataset.id,
        name: e.currentTarget.dataset.name
      }
    })
  },
  bindQuestion(e) { //多选
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var problem = [];
    var selectedQuestion = this.data.selected.problem;
    var isContain = false;
    this.data.problem.forEach(item => {
      if (item.id == id) {
        isContain = true;
      }
    })

    if (!isContain) {
      problem = this.data.problem;
      problem.push({
        id: id,
        name: name
      });
    } else { //如果已经选中 从中删除
      this.data.problem.forEach(item => {
        if (item.id != id)
          problem.push(item)
      })
    }

    //实际选中项 
    selectedQuestion.forEach(item => {
      if (item.id == id) {
        item.checked = !isContain;
      }
    })

    this.setData({
      problem: problem,
      'selected.problem': selectedQuestion
    })
  },
  bindAgreeChange(e) {
    this.setData({
      isAgree: e.detail.value
    })
  },
  addPre() {
    this.setData({
      id: Math.floor((Math.random() * 100000)),
      isShow: true,
      categoryId: {},
      deviceId: {},
      positionId: {},
      problem: [],
      files: [],
      picUrls: [],
      memo: '',
      opeate: 'add',
      'selected.device': [],
      'selected.position': [],
      'selected.problem': [],
    })
    console.info(this.data.selected.problem)
  },
  confirmAdd() {
    let that = this
    //console.info(that.data.categoryId)
    console.info(that.data.deviceId.id)
    if (that.data.categoryId.id == 0) {
      wx.showToast({
        title: '请选择服务项',
        icon: 'none',
        duration: 2000
      });
      return
    }
    if (that.data.selected.device.length > 0 && that.data.deviceId.id == undefined) {
      wx.showToast({
        title: '请选择设备',
        icon: 'none',
        duration: 2000
      });
      return
    }
    if (that.data.problem.length == 0) {
      wx.showToast({
        title: '请选择存在问题',
        icon: 'none',
        duration: 2000
      });
      return
    }
    // 如果问题为其他,则图片和备注必填
    let isOther = this.data.problem.some(item => {
      return item.name == '其他'
    });
    if (isOther && (this.data.memo == '' || this.data.files.length == 0)) {
      wx.showToast({
        title: '请上传图片和填写问题',
        icon: 'none',
        duration: 2000
      });
      return
    }
    var pre = {
      id: that.data.id,
      categoryId: that.data.categoryId,
      deviceId: that.data.deviceId,
      positionId: that.data.positionId,
      problem: that.data.problem,
      files: that.data.files,
      picUrls: that.data.picUrls,
      memo: that.data.memo
    }

    var pres = that.data.pres;
    if (that.data.opeate == 'update') { //修改时 将旧的选项删除
      for (var i = 0; i < pres.length; i++) {
        if (pres[i].id == pre.id) {
          pres.splice(i, 1);
          break;
        }
      }
    }
    pres.push(pre);

    that.setData({
      pres: pres,
      isShow: false
    })
  },
  cancelAdd() {
    this.setData({
      isShow: false,
      categoryId: {},
      deviceId: {},
      positionId: {},
      problem: [],
      files: [],
      picUrls: []
    })
  },
  modifyPre(e) {
    let that = this
    var id = e.currentTarget.dataset.id;
    that.data.pres.forEach(item => {
      if (item.id == id) {
        that.setData({
          id: item.id,
          categoryId: item.categoryId,
          deviceId: item.deviceId,
          positionId: item.positionId,
          problem: item.problem,
          files: item.files,
          picUrls: item.picUrls,
          memo: item.memo,
          isShow: true,
          opeate: 'update'
        });

      }
    });

    //筛选设备
    var device = [];
    this.data.base.device.forEach(item => {
      if (item.categoryId == this.data.categoryId.id)
        device.push(item)
    })
    //位置
    var position = this.data.base.position;
    // this.data.base.position.forEach(item => {
    //   if (item.categoryId == this.data.categoryId.id)
    //     position.push(item)
    // })
    //问题
    var problem = [];
    let checkedProblem = this.data.problem.map(i => {
      return i.id
    });
    //console.log(checkedProblem);
    this.data.base.problem.forEach(item => {
      if (item.categoryId == this.data.categoryId.id) {
        item.checked = false;
        if (checkedProblem.indexOf(item.id) > -1) {
          item.checked = true;
        }
        problem.push(item)
      }
    })

    this.setData({
      'selected.device': device,
      'selected.position': position,
      'selected.problem': problem,

    });


  },
  deletePre(e) {
    let that = this
    var id = e.currentTarget.dataset.id;
    var pres = []

    that.data.pres.forEach(item => {
      if (item.id != id)
        pres.push(item)
    })

    that.setData({
      pres: pres
    })
  },
  confirmPre() { //下一步用户确认
    if (this.data.mobile.length < 11 || this.data.bookNo.length <= 0) {
      wx.showToast({
        title: '请填写工单号和手机号',
        icon: 'none',
        duration: 2000
      });
      return
    }
    if (this.data.categoryId.id == 0) {
      wx.showToast({
        title: '请选择服务项和内容',
        icon: 'none',
        duration: 2000
      });
      return
    }


    this.setData({
      isConfirm: true
    })

  },
  savePre() { //保存预检单
    let that = this
    // if (that.data.isAgree == false) {
    //   wx.showToast({
    //     title: '请选择服务条款',
    //     icon: 'none',
    //     duration: 2000
    //   });
    //   return
    // }

    if (that.data.captcha.length == 0) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    var items = [];
    that.data.pres.forEach(item => {
      var problem = [];
      if (item.problem.length > 0) {
        item.problem.forEach(element => {
          problem.push(element.id)
        })
      }
      var item = {
        categoryId: item.categoryId.id,
        positionId: item.positionId.id,
        deviceId: item.deviceId.id,
        picUrls: item.picUrls,
        problems: problem,
        memo: item.memo
      }
      items.push(item);
    })
    var pre = {
      mobile: that.data.mobile,
      bookNo: that.data.bookNo,
      captcha: that.data.captcha,
      items: items
    }
    
    wx.showLoading({
      title: '保存中',
    })

    if (this.data.isEdit) {
      // 编辑
      util.request(api.PreUpdate, pre, "POST").then(res => {
        wx.hideLoading();

        if (res.errno == 0) {
          wx.showModal({
            title: '提醒',
            content: '预检单编辑成功',
            showCancel: false, //是否显示取消按钮 
            success: function (res) {
              wx.redirectTo({
                // url: '/pages/pre/list/preList',
                url: '/pages/new/ticketDetail/ticketDetail?bookTradeNo=' + that.data.bookNo,
              })
            }
          })
        } else
          wx.showToast({
            title: res.errmsg,
            icon: 'none',
            duration: 2000
          });

      }).catch(res => {
        wx.hideLoading();
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 2000
        });
      })
    } else {
      // 保存
      util.request(api.PreSave, pre, "POST").then(res => {
        wx.hideLoading();
        if (res.errno == 0) {
          wx.showModal({
            title: '提醒',
            content: '预检单提交成功',
            showCancel: false, //是否显示取消按钮 
            success: function (res) {
              wx.redirectTo({
                // url: '/pages/pre/list/preList',
                url: '/pages/new/ticketDetail/ticketDetail?bookTradeNo=' + that.data.bookNo,
              })
            }
          })
        } else
          wx.showToast({
            title: res.errmsg,
            icon: 'none',
            duration: 2000
          });

      }).catch(res => {
        wx.hideLoading();
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 2000
        });
      })


    }


  },
  bindMemo(e) {
    this.setData({
      memo: e.detail.value
    })
  },
  bindBookNo(e) {
    this.setData({
      bookNo: e.detail.value
    })
  },
  bindMobile(e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  bindcaptchaInput(e) {
    this.setData({
      captcha: e.detail.value
    })
  },
  getCaptcha() {
    console.info(this.data.mobile)
    if (this.data.mobile.length != 11 || this.data.mobile.startsWith("1") == false) {
      wx.showToast({
        title: '请输入正确手机号',
        duration: 3000
      });
      return;
		}
		
		if (this.data.mobile.indexOf("*")!=-1) {
			wx.showToast({
        title: '请输入正确手机号',
        duration: 3000
			});
			return;
		}

    let that=this;
    var items = [];
    that.data.pres.forEach(item => {
      var problem = [];
      if (item.problem.length > 0) {
        item.problem.forEach(element => {
          problem.push(element.id)
        })
      }
      var item = {
        categoryId: item.categoryId.id,
        categoryName:item.categoryId.name,
        positionId: item.positionId.id,
        positionName:item.positionId.name,
        deviceId: item.deviceId.id,
        deviceName:item.deviceId.name,
        picUrls: item.picUrls,
        problems: problem,
        memo: item.memo
      }
      items.push(item);
    })
    var pre = {
      mobile: that.data.mobile,//
      bookNo: that.data.bookNo,
      captcha: that.data.captcha,
			items: items,
			userName:that.data.userName,
			address:that.data.address
			
    }

    util.request(api.AuthCaptchaPre, pre, "POST").then(res => {
      if (res.errno == 0)
        wx.showToast({
          title: '验证码发送成功',
          duration: 3000
        });
      else
        wx.showToast({
          title: res.errmsg,
          duration: 3000
        });
    }).catch(res => {
      wx.showToast({
        title: res.errMsg,
        icon: 'error',
        duration: 3000
      });
    })

  },
  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)
        });
        that.compressImage(res.tempFilePaths[0], (res1) => {
          that.upload(res1)
        })

      }
    })
  },
  upload: function (path) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload(),
      filePath: path, //res.tempFilePaths[0],
      name: 'file',
      success: function (res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          var url = _res.data.fileUrl
          that.data.picUrls.push(url)
          that.setData({
            hasPicture: true,
            picUrls: that.data.picUrls
          })
        }
      },
      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) {
        //如果图片小于800宽度 不压缩 
        if (res.width < 1200) {
          callback(res.path);
          return
        }
        var ctx = wx.createCanvasContext('photo_canvas'); // 创建画布
        var towidth = 1200; //设置canvas尺寸，按宽度500px的比例压缩
        var toheight = Math.trunc(1200 * res.height / res.width); //根据图片比例换算出图片高度
        that.setData({
          canvasHeight: toheight
        });
        ctx.drawImage(path, 0, 0, res.width, res.height, 0, 0, towidth, toheight);
        ctx.draw(false, function () {
          wx.canvasToTempFilePath({
            canvasId: 'photo_canvas',
            fileType: "jpg",
            quality: 0.8,
            success: function (res) {
              console.log(res.tempFilePath);
              callback(res.tempFilePath);
            }
          }, this)
        })
      }
    });
  },
  getPreDetail() {
    util.request(api.PreDetail, {
      bookNo: this.data.editBookNo
    }, "GET").then(res => {
      let list = res.data.items;
      let pres = [];
      list.forEach(item => {
        let obj = {
          deviceId: {
            id: item.deviceId,
            name: item.deviceName
          },
          categoryId: {
            id: item.categoryId,
            name: item.categoryName
          },
          positionId: {
            id: item.positionId ? item.positionId : 0,
            name: item.positionName ? item.positionName : ''
          },
          problem: item.problemsNamelist,
          memo: item.memo,
          files: item.picUrls,
          picUrls: item.picUrls
        }
        pres.push(obj);
      });

      this.setData({
        bookNo: res.data.bookNo,
        mobile: res.data.mobile,
        pres: pres,

      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
	maskPhone(phone) {
		if (!phone || phone.length !== 11) return phone; // 确保电话号码有效且长度为11位
		return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
	},
  onLoad: function (options) {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo)
      this.setData({
        userInfo: userInfo 
      }); 
    let phone = options.phone;
    if (options.bookNo) {
      if (phone) {
				if(options.bookNo.indexOf("JZ")==-1){ 
					 this.setData({ 
						tempMobile: this.maskPhone(phone), 
					});
				}
        this.setData({ 
          bookNo: options.bookNo,
					mobile: phone
        });
      } else {
        this.setData({
          isEdit: true,
          editBookNo: options.bookNo 
        });
      }

    }
    if (this.data.isEdit) {
      // 加载编辑预检单信息
      this.getPreDetail();
    }
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCategory();
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})