// pages/wodeBillSharePage/index.js
const app = getApp();
import { formatDateYMD } from "../../utils/dateUtil";
import { customRequest } from '../../utils/request.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    inputVal: "搜索姓名",
    searchParam: {
      pageNum: 1,
      pageSize: 20,
      keys: "",
      status: "",
    },
    recordList: [], // 账单详情列表
    factoryBill: {}, // 账单详情
    billInfo: {}, // 列表传输过来的账单信息
    currentDetail: {}, // 当前对象详情
    currIndex: 0,
    chaShowed: false,
    dialog: false,
    isChecked: false,
    selectTotalSalary: 0, // 待确认选中的总价格
    hasMoreData: false,
    isTrigger: false,
    id: "",
    isLogin: app.globalData.isLogin,
    wxCode: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    console.log(options);
    console.log("showId");
    // let info = JSON.parse(options.id);
    this.data.searchParam.agencyId = options.agencyId;
    this.data.searchParam.factoryBillId = options.factoryBillId;
    // this.data.searchParam.status = '';
    this.setData({
      // id: info.id,
      searchParam: this.data.searchParam,
    });
    console.log(this.data.searchParam);
    wx.setNavigationBarTitle({
      // title: info.title,
    });
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
    this.data.searchParam.pageNum = 1;
    this.setData({
      recordList: [],
      searchParam: this.data.searchParam,
    });
    console.log(this.data.searchParam);
    this.wxLogin();
    this.getList();
  },

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

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

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

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

  /**
   * 用户点击右上角分享
   */
