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



Page({
  data: {
		mini:'',
		failShow:false,
		receiveShow:false,
		mobile:'',
		sendCodeText:'发送验证码',
		code:'',
		totolTime: 60,
		timer: "",
		isFinished:false,
    workerNotice:[
     
    ],
    orderDisable:true,
    orderDisable1:false,
    activeTab:1,
    ticketList:[],
    bookOrderInfo:{
      receiveStatus:'',
      bookTradeNo:""
    },
    preResultData:{

    },
    bookTradeNo:'',
    comments: {
      ticketId:0,
      ticketSn:'',
      selected:0,//选中的星描述
      selectedDes:'',
      comment: '',
      stars: [{level:1,img: '/static/images/star.png',imgSelected:'/static/images/star@selected.png',checked:false,des:'非常差'},
      {level:2,img: '/static/images/star.png',imgSelected:'/static/images/star@selected.png',checked:false,des:'差'},
      {level:3,img: '/static/images/star.png',imgSelected:'/static/images/star@selected.png',checked:false,des:'一般'},
      {level:4,img: '/static/images/star.png',imgSelected:'/static/images/star@selected.png',checked:false,des:'满意'},
      {level:5,img: '/static/images/star.png',imgSelected:'/static/images/star@selected.png',checked:false,des:'非常满意'},]

    }
  },
  onTabChange(e) {

		this.setData({
			activeTab: e.detail.name,
		});

		if (this.data.activeTab == 1) {

    }else{

    }
  },
  getServiceOrder(){
    wx.showLoading({
      title: '加载中...',
    });
    util.request(jms.ServiceOrderDetail, {
      serviceId:this.data.bookTradeNo
    }, 'GET').then(res=> {
      wx.hideLoading();
      if (res.errno === 0) {
          console.log(res);
          this.setData({
          
            bookOrderInfo:res.data,
          
					});
					if(res.data.receiveStatus==2){
						wx.showToast({
							title: '!抱歉此单已被接',
							icon:'none'
						})
					}
			
			
        
      }
  }).catch(err=>{
      wx.hideLoading();
  });
	},
	receiveOrder(){
   this.setData({
		 receiveShow:true,
		 failShow:false,
		 mobile:'',
		 code:''
	 });
	},
	bindMobile(e){
		this.setData({
			mobile:e.detail.value,
			failShow:false
		
		})
	},
	bindCode(e){
		this.setData({
			code:e.detail.value
		})
	},
	cancelReceive(){
		this.setData({
			receiveShow:false,
		});
	},
	confReceive(){
		if(this.data.mobile==''){
			wx.showToast({
				title: '请输入手机号',
				icon:'none'
			});
			return false;

		}else if(this.data.code==''){
			wx.showToast({
				title: '请输入验证码',
				icon:'none'
			});
			return false;

		}
		wx.showLoading({
      title: '提交中...',
    });
    util.request(jms.ReceiveServiceOrder, {
			serviceId:this.data.bookTradeNo,
			workerTel:this.data.mobile,verifyCode:this.data.code
    }, 'GET').then(res=> {
      wx.hideLoading();
      if (res.errno === 0) {
          console.log(res);
          this.setData({
          
						isFinished:true,
						receiveShow:false
          
					});
					wx.showToast({
						title: '接单成功',
					});
					setTimeout(()=>{	this.getServiceOrder();},2000)
				
				
			}else if(res.errno === 301)
			{
				wx.showModal({
					title: '提示',
					content: '您还未注册，是否现在去注册？',
					// showCancel:false,
					complete: (res) => {
						if (res.cancel) {
							
						}
				
						if (res.confirm) {
						wx.navigateTo({
							url: '/pages/temp/register/register?fraName='+this.data.bookOrderInfo.fraName+'&fraId='+this.data.bookOrderInfo.fraId,
						})
						}
					}
				})
			}else{
				wx.showModal({
          title: '提醒',
          content: res.errmsg,
					showCancel: false,
					confirmText:'知道了'
        });
			}
  }).catch(err=>{
      wx.hideLoading();
  });
	},
 copyNum(){
  let bookno=e.currentTarget.data.set.bookno;
  console.log(bookno);
wx.setClipboardData({
 data: bookno,
 success: function (res) {

   wx.showToast({
     title: '复制成功',
     icon: 'none',
     duration: 2000
   });
 }
})
 },
 callUp(e){
  let status=e.currentTarget.dataset.status;
  let phone=e.currentTarget.dataset.phone;
  if(status=='待上门'){
     wx.makePhoneCall({
         phoneNumber: phone
       });
  }
 },
 openMap(e){//打开地图
  let status=e.currentTarget.dataset.status;
  let address=e.currentTarget.dataset.address;
  if(status=='待上门'){
    let lnglat=e.currentTarget.dataset.lnglat.split(',');
    let lng='';
    let lat="";
    if (lnglat.length>0){
      lng=Number(lnglat[0]);
      lat=Number(lnglat[1]);
    }
   console.log(lng,lat);
     wx.openLocation({       
          latitude: lat,  
          longitude: lng,
        //   name: address,
          address:address,
          scale: 28
        }) ;
  }
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 
      // if(options){
      //   this.setData({
      //     bookTradeNo:options.bookTradeNo
      //   });
      //   app.globalData.bookTradeNo=options.bookTradeNo;
      //   this.getData();
      // }
			// this.getTips();
			console.log(options);
			if (options.scene) {
				var scene = decodeURIComponent(options.scene);
				console.log(scene);
				this.setData({
					bookTradeNo:scene
				});
				this.getServiceOrder();
			}else if(options.id){
				this.setData({
					bookTradeNo:options.id
				});
				this.getServiceOrder();
			}

			if(options.mini){
				this.setData({
					mini:options.mini
				});
			}

  },
  getTips(){
    let userInfo = wx.getStorageSync('userInfo');
    util.request(api.getWorkerTips, {
      workerNo:userInfo.workerNo
    }, 'GET').then(res=> {
      if (res.errno === 0) {
          console.log(res);
          this.setData({
            workerNotice:res.data
          });
         
      }
  }).catch(err=>{
     
  });
  },
  onReachBottom() {
    // if (this.data.totalPages > this.data.page) {
    //   this.setData({
    //     page: this.data.page + 1
    //   });
    //   this.getGoodsList();
    // } else {
    //   wx.showToast({
    //     title: '没有更多商品了',
    //     icon: 'none',
    //     duration: 2000
    //   });
    //   return false;
    // }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
    wx.hideHomeButton();
  },
 
  onHide: function () {
		clearInterval(this.data.timer);
  },

  onUnload: function () {
		
  },
  

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
   
  },
  
  /**
   * 用户点击右上角分享
   */
	onShareAppMessage: function () {
	
    return {
      title: '服务单详情',
      path: '/pages/upgrade/tempDetail/tempDetail?id=' + this.data.bookTradeNo,
    
    }
   
  },
  makeCall(e) {
    let mobile = e.currentTarget.dataset.mobile;
    wx.makePhoneCall({
      phoneNumber: mobile,
    })
	},
	sendCode: function() {
		if(this.data.sendCodeText!="发送验证码"){
			return false;
		}
		if (this.data.mobile == "") {
		wx.showToast({
			title: '请输入手机号',
			icon:'none'
		});
			return false;
		} else if (!/^1\d{10}$/.test(this.data.mobile)) {
			wx.showToast({
				title: '请输入正确的手机号码',
				icon:'none'
			});
				return false;
	
		} else {
			this.codeTimer();
			wx.showLoading({
				title: '发送中...',
			});
		
			util.request(jms.sendVerifyCode, {
				serviceId:this.data.bookTradeNo,
				workerTel:this.data.mobile
			}, 'GET').then(res => {

				  wx.hideLoading();
      if (res.errno === 0) {
				wx.showToast({
					title: '验证码已发送到您的手机',
					icon:'none'
				})
				} else  {
					this.setData({
						failShow:true
					});
					wx.showToast({
						title: res.errmsg,
						icon:'error'
					})
					
				}
			}).catch(err=>{
				wx.hideLoading();
				wx.showToast({
					title: '发送失败',
					icon:'error'
				})
			});
		}
	},
	codeTimer: function() {
		this.setData({
			sendCodeText:this.data.totolTime + " S"
		})
	
 let timer = setInterval(() => {
	 this.setData({
		totolTime:this.data.totolTime-1
	 });
	 this.setData({
		sendCodeText:this.data.totolTime + " S"
	})
		
			if (this.data.totolTime == 0) {
				this.setData({
					sendCodeText:"发送验证码",
					totolTime:60
				})
		
				clearInterval(this.data.timer);
			}
		}, 1000);
		this.setData({
			timer:timer
		})
	},
  goPre(e) { //去预检
    let id = e.currentTarget.dataset.id;
    let bookNo = e.currentTarget.dataset.bookno;
    let phone = e.currentTarget.dataset.userphone;
    wx.navigateTo({
      url: '/pages/pre/previewing/index?id=' + id+'&bookNo='+bookNo+'&phone='+phone,
    })
  },
  editPre(e) {
    let bookNo = e.currentTarget.dataset.bookno;
    wx.navigateTo({
      url: '/pages/pre/previewing/index?bookNo=' + bookNo,
    });
  },
  goProblemList() {
    // this.setData({
    //   navigateType: 1
    // })
    wx.navigateTo({
      url: '/pages/problem/list/list?bookTradeNo='+this.data.bookTradeNo,
    })
  },
  arriveCus(){
    if(this.data.bookOrderInfo.status=='待上门'){
      wx.showModal({
        title: '',
        content: '确定已经到门？',
        success: res=>{
          if (res.confirm) {
            util.request(api.arrivedByMerchant, {
              bookTradeNo: this.data.bookTradeNo,
              workerNo:this.data.bookOrderInfo.workerNo
            }, 'GET').then(res=> {
              if (res.errno === 0) {
                wx.showToast({
                  title: '操作成功'
                });
                this.setData({
                 activeTab:1
                });
                this.getData();
             
              } else {
                util.showErrorToast(res.errmsg);
              }
            });
          }
        }
      });

    }
  },

  finishOrder(){
    if(this.data.bookOrderInfo.status=='待履约'||this.data.bookOrderInfo.status=='已预约'){
      wx.showModal({
        title: '',
        content: '确定服务完成？',
        success: res=>{
          if (res.confirm) {
            util.request(api.confirmBookTrade, {
              bookTradeNo: this.data.bookTradeNo,
             
            }, 'GET').then(res=> {
              if (res.errno === 0) {
                wx.showToast({
                  title: '操作成功'
                });
                this.setData({
                 activeTab:1
                });
                this.getData();
             
              } else {
                util.showErrorToast(res.errmsg);
              }
            });
          }
        }
      });

    }
  },
  goCancel(e) { //取消报备 
    let that = this;
    let sn = e.currentTarget.dataset.sn;
    wx.showModal({
      title: '取消报备',
      content: '确定要取消此报备吗？',
      showCancel: true, //是否显示取消按钮
      cancelText: "否", //默认是“取消”
      cancelColor: 'skyblue', //取消文字的颜色
      confirmText: "是", //默认是“确定”
      confirmColor: 'skyblue', //确定文字的颜色
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          util.request(api.ProblemCancel, {
            'ticketSn': sn
          }).then(res => {
            let list = that.data.ticketList
            list.forEach(item => {
              if (item.ticketSN == sn) {
                item.statusDesc = "作废";
                item.status = 3;
              }
            })
            that.setData({
              ticketList: list
            })
            wx.showToast({
              title: '已取消成功',
              duration: 3000
            });
          })
        }
      },
      fail: function (res) {}, //接口调用失败的回调函数
      complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
    })

  },
  goUrge(e) { //催促办理 
    let sn = e.currentTarget.dataset.sn;
    let that = this;
    wx.showLoading();
    util.request(api.ProblemUrge, {
      ticketSn: sn
    }).then(function (res) {
      wx.hideLoading();
      if (res.errno === 0) {
        //设置为已催办
        let list = that.data.ticketList;
        list.forEach(item => {
          if (item.ticketSN == sn) {
            item.statusDesc = "处理中-升级"
          }
        })
        that.setData({
          ticketList: list
        })
        wx.showToast({
          title: '已催促负责人尽快办理',
          icon:'none',
          duration: 3000
        });
      }
    });
  },
  goComment(e) { //去评论
    // wx.pageScrollTo({
    //   scrollTop: 0
    // });

    let id = e.currentTarget.dataset.id;
    let sn = e.currentTarget.dataset.sn;

    this.setData({
      myqr_show: true,
      myqr_blur: 0,
      'comments.ticketId':id, 
      'comments.ticketSn':sn
    })
  },
  clickStar(e){ 
    let level = e.currentTarget.dataset.level;
    console.info(level)
    let stars=this.data.comments.stars;
    let des=''
    stars.forEach(item=>{
      if(item.level<=level) {
        item.checked=true;
        des=item.des
      }else{
        item.checked=false;
      }
    })
    this.setData({
      'comments.stars':stars, 
      'comments.selectedDes':des,
      'comments.selected':level
    })
  },
  onClickHide(){

  },
  qrtouchstart: function () {
    this.setData({
      myqr_blur: 0,
      myqr_show: false
    });
  },
  bindCommentRemark(e){
    this.setData({
      'comments.comment':e.detail.value
    }) 
  },
  goSaveCommnet(){//保存评论
    let that=this;
    if(that.data.comments.selected==0){
      wx.showToast({
        title:'请选择满意度',
        icon:'none',
        duration:2000
      })
      return;
    }

    if(that.data.comments.selected<4&&that.data.comments.comment==''){
      wx.showToast({
        title:'请填写有待提升的地方',
        icon:'none',
        duration:2000
      })
      return;
    }

    wx.showModal({
      title: '提示',
      content: '确定要评价此处理过程吗？提交后 无法修改',
      success: function (sm) {
        if (sm.confirm) {
          wx.showLoading(); 
          let data={
            ticketId:that.data.comments.ticketId,
            ticketSn:that.data.comments.ticketSn,
            comment:that.data.comments.comment,
            star:that.data.comments.selected
          }
          util.request(api.ProblemComment,data,"POST").then(res=>{
            wx.hideLoading();
            if(res.errno==0){
         
              let list=that.data.ticketList;
              list.forEach(item=>{
                if(item.ticketSN==that.data.comments.ticketSN){
                  item.isCommented=true;
                }
              })
              let comments=that.data.comments;
              comments.selected=0;
              comments.selectedDes="";
              comments.comment="";
              comments.stars.forEach(star=>{
                star.checked=false;
              })
              that.setData({ 
                myqr_blur: 0,
                myqr_show: false,
                comments:comments,
                ticketList:list
              });
              wx.showToast({
                title: '评价成功',
                duration: 3000 
              });
            }else{
              wx.showToast({
                title: res.errmsg,
                icon:'none',
                duration: 3000
              });
            }
          

          }).catch(res=>{ 
              wx.hideLoading();
              wx.showToast({
                title: res.errmsg,
                icon:'none',
                duration: 3000
              });
            });
          
        }
      }
    });
	},
	backMini(){
		wx.navigateBackMiniProgram({
      success(res){
				console.log('返回加盟商小程序');
				console.log(res);
			}
		});
	}




})