// pages/wodeBillDetail/index.js
const app = getApp();
import { formatDateYMD } from "../../utils/dateUtil";
const commonUtil = require("../../utils/commonUtil.js");
import { customRequest } from '../../utils/request.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    inputVal: "搜索姓名",
    // settlePrice:'',
    // settleUnit:'',
    searchParam: {
      pageNum: 1,
      pageSize: 40,
      keys: "",
      status: "",
    },
    recordList: [], // 账单详情列表
    factoryBill: {}, // 账单详情
    billInfo: {}, // 列表传输过来的账单信息
    currentDetail: {}, // 当前对象详情
    currIndex: 0,
    chaShowed: false,
    dialog: false,
    isChecked: false,
    selectTotalSalary: 0, // 待确认选中的总价格
    hasMoreData: false,
    isTrigger: false,
    userInfo: app.globalData.loginUserInfo,
    // img: "/assets/images/shareImg.jpg",
    // img: "http://matripecandy.oss-cn-beijing.aliyuncs.com/1shoudanImg/bg.png",
    img: "https://matripe-cms.oss-cn-beijing.aliyuncs.com/1shoudan/bg.png",
    isAgency: app.globalData.loginUserInfo.agencyStatus == 1 ? true : false,
    isLogin: null,
    canvasId: "canvasId",
    isLoading: false,
    isBtnLoading: false, // 点击确认按钮后的loading判断
    // base64: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    let that = this;
    console.log("options+++++++++++++++++++++++++++++", options);
    // if(wx.getStorageSync('loginUserTokenInfo')){
    //   app.getLoginUserTokenInfo().then((res)=>{
    //     console.log(res);
    //   })
    // }
    new Promise((res, rej) => {
      if (app.globalData.isLogin) {
        console.log("isLogin");
        that.setData({
          isLogin: app.globalData.isLogin,
        });
        res(app.globalData.isLogin);
      } else {
        // 由于 userLogin 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        setTimeout(() => {
          app.userLoginCallback = (res) => {
            that.setData({
              isLogin: app.globalData.isLogin,
            });
          };
          console.log(app.globalData.isLogin);
          res(app.globalData.isLogin);
        }, 500);
      }
    }).then((res) => {
      console.log(res);
      console.log(that.data); ``
      let status;
      let info;
      let index;
      console.log(options);
      if (app.isNotEmptyCheck(options.scene)) {
        var sceneStr = decodeURIComponent(options.scene);
        console.log(sceneStr);
        var sceneJson = commonUtil.sceneToJson(sceneStr);
        if (res) {
          console.log(sceneJson);
          that.data.searchParam.agencyId = sceneJson.agencyId || sceneJson.aId;
          that.data.searchParam.factoryBillId = sceneJson.factoryBillId || sceneJson.fId;
          if (app.isNotEmptyCheck(sceneJson.status)) {
            status = sceneJson.status;
          } else {
            status = 0;
          }
        } else {
          wx.setStorageSync("comeFromPage", "BillInfo");
          wx.setStorageSync("QRBillInfo", sceneJson);
          wx.redirectTo({
            url: "/pages/login/index",
          });
        }
      } else {
        console.log("info");
        info = JSON.parse(options.info);
        that.data.searchParam.agencyId = info.agencyId;
        that.data.searchParam.factoryBillId = info.factoryBillId;
        if (app.isNotEmptyCheck(info.status)) {
          status = info.status;
        } else {
          status = 10;
        }
      }
      if (status == 0) {
        that.data.searchParam.status = "";
        index = 0;
      } else if (status == 10) {
        that.data.searchParam.status = 10;
        index = 1;
      } else if (status == 20) {
        that.data.searchParam.status = 20;
        index = 2;
        wx.setNavigationBarTitle({
          title: "待结算账单",
        });
      } else if (status == 30) {
        that.data.searchParam.status = 30;
        index = 3;
        wx.setNavigationBarTitle({
          title: "已结算账单",
        });
      }
      console.log(that.data.searchParam);
      that.setData({
        searchParam: that.data.searchParam,
        billInfo: info,
        currIndex: index,
      });
      // wx.setNavigationBarTitle({
      // 	title: info.title,
      // });
      wx.showLoading({
        title: "加载中...",
      });
      this.setData({
        isLoading: true,
      });
      that.getList();
    });
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () { },

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
    let that = this;
    return this.getCanvas().then(() => {
      // console.log(this.data.base64);
      return {
        title: this.data.factoryBill.title,
        path: "pages/wodeBillSharePage/index?agencyId=" + this.data.searchParam.agencyId + "&factoryBillId=" + this.data.searchParam.factoryBillId, // 路径，传递参数到指定页面。

        // imageUrl: "../../assets/images/shareImg.jpg",
        imageUrl: this.data.canvasImg,
      };
    });

    // let imgUrl = "../../assets/images/shareImg.jpg";
  },
  getCanvas () {
    const that = this;
    return new Promise((resolve) => {
      var mycenter = 0; //文字左右居中显示
      var myheight = 0; //文字高度
      const query = wx.createSelectorQuery();
      query
        .select("#" + this.data.canvasId)
        .fields({ node: true, size: true })
        .exec((res) => {
          console.log(res);
          const canvas = res[0].node;
          const ctx = canvas.getContext("2d");
          new Promise(function (resolve) {
            // 绘制背景图片
            wx.getImageInfo({
              src: that.data.img, //网络图片,如果不行请换一个
              success (res) {
                console.log(res);
                var width = res.width;
                var height = res.height;
                mycenter = width / 2;
                myheight = height;
                canvas.width = width;
                canvas.height = height;
                const img = canvas.createImage();
                console.log(ctx);
                img.src = res.path;
                img.onload = () => {
                  ctx.drawImage(img, 0, 0, width, height);
                  resolve(true);
                };
              },
            });
          })
            .then(() => {
              ctx.font = "500 70px Arial";
              ctx.textAlign = "left";
              // ctx.fillStyle = "#333";
              ctx.fillStyle = "#fff";
              // console.log(that.data.factoryBill.totalSalary.toString().length);
              // let steNumber = that.data.factoryBill.totalSalary.toString().length
              // ctx.fillRect(40, 168, steNumber * 30, 72);
              ctx.fillText(that.data.factoryBill.totalSalary + "元", 40, 210);
            })
            .then(function () {
              wx.canvasToTempFilePath({
                canvas: canvas,
                success (res) {
                  console.log(res);
                  that.setData({
                    canvasImg: res.tempFilePath,
                    // base64: canvas.toDataURL(),
                  });
                  resolve();
                  // console.log(that.data.canvasImg);
                },
              });
            })
            .catch((err) => { });
        });
    });
  },
  //canvas转为图片
  transferCanvasToImage (canvas) {
    const that = this;
    console.log(canvas);
    wx.canvasToTempFilePath({
      canvas: canvas,
      success (res) {
        console.log(res);
        that.setData({
          canvasImg: res.tempFilePath,
          // base64: canvas.toDataURL(),
        });
        resolve();
        // console.log(that.data.canvasImg);
      },
    });
  },
  /* 
    跳转搜索页面
  */
  goSearch () {
    wx.navigateTo({
      url: "../search/index?from=wodeBillDetail",
    });
  },
  /* 
  清空输入框
  */
  clearInput: function () {
    console.log(123);
    this.setData({
      inputVal: "搜索姓名",
      chaShowed: false,
    });
    this.data.recordList = [];
    this.data.searchParam.keys = "";
    this.data.searchParam.pageNum = 1;
    wx.showLoading({
      title: "加载中...",
    });
    this.getList();
  },
  /* 
    搜索关键词
  */
  searchKey: function (e) {
    console.log("onsearch");
    console.log(this.data.inputVal);
    this.data.recordList = [];
    this.data.searchParam.pageNum = 1;
    this.data.searchParam.keys = this.data.inputVal;
    wx.showLoading({
      title: "加载中...",
    });
    this.getList();
  },
  onScrollToLower: function () {
    this.data.searchParam.pageNum = this.data.searchParam.pageNum + 1;
    wx.showLoading({
      title: "加载中...",
    });
    this.getList();
  },
  onScrollRefresh () {
    this.data.recordList = [];
    this.data.searchParam.pageNum = 1;
    this.setData({
      selectTotalSalary: 0,
    });
    console.log("isonScrollRefresh");
    wx.showLoading({
      title: "加载中...",
    });
    this.getList();
  },

  changeMenu (e) {
    var that = this;
    that.data.searchParam.pageNum = 1;
    if (e.currentTarget.dataset.id == 0) {
      this.data.searchParam.status = "";
    } else if (e.currentTarget.dataset.id == 1) {
      this.data.searchParam.status = 10;
    } else if (e.currentTarget.dataset.id == 2) {
      this.data.searchParam.status = 20;
    }
    console.log(this.data.searchParam.status);
    this.setData({
      currIndex: e.currentTarget.dataset.id,
      recordList: [],
      searchParam: this.data.searchParam,
      selectTotalSalary: 0,
      isChecked: false,
    });
    console.log(this.data.recordList);
    wx.showLoading({
      title: "加载中...",
    });
    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);
      }
    })
    // 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);
    //     }
    //   },
    // });
    this.setData({
      dialog: true,
    });
    // this.data.dialog = true

    console.log("isIntoDetail");
  },
  closeDrawer () {
    this.setData({
      dialog: false,
      currentDetail: {},
    });
  },
  confirmBillDetail () {
    let that = this;
    let ids = {};
    wx.showLoading({
      title: "确认中...",
    });
    ids.recordIds = this.data.currentDetail.id + "";
    ids.factoryBillId = this.data.searchParam.factoryBillId;
    // console.log(ids);
    // return
    this.billSubmit(ids)
  },
  confirmBill () {
    let that = this;
    let ids = {};
    wx.showLoading({
      title: "确认中...",
    });
    let arr = [];

    this.data.recordList.forEach((item) => {
      // console.log(item);
      if (item.checked) {
        arr.push(item.id);
      }
    });
    if (arr.length == 0) {
      wx.showToast({
        title: "您还没有选择名单哦！",
        icon: "none",
        duration: 2000,
      });
      console.log("nolist");
      return;
    }
    ids.recordIds = arr.join(',');
    ids.factoryBillId = this.data.searchParam.factoryBillId;
    // console.log(ids);
    // return
    this.billSubmit(ids)
  },
  billSubmit (ids) {
    let that = this;
    if (!this.data.isBtnLoading) {
      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: 1,
            selectTotalSalary: 0,
            isChecked: false,
          });
          that.getList();
        } else {
          wx.showToast({ title: data.msg, icon: "none", duration: 2000 }); //隐藏消息提示框
        }
        setTimeout(() => {
          that.setData({
            isBtnLoading: false,
          });
          wx.hideLoading();
        }, 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: 1,
      //         selectTotalSalary: 0,
      //         isChecked: false,
      //       });
      //       that.getList();
      //     } else {
      //       wx.showToast({ title: data.msg, icon: "none", duration: 2000 }); //隐藏消息提示框
      //     }
      //     setTimeout(() => {
      //       that.setData({
      //         isBtnLoading: false,
      //       });
      //       wx.hideLoading();
      //     }, 2000);
      //   },
      // });
    }
    that.setData({
      isBtnLoading: true,
    });
  },
  radioChange (e) {
    console.log(e);
  },
  formatNum (num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
      alert("传递参数错误，请检查！");
      return false;
    }
    result = Math.round(num * 100) / 100;
    return result;
  },
  stopEvent (e) {
    // 点击切换单个选择状态以及总价的加减
    let result = this.data.recordList.find((item) => {
      return item.id == e.target.dataset.id;
    });
    let index = this.data.recordList.indexOf(result);
    if (!this.data.recordList[index].checked) {
      this.data.selectTotalSalary = this.formatNum(this.data.selectTotalSalary + this.data.recordList[index].salary);
    } else {
      this.data.selectTotalSalary = this.formatNum(this.data.selectTotalSalary - this.data.recordList[index].salary);
    }
    this.data.recordList[index].checked = !this.data.recordList[index].checked;
    // 单个选择状态反选

    let isTotalChecked = true;
    try {
      this.data.recordList.forEach((item) => {
        console.log(item.checked);
        if (item.checked == false || item.checked == undefined) {
          isTotalChecked = false;
          throw Error();
        }
      });
    } catch (error) { }
    this.setData({
      recordList: this.data.recordList,
      selectTotalSalary: this.data.selectTotalSalary,
      isChecked: isTotalChecked,
    });
    // e.stopPropagation();
  },
  totalChange () {
    this.setData({
      isChecked: !this.data.isChecked,
    });
    this.data.recordList.forEach((item) => {
      if (item.status == 10) {
        item.checked = this.data.isChecked;
      }
    });
    if (this.data.isChecked) {
      this.data.selectTotalSalary = this.data.factoryBill.totalSalary;
    } else {
      this.data.selectTotalSalary = 0;
    }
    this.setData({
      recordList: this.data.recordList,
      selectTotalSalary: this.data.selectTotalSalary,
    });
  },
  getList () {
    let that = this;
    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) => {
          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 = "-";
          }
          if (item.salary != undefined) {
            item.salaryStr = Math.floor(item.salary);
            // console.log(item.salaryStr);
            // item.salaryDot = item.salary.toFixed(2).slice(-2);
            item.salaryDot = item.salary.toFixed(2);
            // console.log(item.salaryDot);
            if (item.salaryDot == "00") {
              item.isInt = true;
            } else {
              item.isInt = false;
            }
          }
          switch (item.status) {
            case 10:
              item.statusStr = "待核对";
              break;
            case 20:
              item.statusStr = "已核对";
              break;
            case 30:
              item.statusStr = "已结算";
              break;
          }
        });
        if (res.data.data.factoryBill.totalSalary != undefined) {
          res.data.data.factoryBill.totalSalaryStr = Math.floor(res.data.data.factoryBill.totalSalary);
          console.log(res.data.data.factoryBill.totalSalaryStr);
          res.data.data.factoryBill.totalSalaryDot = res.data.data.factoryBill.totalSalary.toFixed(2).slice(-2);
          if (res.data.data.factoryBill.totalSalaryDot == "00") {
            res.data.data.factoryBill.isInt = true;
          } else {
            res.data.data.factoryBill.isInt = false;
          }
        }
        if (res.data.data.factoryBill.totalServicePrice != undefined) {
          res.data.data.factoryBill.totalServicePriceStr = Math.floor(res.data.data.factoryBill.totalServicePrice);
          res.data.data.factoryBill.totalServicePriceDot = res.data.data.factoryBill.totalServicePrice.toFixed(2).slice(-2);
          if (res.data.data.factoryBill.totalServicePriceDot == "00") {
            res.data.data.factoryBill.isInt = true;
          } else {
            res.data.data.factoryBill.isInt = false;
          }
        }

        that.setData({
          recordList: that.data.recordList,
          factoryBill: res.data.data.factoryBill,
          isTrigger: false,
        });
        console.log(that.data.factoryBill);
        console.log(that.data.recordList);
      }
      wx.hideLoading();
      that.setData({
        isLoading: false,
      });
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/factory/bill/record/list",
    //   data: that.data.searchParam,
    //   header: app.globalData.headers,
    //   method: "POST",
    //   success: function (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) => {
    //         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 = "-";
    //         }
    //         if (item.salary != undefined) {
    //           item.salaryStr = Math.floor(item.salary);
    //           // console.log(item.salaryStr);
    //           // item.salaryDot = item.salary.toFixed(2).slice(-2);
    //           item.salaryDot = item.salary.toFixed(2);
    //           // console.log(item.salaryDot);
    //           if (item.salaryDot == "00") {
    //             item.isInt = true;
    //           } else {
    //             item.isInt = false;
    //           }
    //         }
    //         switch (item.status) {
    //           case 10:
    //             item.statusStr = "待核对";
    //             break;
    //           case 20:
    //             item.statusStr = "已核对";
    //             break;
    //           case 30:
    //             item.statusStr = "已结算";
    //             break;
    //         }
    //       });
    //       if (res.data.data.factoryBill.totalSalary != undefined) {
    //         res.data.data.factoryBill.totalSalaryStr = Math.floor(res.data.data.factoryBill.totalSalary);
    //         console.log(res.data.data.factoryBill.totalSalaryStr);
    //         res.data.data.factoryBill.totalSalaryDot = res.data.data.factoryBill.totalSalary.toFixed(2).slice(-2);
    //         if (res.data.data.factoryBill.totalSalaryDot == "00") {
    //           res.data.data.factoryBill.isInt = true;
    //         } else {
    //           res.data.data.factoryBill.isInt = false;
    //         }
    //       }
    //       if (res.data.data.factoryBill.totalServicePrice != undefined) {
    //         res.data.data.factoryBill.totalServicePriceStr = Math.floor(res.data.data.factoryBill.totalServicePrice);
    //         res.data.data.factoryBill.totalServicePriceDot = res.data.data.factoryBill.totalServicePrice.toFixed(2).slice(-2);
    //         if (res.data.data.factoryBill.totalServicePriceDot == "00") {
    //           res.data.data.factoryBill.isInt = true;
    //         } else {
    //           res.data.data.factoryBill.isInt = false;
    //         }
    //       }

    //       that.setData({
    //         recordList: that.data.recordList,
    //         factoryBill: res.data.data.factoryBill,
    //         isTrigger: false,
    //       });
    //       console.log(that.data.factoryBill);
    //       console.log(that.data.recordList);
    //     }
    //     wx.hideLoading();
    //     that.setData({
    //       isLoading: false,
    //     });
    //   },
    // });
  },
  copyText () {
    console.log(this.data.factoryBill.remark);
    wx.setClipboardData({
      //复制文本
      data: this.data.factoryBill.title + "核对，如有疑问请及时联系，" + (this.data.factoryBill.remark ? this.data.factoryBill.remark + "，" : "") + "感谢支持！",
      success: function (res) {
        wx.getClipboardData({
          //获取复制文本
          success: function (res) {
            console.log(res);
            wx.showToast({
              title: "复制成功",
              icon: "none", //是否需要icon
              mask: "ture", //是否设置点击蒙版，防止点击穿透
            });
          },
        });
      },
    });
  },
});