onShareAppMessage() {
  return app.sharePageImage()
},
  onScrollToLower: function () {
    this.data.searchParam.pageNum = this.data.searchParam.pageNum + 1;
    this.getList();
  },
  getList () {
    let that = this;
    console.log("+++++++++++++++++", "getlistRigth");
    this.data.searchParam.keys = this.data.inputVal == "搜索姓名" ? "" : this.data.inputVal;
    wx.showLoading({
      title: "加载中...",
    });
    customRequest("/yishoudan/factory/bill/record/list",{header:'headers', method: 'POST', data:that.data.searchParam}).then((res)=>{
      if (res.data.status == 200) {
        if (res.data.data.pageBean.recordList != null && res.data.data.pageBean.recordList.length < 20) {
          var recordListTemp = res.data.data.pageBean.recordList;
          that.data.recordList = that.data.recordList.concat(recordListTemp);
          that.setData({
            hasMoreData: false,
          });
        } else {
          var recordListTemp = res.data.data.pageBean.recordList;
          that.data.recordList = that.data.recordList.concat(recordListTemp);
          that.setData({
            hasMoreData: true,
          });
        }
        that.data.recordList.forEach((item) => {
          console.log(item.finished);
          console.log(item.workDays);
          if (item.finished && item.workDays) {
            item.workInfo = item.finished + " | " + "出勤" + item.workDays;
          } else if (item.finished || item.workDays) {
            item.workInfo = item.finished + (item.workDays ? "出勤" + item.workDays : "");
          } else {
            item.workInfo = "-";
          }
          // console.log(item.workInfo);
        });
        that.setData({
          recordList: that.data.recordList,
          factoryBill: { ...res.data.data.factoryBill, agencyName: that.data.recordList[0].agencyName },
          isTrigger: false,
        });
        console.log(that.data.factoryBill);
      }
      wx.hideLoading();
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/factory/bill/record/list",
    //   data: that.data.searchParam,
    //   header: app.globalData.headers,
    //   method: "POST",
    //   success: function (res) {
    //     console.log(res, "+++++++++++++++++", "requestRigth");
    //     if (res.data.status == 200) {
    //       if (res.data.data.pageBean.recordList != null && res.data.data.pageBean.recordList.length < 20) {
    //         var recordListTemp = res.data.data.pageBean.recordList;
    //         that.data.recordList = that.data.recordList.concat(recordListTemp);
    //         that.setData({
    //           hasMoreData: false,
    //         });
    //       } else {
    //         var recordListTemp = res.data.data.pageBean.recordList;
    //         that.data.recordList = that.data.recordList.concat(recordListTemp);
    //         that.setData({
    //           hasMoreData: true,
    //         });
    //       }
    //       that.data.recordList.forEach((item) => {
    //         console.log(item.finished);
    //         console.log(item.workDays);
    //         if (item.finished && item.workDays) {
    //           item.workInfo = item.finished + " | " + "出勤" + item.workDays;
    //         } else if (item.finished || item.workDays) {
    //           item.workInfo = item.finished + (item.workDays ? "出勤" + item.workDays : "");
    //         } else {
    //           item.workInfo = "-";
    //         }
    //         // console.log(item.workInfo);
    //       });
    //       that.setData({
    //         recordList: that.data.recordList,
    //         factoryBill: { ...res.data.data.factoryBill, agencyName: that.data.recordList[0].agencyName },
    //         isTrigger: false,
    //       });
    //       console.log(that.data.factoryBill);
    //     }
    //     wx.hideLoading();
    //   },
    // });
  },
  onScrollRefresh () {
    this.data.recordList = [];
    this.data.searchParam.pageNum = 1;
    console.log("isonScrollRefresh");
    this.getList();
  },
  goDetail (e) {
    let that = this;
    console.log(e);
    let id = e.currentTarget.dataset.id;
    customRequest("/yishoudan/factory/bill/record/details/" + id,{header:'headers', method: 'GET', data: {}}).then(({data})=>{
      if (data.status == 200) {
        // data.data.pageBean.recordList.forEach((item) => {
        // item.showTime = formatDateYMDHM(item.updateTime);
        // });

        data.data.billRecord.applyTimeStr = formatDateYMD(data.data.billRecord.applyTime);
        data.data.billRecord.entryTimeStr = formatDateYMD(data.data.billRecord.entryTime);
        data.data.billRecord.leaveTimeStr = formatDateYMD(data.data.billRecord.leaveTime);

        that.setData({
          currentDetail: { ...data.data.billRecord, customize: data.data.titles },
        });
        console.log(that.data.currentDetail.customize);
      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/factory/bill/record/details/" + id,
    //   // data: that.data.searchParam,
    //   header: app.globalData.headers,
    //   success: function ({ data }) {
    //     console.log(data);
    //     if (data.status == 200) {
    //       // data.data.pageBean.recordList.forEach((item) => {
    //       // item.showTime = formatDateYMDHM(item.updateTime);
    //       // });

    //       data.data.billRecord.applyTimeStr = formatDateYMD(data.data.billRecord.applyTime);
    //       data.data.billRecord.entryTimeStr = formatDateYMD(data.data.billRecord.entryTime);
    //       data.data.billRecord.leaveTimeStr = formatDateYMD(data.data.billRecord.leaveTime);

    //       that.setData({
    //         currentDetail: { ...data.data.billRecord, customize: data.data.titles },
    //       });
    //       console.log(that.data.currentDetail.customize);
    //     }
    //   },
    // });
    this.setData({
      dialog: true,
    });
    // this.data.dialog = true

    console.log("isIntoDetail");
  },
  closeDrawer () {
    this.setData({
      dialog: false,
      currentDetail: {},
    });
  },
  wxLogin () {
    var that = this;
    wx.login({
      success (res) {
        console.log(res);
        if (res.code) {
          that.setData({
            wxCode: res.code,
          });
        } else {
          console.log("获取code失败！" + res.errMsg);
        }
      },
    });
  },
  confirmBill () {
    let that = this;
    let ids = {};
    console.log("sdasfdasdf");
    wx.showLoading({
      title: "确认中...",
    });
    console.log(this.data.currentDetail);
    ids.recordIds = this.data.currentDetail.id + "";
    ids.factoryBillId = this.data.searchParam.factoryBillId;
    console.log(app.globalData.headers);
    customRequest("/yishoudan/factory/bill/record/confirm",{header:'headers', method: 'post', data: ids}).then(({data})=>{
      if (data.status == 200) {
        wx.showToast({ title: "确认成功", icon: "success", duration: 2000 }); //隐藏消息提示框
        // that.data.searchParam.status = 10;
        that.setData({
          dialog: false,
          recordList: [],
          searchParam: that.data.searchParam,
          currIndex: 0,
          selectTotalSalary: 0,
          isChecked: false,
        });
        that.getList();
        // wx.hideLoading();
      } else {
        wx.showToast({ title: data.msg, icon: "none", duration: 2000 }); //隐藏消息提示框

      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/factory/bill/record/confirm",
    //   data: ids,
    //   header: app.globalData.headers,
    //   method: "post",
    //   success: function ({ data }) {
    //     console.log(data);
    //     if (data.status == 200) {
    //       wx.showToast({ title: "确认成功", icon: "success", duration: 2000 }); //隐藏消息提示框
    //       // that.data.searchParam.status = 10;
    //       that.setData({
    //         dialog: false,
    //         recordList: [],
    //         searchParam: that.data.searchParam,
    //         currIndex: 0,
    //         selectTotalSalary: 0,
    //         isChecked: false,
    //       });
    //       that.getList();
    //       // wx.hideLoading();
    //     } else {
    //       wx.showToast({ title: data.msg, icon: "none", duration: 2000 }); //隐藏消息提示框

    //     }
    //   },
    // });
  },
  getPhoneNumber (e) {
    console.log(e);
    console.log("into getphonenumber");
    let that = this;
    if ("getPhoneNumber:ok" == e.detail.errMsg) {
      //同意 
      var iv = e.detail.iv;
      var encryptedData = e.detail.encryptedData;
      console.log(iv, "=-=========", encryptedData);
      wx.checkSession({
        success () {
          //session_key 未过期，并且在本生命周期一直有效
          customRequest("/getWechatTel",{header:'headers', method: 'GET', data: { code: that.data.wxCode,
            iv: iv,
            encryptedData: encryptedData,
            type: "yishoudan",}}).then((res)=>{
              app.globalData.openId = res.data.data.openId;
              let promise = app.setLoginUserTokenInfo(res.data.data.phoneNumber, null);
              promise.then((res) => {
                that.setData({
                  isLogin: app.globalData.isLogin,
                });
                that.confirmBill();
              });
          })
          // wx.request({
          //   url: app.globalData.ip + "/getWechatTel",
          //   data: {
          //     code: that.data.wxCode,
          //     iv: iv,
          //     encryptedData: encryptedData,
          //     type: "yishoudan",
          //   },
          //   success: function (res) {
          //     console.log(res);
          //     app.globalData.openId = res.data.data.openId;
          //     let promise = app.setLoginUserTokenInfo(res.data.data.phoneNumber, null);
          //     promise.then((res) => {
          //       that.setData({
          //         isLogin: app.globalData.isLogin,
          //       });
          //       that.confirmBill();
          //     });
          //   },
          //   fail: function (res) {
          //     console.log("获取用户手机号错误");
          //   },
          // });
        },
        fail () {
          // session_key 已经失效，需要重新执行登录流程
          wx.login({
            success (res) {
              if (res.code) {
                console.log(res.code);
                //发起网络请求
                customRequest("/getWechatTel",{header:'headers', method: 'GET', data: {  code: res.code,
                  iv: iv,
                  encryptedData: encryptedData,
                  type: "yishoudan",}}).then((res)=>{
                    let promise = app.setLoginUserTokenInfo(res.data.data.phoneNumber, null);
                    promise.then((res) => {
                      that.setData({
                        isLogin: app.globalData.isLogin,
                      });
                      that.confirmBill();
                    });
                })
                // wx.request({
                //   url: app.globalData.ip + "/getWechatTel",
                //   data: {
                //     code: res.code,
                //     iv: iv,
                //     encryptedData: encryptedData,
                //     type: "yishoudan",
                //   },
                //   success: function (res) {
                //     console.log(res);
                //     let promise = app.setLoginUserTokenInfo(res.data.data.phoneNumber, null);
                //     promise.then((res) => {
                //       that.setData({
                //         isLogin: app.globalData.isLogin,
                //       });
                //       that.confirmBill();
                //     });
                //   },
                //   fail: function (res) {
                //     console.log("获取用户手机号错误");
                //   },
                // });
              } else {
                console.log("获取手机号失败！" + res.errMsg);
              }
            },
          });
        },
      });
    }
  },
});
