const app = getApp()
const util = require("../../utils/util");
const api = require('../../api/api.js');
const user = require('../../utils/user.js');
const wxCharts = require('../../utils/wxcharts-min.js')


import todo from '../../lib/calendar/plugins/todo'
import selectable from '../../lib/calendar/plugins/selectable'
import solarLunar from '../../lib/calendar/plugins/solarLunar/index'
import timeRange from '../../lib/calendar/plugins/time-range'
import week from '../../lib/calendar/plugins/week'
import holidays from '../../lib/calendar/plugins/holidays/index'
import plugin from '../../lib/calendar/plugins/index'

var calendar;
plugin.use(todo).use(solarLunar).use(selectable).use(week).use(timeRange).use(holidays)

Page({
  data: {
    userInfo: {
      nickName: '点击登录',
      avatarUrl: '/static/images/my.png'
    },
    hasLogin: false,
    count: 0, //服务中的工单 当天待处理
    list: [],
    page: 1,
    limit: 10,
    totalPages: 1,
    addressInfo: {
      shopId: 0
    },
    myqr_show: false, //我的分享二维码
    myqr_url: null,
    myqr_blur: 0, //背景模糊值
    code: '',
    calendarConfig: {
      theme: 'elegant'
    },
    list: [],
    board: {},
    selected: [], //选中日期的服务单
    selectedDate: '未选择', //选中的日期和时间
    selectedTime: '',
    isMaster: false, //是否为站长
    curDate: '', //当前选中时间
    line: {}, //当登录用户是站长时的数据对象
    today: '', //今日时间 用来控制是否可以点击到家
    testMobiles: ['132****8272', '173****9375', '182****9968', '130****7996', '131****2586', '138****9808', '151****2510', '178****5726','166****5459','180****8315','158****3676'],
    isTest: false,
    isFirstLoad: true, //是否第一次加载此页面
    salary:{//工资信息
      salary:0,
      total:0
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let week = util.getWeekByDate(new Date());
    this.setData({
      today: util.formatDate(new Date()) + '  ' + week
    })

    var addressInfo = wx.getStorageSync('addressInfo');
    if (addressInfo) {
      this.setData({
        addressInfo: addressInfo
      })
    }
    let that = this;
    user.login().then(res => {
      console.info(res)
      that.setData({
        code: res.code
      })
    }) 
  },
  // alertModel(){
  //   if(wx.getStorageSync('alertgq')&&wx.getStorageSync('alertgq')==1){
  //     return;
  //   }
  //   wx.showModal({
  //     title: '公告',
  //     content: '由于国庆假期，服务费盒马部分数据无法按时提供，影响核算时间，故本次9月服务费延期至10月17日周一发放，请各位劳动者知悉。',
  //     success (res) {
  //       if (res.confirm) {
  //         console.log('用户点击确定')
  //         wx.setStorageSync('alertgq', 1);
  //       } 
  //     }
  //   })
  // },
  goArrived(e) { //我已上门
    let that = this;
    let bookTradeNo = e.currentTarget.dataset.id;
    wx.showModal({
      title: '我已上门',
      content: '确定我已到顾客服务地？',
      showCancel: true, //是否显示取消按钮 
      confirmText: "已上门", //默认是“确定”
      confirmColor: '#09afff', //确定文字的颜色 
      success: function (res) {
        if (res.confirm == false) return;
        wx.showLoading();
        util.request(api.HmApiArrived, {
          bookTradeNo: bookTradeNo
        }).then(res => {
          wx.hideLoading();
          if (res.errno == 0) {
            let selected = that.data.selected;
            selected.forEach(item => {
              if (item.bookNo == bookTradeNo) {
                item.status = '待履约'
              }
            })
            that.setData({
              selected: selected
            })
          } else
            util.showErrorToast(res.errmsg);
        }).catch(res => {
          wx.hideLoading();
          util.showErrorToast(res.errmsg);
        })
      }
    })
  },
  goConfirm(e) {
    let that = this;
    let bookTradeNo = e.currentTarget.dataset.id;
    wx.showModal({
      title: '服务已完成',
      content: '确定我已服务完成？',
      showCancel: true, //是否显示取消按钮 
      confirmText: "完成", //默认是“确定”
      confirmColor: '#09afff', //确定文字的颜色 
      success: function (res) {
        if (res.confirm == false) return;
        wx.showLoading();
        util.request(api.HmApiConfirm, {
          bookTradeNo: bookTradeNo
        }).then(res => {
          wx.hideLoading();
          if (res.errno == 0) {
            let selected = that.data.selected;
            selected.forEach(item => {
              if (item.bookNo == bookTradeNo) {
                item.status = '服务已完成'
              }
            })
            that.setData({
              selected: selected
            })
          } else
            util.showErrorToast(res.errmsg);
        }).catch(res => {
          wx.hideLoading();
          util.showErrorToast(res.errmsg);
        })
      }
    })
  },
  goProblemAdd(e) {
    let id = e.currentTarget.dataset.id;
    if (id) {
      wx.navigateTo({
        url: '/pages/problem/list/list?bookTradeNo=' + id,
      })
    }
  },
  getBoard(month) { //获取看板信息 
    let that = this;
    that.setData({
      curDate: month
    }) 

    wx.showLoading();
    util.request(api.Board, {
      'month': month
    }).then(res => {
      console.info(res.data)
      wx.hideLoading();
      // if (res.data.isMaster) {
      //   that.setData({
      //     line: res.data.board,
      //     isMaster: res.data.isMaster
      //   })
      //   that.goChat();
      // } else {
        console.info("getScheduling")
        that.setData({
          board: res.data.board,
          isMaster: res.data.isMaster
        })
        //that.calendar.header= res.data.board;
        that.getScheduling();
      //}

    }).catch(res => {
      //console.info(res) 
      wx.hideLoading();
      util.showErrorToast(res.errmsg);
    })
  },
  isNewYearReport() { //是否新年报表
    util.request(api.NewYearReported).then(res => {
      if (!res.data) {
        wx.showModal({
          title: '返乡调查',
          content: '新年返乡调查已开始，是否现在去报备？',
          success: function (sm) {
            if (sm.confirm) {
              wx.navigateTo({
                url: '/pages/servant/gohome/report',
              })

            }
          }
        });
      }
    })

  },
  getScheduling() { //获取可用排班  
    let that = this;
    //获取当月的所有日期 
    if (calendar == undefined) {
      return;
    }
    var dates = calendar.getCalendarDates({
      lunar: true
    })

    //一天多个订单 聚集到一个list
    var books = [];
    dates.forEach(function (item, index) {
      var _date = String(item.year) + '-' + ((item.month < 10 ? "0" : "") + String(item.month)) + '-' + ((item.date < 10 ? "0" : "") + String(item.date));
      var bookDate = null;
      books.forEach(book => {
        if (book.date == _date)
          bookDate = book;
      })
      //是否包含当前日期 
      that.data.board.details.forEach(element => {
        if (element.date == _date) {
          if (bookDate == null) {
            bookDate = {
              date: item.date,
              books: []
            };
            books.push(bookDate);
          }
          bookDate.books.push(element);
        }
      })
    })
    //赋值显示
    //console.info(books);
    books.forEach(item => {
      if (item.books.length > 0) {
        that.calenderTodo(item.date, item.books);
      }
    })
    that.setData({
      list: books
    });

    //选中当前时间 
    if (that.data.isFirstLoad) {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let day = now.getDate();

      const toSet = [{
        year,
        month,
        date: day
      }, {
        year,
        month,
        date: day
      }]

      calendar['setSelectedDates'](toSet);
      let nowDay = now.getDate();
      if (nowDay < 10)
        nowDay = '0' + nowDay;

      this.selectDate(util.formatDate(now), nowDay);
    }
  },
  goChat() {
    let that = this;
    var windowWidth = '',
      windowHeight = ''; //定义宽高
    try {
      var res = wx.getSystemInfoSync(); //试图获取屏幕宽高数据
      windowWidth = res.windowWidth / 750 * 690; //以设计图750为主进行比例算换
      windowHeight = res.windowWidth / 750 * 550 //以设计图750为主进行比例算换
    } catch (e) {
      console.error('getSystemInfoSync failed!'); //如果获取失败
    }

    new wxCharts({ //定义一个wxCharts图表实例
      canvasId: 'lineCanvas', //输入wxml中canvas的id
      type: 'line', //图标展示的类型有:'line','pie','column','area','ring','radar'
      categories: that.data.line.categories, //['6-13', '6-14', '6-15', '6-16', '6-17', '6-18', '6-19'],
      animation: true, //是否开启动画
      series: that.data.line.series,
      xAxis: { //是否隐藏x轴分割线
        disableGrid: true,
      },
      yAxis: { //y轴数据
        title: '数值', //标题
        format: function (val) { //返回数值
          return val.toFixed(2);
        },
        gridColor: '#D8D8D8',
      },
      width: windowWidth, //图表展示内容宽度
      height: windowHeight, //图表展示内容高度
      dataLabel: false, //是否在图表上直接显示数据
      dataPointShape: true, //是否在图标上显示数据点标志
      extra: {
        lineStyle: 'curve' //曲线
      },
    });
  },
  goNextWeek() {
    var date = util.mathChangeDate(this.data.curDate, '+', 7, true);
    console.info(date)
    this.getBoard(date)
  },
  goPreWeek() {
    var date = util.mathChangeDate(this.data.curDate, '-', 7, true);
    console.info(date)
    this.getBoard(date)
  },
  qrtouchstart: function () {
    this.setData({
      myqr_blur: 0,
      myqr_show: false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        hasLogin: true
      });
      var isTest = false;
      this.data.testMobiles.forEach(item => {
        if (item == userInfo.mobile)
          isTest = true;
      })
      this.setData({
        isTest: isTest
      });
    }
    if (this.hasLogin == false) {
      wx.navigateTo({
        url: '/pages/index/index',
      })
      return;
    }

    //this.isNewYearReport();
    if (this.data.curDate != '') return;
    this.setData({
      list: []
    })
    this.getSalary(util.formatDate(new Date()));
    this.getBoard(util.formatDate(new Date()));
 
  },
  getSalary(month){
    let that=this
    util.request(api.BoardSalary,{month:month}).then(res=>{
      that.setData({
        salary:res.data
      }) 
    }) 
  },
  getGoodsList() {
    let that = this
    //console.info(that.data.addressInfo)
    wx.showLoading();
    util.request(api.GoodsList, {
      shopId: that.data.addressInfo.shopId,
      limit: that.data.limit,
      page: that.data.page
    }).then(res => {
      wx.hideLoading();
      if (res.errno === 0) {
        that.setData({
          list: that.data.list.concat(res.data.list),
          totalPages: res.data.pages
        });
      }
    }).catch(res => {
      console.info(res)
      wx.hideLoading();
    })
  },
  getUserProfile(e) {
    let that = this
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        res.userInfo.code = that.data.code;
        util.request(api.AuthLoginByWeixin, res.userInfo, "POST").then(res => {
          console.info(res)
          if (res.errno == 0) {
            that.setData({
              userInfo: res.data.userInfo
            })
            wx.setStorageSync('userInfo', res.data.userInfo);
          }
        })
      }
    })
  },
  goNucleicList() {
    wx.navigateTo({
      url: '/pages/servant/nucleic/list'
    })
  },
  goCRM(){
    wx.navigateTo({
      url: '/pages/servant/crm/ticket'
    })
  },
  goBookDetail(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/board/detail/detail?no=' + id,
    })
  },
  goPaymentOrderDetail(e){//钟点工订单明细
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/servant/orderDetail/hmOrderDetail?payId=' + id,
    })
  },
  goSalaryDetail(e) { //查询工资明细
    const {
      year,
      month
    } = calendar.getCurrentYM();
    let m = month;
    if (m < 10) m = '0' + String(m);
    let type = e.currentTarget.dataset.type;
    let total = (type == 1 ? this.data.salary.salary : this.data.salary.total);
    //servantType 表示服务者身份99是临时服务者 明细页可以显示提现按钮
    wx.navigateTo({
      url: '/pages/servant/salary/detail/detail?month=' + (String(year) + m) + '&total=' + total + '&type=' + type+'&servantType='+this.data.board.type+'&blance='+this.data.salary.salary
    })
  },
  afterTapDate(e) { //选中某个日期
    console.log('afterTapDate', e.detail.date)
    let that = this;
    var month = e.detail.month < 10 ? "0" + String(e.detail.month) : String(e.detail.month);
    var date = e.detail.date < 10 ? "0" + String(e.detail.date) : String(e.detail.date);
    let fullDate = e.detail.year + '-' + month + '-' + date;
    that.selectDate(fullDate, e.detail.date);
  },
  selectDate(fullDate, day) {
    console.info("selectDate:" + fullDate)
    let that = this;
    let week = util.getWeekByDate(fullDate);
    that.setData({
      selectedDate: fullDate + '  ' + week,
      isFirstLoad: false
    })
    that.setData({
      selected: []
    })

    that.data.list.forEach(item => {
      if (parseInt(item.date) == day) {
        that.setData({
          selected: item.books
        })
      }
    })

    // if(that.data.selected.length>0&&that.data.curDate==fullDate){//如果当日有订单 角标提醒（角标）
    //     wx.setTabBarBadge({
    //       index: 3,
    //       text: String(that.data.selected.length)
    //     })
    // }

  },
  whenChangeMonth(e) {
    console.log('whenChangeMonth', e.detail)
    const {
      year,
      month
    } = calendar.getCurrentYM();

    let m=month;
    if (m < 10) m = String(0) + m;
    
    this.getBoard(year + '-' + m + '-01');
    this.getSalary(year + '-' + m + '-01');
  },
  whenChangeWeek(e) {
    console.log('whenChangeWeek', e.detail)
  },
  takeoverTap(e) {
    console.log('takeoverTap', e.detail)
  },
  afterCalendarRender(e) {
    console.log('afterCalendarRender', e);
    //初始化完成后，将插件变量赋值
    calendar = this.selectComponent('#calendar').calendar;  
    const {
      year,
      month
    } = calendar.getCurrentYM();
    if (this.data.isMaster == false) {
      let date = (new Date()).getDate();
      if (date < 10) date = String(0) + date;

      let m=month;
      if (m < 10) m = String(0) + m;
      
      this.getBoard(year + '-' + m + '-' + date);
      this.getSalary(year + '-' + m + '-' + date);
    } 
  },
  onSwipe(e) {
    console.log('onSwipe', e)
  },
  calendarSetEnabledDates(dates) { //设置可选择的日期  
    //const calendar = this.selectComponent('#calendar').calendar;
    //console.info(dates); 
    //calendar['enableDates'](dates);
  },
  calenderTodo(date, title) { //设置指定日期  
    const {
      year,
      month
    } = calendar.getCurrentYM();
    const dates = [{
      year,
      month,
      date: date,
      todoText: title
    }]

    calendar['setTodos']({
      showLabelAlways: true,
      dates
    })
    //console.log('set todo: ', dates) ;
  },
  openMap(e) { //打开地图
    let that = this;
    let bookTradeNo = e.currentTarget.dataset.id;
    let bookInfo = null;
    that.data.board.details.forEach(item => {
      if (item.bookNo == bookTradeNo) {
        bookInfo = item;
        return;
      }
    })
    console.info(bookInfo)
    let address = bookInfo.address;
    let lng = bookInfo.position.split(',')[0];
    let lat = bookInfo.position.split(',')[1];
    wx.openLocation({
      latitude: parseFloat(lat),
      longitude: parseFloat(lng),
      name: address,
      address: address,
      scale: 28
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  userProtocol(){
		wx.navigateTo({
			url: '/pages/servant/salary/protocol/protocol'
		});
	},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  shareGoods(e) {
    let that = this;
    wx.showLoading({
      title: '生成中',
    });
    util.request(api.GoodsShare, {
      goodsId: e.currentTarget.dataset.id
    }).then(function (res) {
      console.info(res)
      wx.hideLoading();
      if (res.errno == 0) {
        that.setData({
          myqr_url: res.data.imgUrl,
          myqr_show: true,
          myqr_blur: 5
        });
      } else if (res.errno == 501) {

        // wx.navigateTo({
        //   url: "/pages/index/index"
        // });
      } else {
        wx.showToast({
          title: res.errmsg,
          duration: 5000
        })
      }
    });
  },
  makeCall(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
    })
  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 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;
    // }
  },
  goShowMoneyTip() {
    wx.showModal({
      title: '服务费说明',
      content: '因影响服务费的因素较多，如有疑问请及时反馈到站长，实际服务费以次月发放为准',
      showCancel: false
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  saveShare: function () {
    let that = this;
    wx.showLoading({
      title: '图片保存中',
    });
    console.log(that.data);
    wx.downloadFile({
      url: that.data.myqr_url,
      success: function (res) {
        console.log(res)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            wx.hideLoading();
            wx.showModal({
              title: '存图成功',
              content: '图片成功保存到相册了，可以分享到朋友圈了',
              showCancel: false,
              confirmText: '好的',
              confirmColor: '#a78845',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                  that.setData({
                    myqr_show: false,
                    myqr_blur: 0
                  });
                }
              }
            })
          },
          fail: function (res) {
            wx.hideLoading();
            wx.showModal({
              title: '警告',
              content: '未授权无法保存',
              showCancel: false
            })
            that.setData({
              myqr_show: false,
              myqr_blur: 0
            });
          }
        })
      },
      fail: function (res) {
        wx.hideLoading();
        console.log(res);
      }
    })
  },
  goProview() {
    wx.switchTab({
      url: '/pages/pre/list/preList',
    })
  },
  goBookIndex(e) {
    if (this.data.hasLogin) {
      let tab = e.currentTarget.dataset.index
      let route = e.currentTarget.dataset.route
      try {
        wx.setStorageSync('tab', tab);
      } catch (e) {

      }
      wx.navigateTo({
        url: route,
        success: function (res) {},
        fail: function (res) {},
        complete: function (res) {},
      })
    } else {
      wx.navigateTo({
        url: "/pages/index/index"
      });
    };
  },
  goLeave(){//请假
    // wx.navigateTo({
    //   url: '/pages/servant/leave/leave',
    // })
    wx.showModal({
      title: '提醒',
      content: '暂未开通，敬请期待',
      showCancel: false
    })
  },
  exitLogin: function () {
    wx.showModal({
      title: '',
      confirmColor: '#b4282d',
      content: '退出登录？',
      success: function (res) {
        if (!res.confirm) {
          return;
        }

        util.request(api.AuthLogout, {}, 'POST');
        app.globalData.hasLogin = false;
        wx.removeStorageSync('token');
        wx.removeStorageSync('userInfo');
        wx.navigateTo({
          url: '/pages/index/index'
        });
      }
    })

  }
})