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



Page({
	data: { 
		showjz:false,
		remarkTipsShow: false,
		issueTipsShow: false,
		orderInfo:{
      canOperateMap:{

			},
			unitIncreaseNumber:'',
			unitDescribe:'',


		},
		preResultData: {

		},
		ticketList: [],
		workerNotice: [

		],
		orderDisable: true,
		orderDisable1: false,
		activeTab: 1,
    ticketPrelist:[],
		bookOrderInfo: {
			rebuySpeach: '',
			bookTradeNo: ""
		},

		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 {

		}
	},
	getDataRefresh(){
		this.getData(true);
	},
	getData(flag) {
		wx.showLoading({
			title: '加载中...',
		});
		util.request(api.workerServiceOrderDetail, {
			detailId: app.globalData.bookTradeNo,
			noCache:flag?'true':''
		}, 'GET').then(res => {
			wx.hideLoading();
			if (res.errno === 0) {
				console.log(res);
				this.setData({
					orderInfo:res.data,
						preResultData: res.data.preResultData,
						ticketList:res.data.ticketList,
					// ticketList: res.data.ticketList,
					// bookOrderInfo: (res.data.bookOrderInfo)[0],
          ticketPrelist:res.data.ticketPrelist
        });
				this.selectComponent('#tabs').resize();
				if((!res.data.isRead)&&res.data.customerServiceSr){
					this.setData({
						remarkTipsShow:true
					});
				}
			}
		}).catch(err => {
			wx.hideLoading();
		});
	},
tapCusRemark(){
	this.setData({
		remarkTipsShow:true
	});
},
	readRemark(){
		wx.showLoading({
			title: '加载中...',
		});
		util.request(api.hasReadServiceRemark, {
			detailId: this.data.bookTradeNo
		}, 'GET').then(res => {
			wx.hideLoading();
			if (res.errno === 0) {
				this.setData({
					remarkTipsShow:false,

				});
			 wx.showToast({
				 title: '操作成功',
				 icon:'none'
			 })

			}
		}).catch(err => {
			wx.hideLoading();
		});
	},
	copyNum(e) {
	let content=e.currentTarget.dataset.content;
		wx.setClipboardData({
			data: content,
			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() {//打开地图

		let address = this.data.orderInfo.addr;

			let lnglat = this.data.orderInfo.addrDetail.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) {
		this.selectComponent('#tabs').resize();
		if (options) {
			this.setData({
				bookTradeNo: options.bookTradeNo
			});
			app.globalData.bookTradeNo = options.bookTradeNo;
			// this.getData();
		}
		// this.getTips();
	},
	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 () {
		let userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.ofJz == 293) {
			this.setData({
				showjz:true
			})
		}
		this.getData();
	},

	onHide: function () {

	},

	onUnload: function () {

	},


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

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

	},

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

	},
	goIm(){
    wx.navigateTo({
      url: '/pages/chat/im/im'
    });
  },
	supplyRecord(e){
		let bookno = e.currentTarget.dataset.bookno;
    if (bookno.startsWith('JZ')) {
      bookno = bookno.substr(2);
    }
		wx.navigateTo({
			url: '/pages/supplyRecord/supplyRecord?bookno='+bookno,
		});
	},
	getQrCode(e) { //加企微
    let channel = e.currentTarget.dataset.channel;
    let id = e.currentTarget.dataset.id;
    if (channel && channel == '盒马')
      channel = 'hm';
    else channel = 'p';
    wx.navigateTo({
      url: '/pages/upgrade/cp/join?channel=' + channel + '&id=' + id,
    })
	},
	supplyCode(e){
		let bookno = e.currentTarget.dataset.bookno;
    if (bookno.startsWith('JZ')) {
      bookno = bookno.substr(2);
		}
		app.globalData.diffId=0;
		wx.navigateTo({
			url: '/pages/serviceSupply/serviceSupply?bookno='+bookno,
		});
	},
	makeCall(e) {
		let mobile = e.currentTarget.dataset.mobile;
		wx.makePhoneCall({
			phoneNumber: mobile,
		})
	},
	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);
							}
						});
					}
				}
			});

		}
	},
	hideIssue(){
		this.setData({
			issueTipsShow:false
		});
	},
	goCusCheck(){
		wx.navigateTo({
			url: '/pages/new/customerCheck/customerCheck?serviceId='+this.data.bookTradeNo,
		})
	},
	exceotionConf(){
		this.arrivedByMerchant(true);
	},
	arriveCusNew() {
		let nowTime=(new Date()).getTime();
		let serTimeStr=this.data.orderInfo.bookDate+' '+this.data.orderInfo.bookTimeRange.split('-')[0];
		let serTime= (new Date(serTimeStr)).getTime();
		console.log(nowTime,serTime);
		if(nowTime<serTime){
			this.setData({
				issueTipsShow:true
			});

		}else{
      this.arrivedByMerchant()
		}




	},
	arrivedByMerchant(flag){
// wx.showModal({
			// 	title: '',
			// 	content: '确定已经到户？',
			// 	success: res => {
			// 		if (res.confirm) {
				util.request(api.arrivedByMerchantNew, {
					detailId: this.data.orderInfo.detailId,

           isException:flag?'true':''
				}, 'GET').then(res => {
					if (res.errno === 0) {
						wx.showToast({
							title: '操作成功'
						});
						if(flag){
							this.setData({
								issueTipsShow:false
							});
							wx.navigateTo({
								url: '/pages/problem/list/list?bookTradeNo=' + this.data.orderInfo.detailId,
							});
							return false;
						}
						this.setData({
							activeTab: 1
						});
						this.getData(true);

					} 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
						});
					});

				}
			}
		});
	},




})
