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');
import moment from 'moment'



Page({
  data: {
		showjz:false,
		isSearchResult:false,
		isMonthCalender:false,
		isHistoryMonth:false,
		calendarBoardShow:false,
		schedueBoardShow:false,
		serviceOrderList:[],
		totalPage:1,
		page:1,
		weather:{},
		orderType:1,
		today: util.chineseDate(new Date()),
		todayTag: util.formetdate(new Date()),
    currentDay: util.formetdate(new Date()),
		currentMonth: moment(new Date()).format('YYYY-MM'),
		dayTeamName:'',
		dayTeam:[],
		leaveList:[],
		avgDay:'',
		futureThirtyDays:[],
		futureThirtyDaysStr:'',
		futureThirtyDaysEnd:'',
		futureOrderCount:'',
		monthOrderCount:[],
		lastMonthCount:'',
		


    timer: "",
    dayCalendar: {
      bookTradeNo: '',
      workerNo: '',
      star: 0,
      evalMasterShow: false,
      masterComment: '',
      evalDiscipleShow: false,
      discipleComment: '',
      radioDisciple: '通过',
      askForLeaveDTOS: [],
      workerOrderInfoDTOList: [],
      leaveNum: '',
      finishWorkerOrder: '',
      questionNum: '',
      looseOrder: '',
      looseOrderCount: '',
      cycleOrder: '',
      cycleOrderCount: '',
      rebuyNum: '',
      looseRebuyNum: '',
      cycleRebuyNum: '',

    },
   
    calcendarFold: false,
    stickShow: false,
    isLeaveFold: true,
    orderDisable: true,
    orderDisable1: false,
    activeTab: 1,
    ticketList: [{}, {}],
    monthInfo: {
      finishWorkerOrder: 0,
      orderBonus: 0,
      questionNum: 0,
      looseOrder: 0,
      cycleOrder: 0,
      rebuyBonus: 0,
      looseRebuyNum: 0,
      cycleRebuyNum: 0,
    },
    workerDayInfoList: [],
    weekCalendar: [],
    wholeCalendar: [],


	},
	addpreview(){
		wx.navigateTo({
			url: '/pages/pre/diyPreviewing/diypreviewing',
		})
	},
  onPageScroll(e) {
    // console.log(e.scrollTop);
    // if(e.scrollTop > 200){
    //   this.setData({
    //     stickShow: true
    //   });
    // } else {
    //   this.setData({
    //     stickShow: false
    //   });
    // }
  },
  leaveFold() {
    let fold = this.data.isLeaveFold;
    this.setData({
      isLeaveFold: !fold
    });
  },
  copyNum(e) {
    let bookno = e.currentTarget.dataset.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 == '待上门' || status == '待履约' || status == '已预约') {
      wx.makePhoneCall({
        phoneNumber: phone
      });
    }

  },
  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,
    })
  },
  openMap(e) { //打开地图

    let status = e.currentTarget.dataset.status;
    let address = e.currentTarget.dataset.address;
    if (status == '待上门' || status == '待履约' || 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
      });
    }

  },
  goSchedule() {
    wx.navigateTo({
      url: '/pages/upgrade/scheduleCalc/scheduleCalc',
    })
	},
	goApplySche(){
		wx.navigateTo({
      url: '/pages/new/changeSchedue/changeSchedue',
    });
	},
  goDetail(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/new/ticketDetail/ticketDetail?bookTradeNo=' + id,
    });
  },
  evalMaster(e) {
    let id = e.currentTarget.dataset.id;
    let workerno = e.currentTarget.dataset.workerno;
    this.setData({
      evalMasterShow: true,
      star: 0,
      masterComment: '',
      bookTradeNo: id,
      workerNo: workerno
    });
  },
  onClickMsterOverlay() {
    this.setData({
      evalMasterShow: false,
    });
  },
  onClickDiscipleOverlay() {
    this.setData({
      evalDiscipleShow: false,
    });
  },
  onStarChange(event) {
    this.setData({
      star: event.detail,
    });
  },
  onRadioChange(event) {
    this.setData({
      radioDisciple: event.detail,
    });
  },
  bindMasterComment(e) {
    this.setData({
      masterComment: e.detail.value
    })
  },
  bindDiscipleComment(e) {
    this.setData({
      discipleComment: e.detail.value
    })
  },
  stop: function () {
    //阻止弹框冒泡和捕获的空事件，不要删除！！！
  },
  submitEvalMaster() {
    if (this.data.star == 0) {
      wx.showToast({
        title: '请选择评价星级',
        icon: 'none'
      })
    } else if (this.data.masterComment == '') {
      wx.showToast({
        title: '请输入跟单体会',
        icon: 'none'
      })
    } else {
      util.request(api.discipleFeedback, {
        feedback: this.data.discipleComment,
        level: this.data.star,
        bookTradeNo: this.data.bookTradeNo,
        workerNo: this.data.workerNo
      }, 'GET').then(res => {
        if (res.errno === 0) {
          wx.showToast({
            title: '评价成功',
            icon: 'none'
          })
          this.setData({
            evalMasterShow: false,
          });
          this.getDayCalendar();
        } else {
          wx.showToast({
            title: res.errmsg,
            icon: 'none'
          })
        }
      });


    }
  },
  evalDisciple(e) {
    let id = e.currentTarget.dataset.id;
    let workerno = e.currentTarget.dataset.workerno;
    this.setData({
      evalDiscipleShow: true,
      radioDisciple: '通过',
      discipleComment: '',
      bookTradeNo: id,
      workerNo: workerno
    });
  },
  submitEvalDisciple() {
    if (this.data.radioDisciple == '') {
      wx.showToast({
        title: '请选择是否通过',
        icon: 'none'
      })
    } else if (this.data.discipleComment == '') {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
    } else {
      util.request(api.masterFeedback, {
        remark: this.data.discipleComment,
        feedback: this.data.radioDisciple,
        bookTradeNo: this.data.bookTradeNo,
        workerNo: this.data.workerNo
      }, 'GET').then(res => {
        if (res.errno === 0) {
          wx.showToast({
            title: '评价成功',
            icon: 'none'
          })
          this.setData({
            evalDiscipleShow: false,
          });
          this.getDayCalendar();

        } else {
          wx.showToast({
            title: res.errmsg,
            icon: 'none'
          })
        }
      });


    }
  },
  goProblemList(e) {
    // this.setData({
    //   navigateType: 1
    // })
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/problem/list/list?bookTradeNo=' + id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //   let current=this.data.wholeCalendar.filter(item=>{return item.day==this.data.currentDay});
    //   if(current.length==0){
    //       return false;
    //   }
    //   let week=current[0].weekOfYear;
    //   let weekCalendar=this.data.wholeCalendar.filter(item=>{
    //     return item.weekOfYear==week;
    //   });
    //   this.setData({
    //      workerDayInfoList:weekCalendar,
    //      weekCalendar:weekCalendar
    //   });




    // this.getMonthCalender(false, 'first');


    // this.getDayCalendar();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
		let userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.ofJz == 293) {
			this.setData({
				showjz:true
			})
		}
	// if(!this.data.isMonthCalender){
		
	// }
	this.setData({
		page:1,
		serviceOrderList:[],
	});
		this.getOrderList();
		this.getWorkerNearTeam();


    // this.getDayCalendar();
    // let timer = setInterval(() => {
    //   console.log('定时刷新日历数据', new Date());
    //   this.getMonthCalender();
    //   this.getDayCalendar();
    // }, 1 * 60 * 1000);
    // this.setData({
    //   timer: timer
    // });

  },
  onHide: function () {
    // console.log('onHide');
    // clearInterval(this.data.timer);
  },
  onUnload: function () {
    // console.log('onunload');
    // clearInterval(this.data.timer);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
		this.setData({
			page:1,
			serviceOrderList:[],
		});
		this.getOrderList();
		this.getWorkerNearTeam();
	},
	showFuture(){
		this.setData({
			calendarBoardShow:false,
			isSearchResult:true,
			isMonthCalender:true,
			orderType:3,
			calcendarFold:false,
		});
		this.getOrderList('first');
	},
	
  getOrderList(tag) {
    wx.showLoading({
      title: '加载中...',
    });
    util.request(api.workerServiceOrderList, {
			date: this.data.orderType==2?'':this.data.currentDay,
			pageNo:this.data.page,
			pageSize:10,
			queryType:this.data.orderType,
			month:this.data.orderType==2?this.data.currentMonth:''

    }, 'POST').then(res => {
			
      wx.hideLoading();
      if (res.errno == 0) {
				console.log(res);
				if(this.data.orderType==3){
				let wholeList=res.data.futureThirtyDays;
				let current = wholeList.filter(item => {
          return item.day == this.data.currentDay
        });
        if (current.length == 0) {
          return false;
        }
        let week = current[0].weekOfYear;
        let weekCalendar = wholeList.filter(item => {
          return item.weekOfYear == week;
        });
     

					this.setData({
						weekCalendar: weekCalendar,
					
						wholeCalendar:res.data.futureThirtyDays,
						avgDay:res.data.avgDay,
						futureThirtyDaysStr:res.data.futureThirtyDaysStr,
						futureThirtyDaysEnd:res.data.futureThirtyDaysEnd	

					})
					if(tag=='first'){
						this.setData({
							futureThirtyDays:res.data.futureThirtyDays,
						});
					}else{
						// this.setData({
						// 	futureThirtyDays:weekCalendar
						// });
					
					}
				}
        this.setData({
					serviceOrderList: this.data.serviceOrderList.concat(res.data.serviceOrderList),
					weather:res.data.weather,
					totalPage:res.data.totalPage,
					leaveList:res.data.leaveList

        });
      }
    }).catch(err => {
      wx.hideLoading();
    });
	},
	goLeavepost: function () {
    wx.navigateTo({
      url: '/pages/servant/leavepost/leavepost'
    })
  },
	getMonthOrderCount() {
    wx.showLoading({
      title: '加载中...',
    });
    util.request(api.workerServiceMonthOrderCount, {
		
    }, 'GET').then(res => {
			
      wx.hideLoading();
      if (res.errno === 0) {
        this.setData({
					futureOrderCount:res.data.futureOrderCount,
					monthOrderCount:res.data.monthOrderCount
        });
      }
    }).catch(err => {
      wx.hideLoading();
    });
	},
	getWorkerNearTeam() {
    wx.showLoading({
      title: '加载中...',
    });
    util.request(api.getWokerNearTeam, {
			dateDay: this.data.currentDay,

    }, 'GET').then(res => {
      wx.hideLoading();
      if (res.errno === 0) {
        console.log(res);
        this.setData({
					dayTeam:res.data.dayTeam,
					dayTeamName:res.data.dayTeamName
        });
      }
    }).catch(err => {
      wx.hideLoading();
    });
	},
	backStart(){
		this.setData({
			currentDay:this.data.todayTag,
			isSearchResult:false,
			isMonthCalender:false
		})
		this.setData({
			page:1,
			serviceOrderList:[],
			orderType:1
		});
		this.getOrderList();
	},
	switchDayItem(e){
		let day=e.currentTarget.dataset.day;
		let name=e.currentTarget.dataset.name;
		let week=e.currentTarget.dataset.week;
		let weekCalendar = this.data.wholeCalendar.filter(item => {
			return item.weekOfYear == week;
		});
		if(name=='请假'||day<this.data.todayTag){
			return false;
		}else{
		
			this.setData({
				currentDay:day,
				page:1,
				serviceOrderList:[],
				orderType:1,
				calcendarFold:true,
				futureThirtyDays:weekCalendar
			});
			this.getOrderList();
		}
	
	},
	switchMonthItem(e){
		let month=e.currentTarget.dataset.month;
		let count=e.currentTarget.dataset.count;
		this.setData({
			calendarBoardShow:false,
			currentMonth:month,
			isSearchResult:true,
			orderType:2,
			lastMonthCount:count
		});
		this.setData({
			page:1,
			serviceOrderList:[]
		});
		this.getOrderList();
	},


  getDayCalendar() {
    wx.showLoading({
      title: '加载中...',
    });
    util.request(api.dayCalender, {
      date: this.data.currentDay,

    }, 'GET').then(res => {
      wx.hideLoading();
      if (res.errno === 0) {
        console.log(res);
        this.setData({
          dayCalendar: res.data
        });
      }
    }).catch(err => {
      wx.hideLoading();
    });
  },
  getMonthCalender(flag, tag) {
    wx.showLoading({
      title: '加载中...',
    });
    util.request(api.monthCalender, {
      month: this.data.currentMonth,

    }, 'GET').then(res => {
      wx.hideLoading();
      if (res.errno === 0) {
        console.log(res);
        this.setData({
          monthInfo: res.data,
          wholeCalendar: res.data.workerDayInfoList
        });
        if (flag) {
          this.setData({
            calcendarFold: false,
            workerDayInfoList: this.data.wholeCalendar,

          });
        }
        let current = this.data.wholeCalendar.filter(item => {
          return item.day == this.data.currentDay
        });
        if (current.length == 0) {
          return false;
        }
        let week = current[0].weekOfYear;
        let weekCalendar = this.data.wholeCalendar.filter(item => {
          return item.weekOfYear == week;
        });
        this.setData({

          weekCalendar: weekCalendar
        });
        if (tag == 'first') {
          this.setData({
            workerDayInfoList: weekCalendar,
          });
        }
        if (this.data.calcendarFold) {
          this.setData({
            workerDayInfoList: weekCalendar,
          });
        } else {
          this.setData({
            workerDayInfoList: this.data.wholeCalendar,
          });
        }
      } else {
        wx.showToast({
          title: res.errmsg,
          duration: 3000,
          icon: 'none'
        });
      }


    }).catch(err => {
      wx.hideLoading();
    });
  },
  switchDay(e) {
    let day = e.currentTarget.dataset.day;
    this.setData({
      currentDay: day
    });
    this.getDayCalendar();
  },
  calcendarCollapse() {
    let calcendarFold = this.data.calcendarFold;
  
      this.setData({
       futureThirtyDays: this.data.wholeCalendar,
        calcendarFold: !calcendarFold
      });
  

  },
  lastMonth() {
    console.log(this.data);
    let params = util.getYearMonth(this.data.currentMonth, '-');
    this.setData({
      currentMonth: params
    });
    this.getMonthCalender(true);
  },
  nextMonth() {
    let params = util.getYearMonth(this.data.currentMonth, '+');
    console.log(params);
    this.setData({
      currentMonth: params
    });
    this.getMonthCalender(true);
  },
  goIssueTicket() {
    wx.navigateTo({
      url: '/pages/upgrade/issueTicket/issueTicket',
    })
  },
  supplyCode(e) {
    let bookno = e.currentTarget.dataset.bookno;
    if (bookno.startsWith('JZ')) {
      bookno = bookno.substr(2);
    }
    util.request(api.createMakeUpQRCode, {
      serviceId: bookno
    }, 'GET').then(res => {
      if (res.errno === 0) {
        let url = res.data;
        wx.previewImage({
          current: url, // 当前显示图片的http链接
          urls: [url] // 需要预览的图片http链接列表
        })

      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none'
        })
      }
    });



	},
	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,
		});
	},
	supplyRecord(e){
		let bookno = e.currentTarget.dataset.bookno;
    if (bookno.startsWith('JZ')) {
      bookno = bookno.substr(2);
    }
		wx.navigateTo({
			url: '/pages/supplyRecord/supplyRecord?bookno='+bookno,
		});
	},
	showCalendarBoard(){
		this.setData({
			calendarBoardShow:true
		});
		this.getMonthOrderCount();
	},
	onCalendarOverlay(){
		this.setData({
			calendarBoardShow:false
		});
	},
	showSchedueBoard(){
		this.setData({
			schedueBoardShow:true
		});
		this.getWorkerNearTeam();
	},
	onSchedueOverlay(){
		this.setData({
			schedueBoardShow:false
		});
	},
	goLeaveHistory(){
		wx.navigateTo({
			url: '/pages/servant/leave/leave',
		 }); 
	},
	preventClick(){
//不要删，阻止事件冒泡
	},

  onReachBottom() {
    if (this.data.totalPage > this.data.page) {
      this.setData({
        page: this.data.page + 1
      });
      this.getOrderList();
    } else{
			 if(this.data.totalPage>1){
				wx.showToast({
					title: '没有更多工单了',
					icon: 'none',
					duration: 2000
				});
			 }
    
      return false;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },









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

  },

})