// index.js
// 获取应用实例
const app = getApp();
import { timeShowXXX } from "../../utils/dateUtil";
import { customRequest } from '../../utils/request.js';
Page({
  data: {
    isLoading:true,
    serviceInfo:{},
    iosDialog:false,
    isLogin: false,
    map: { num10: '00', num20: '00', num25: '00', num30: '00', num40: '00', num999: '00', user999: "00", user40: "00", user48: "00", user50: "00" },
    motto: "Hello World",
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse("button.open-type.getUserInfo"),
    canIUseGetUserProfile: false,
    // 如需尝试获取用户信息可改为false
    underReviewNum: -1,
    underReviewList: [],
    searchParam: {},
    recordBillType: '',
    configInfo: {},
  },
  // 事件处理函数
  bindViewTap () {
    wx.navigateTo({
      url: "../logs/logs",
    });
  },
  onLoad () {
    console.log(this.setData);
    this.wxLogin();
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        isShow: true,
        selected: 3,
      });
    }

    setTimeout(() => {
      this.setData({
        serviceInfo: app.globalData.serviceInfo,
        userInfo: app.globalData.loginUserInfo,
      
      });
      if (app.globalData.isLogin) {
        this.getTeamList()

      }
    }, 100);
  },
  onUnload () {
    wx.removeStorage({
      key: 'townsManInfo',
    })
    wx.removeStorage({
      key: 'townsManInfoJob',
    })
  },
  onShow () {
    let that= this;
    // if (!app.globalData.isLogin) {
    //   wx.setStorageSync('comeFromPage', "set")
    //   wx.redirectTo({
    //     url: "/pages/login/index",
    //   });
    //   return
    // }
    if (wx.getStorageSync("configInfo")) {
      this.setData({
        configInfo: { ...wx.getStorageSync("configInfo"), biao: false },
      });
      console.log('configInfo',this.data.configInfo);
    }
    this.setData({
      isLogin: app.globalData.isLogin,
    });
    console.log(this.data.isLogin);
    // if (app.globalData.isLogin) {
    // 	this.collectedStoreJobList();
    // } else {

    wx.removeStorage({
      key: 'townsManInfo',
    })
    wx.removeStorage({
      key: 'townsManInfoJob',
    })

    this.getBillNum();
    this.getDataNum();
    // }
    setTimeout(() => {
      if (app.globalData.isLogin) {
        that.setData({
          userInfo: app.globalData.loginUserInfo,
        });
      } else {
        setTimeout(() => {
          that.setData({
            userInfo: app.globalData.loginUserInfo,
          });
        }, 100);
        // };
      }
      console.log(that.data.serviceInfo);
      // this.watch();
    }, 100);
  },
  getUserProfile (e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: "展示用户信息", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
        });
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },
  changeRecordBillType (e) {
    let that = this;
    console.log(e);
    that.setData({
      recordBillType: e.currentTarget.dataset.type,
    });
  },
  chooseIdCard () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success (res) {
        console.log(res);
        wx.navigateTo({
          url: `../newEnroll/enroll/index?applyType=2&imgUrl=${JSON.stringify(res)}`,
        });
        // that.uploadIdcardImg(res);
      },
    });
  },
  navigatorToRecord () {
    console.log("点击跳转");
    wx.navigateTo({
      url: `../newEnroll/enroll/index?applyType=2`,
    });
  },
  // 打开弹窗
  openModal(){
    this.setData({
      iosDialog: true,
    });
  },
  closeDialog () {
    this.setData({
      iosDialog: false,
      iosDialogTobe: false,
    });
  },
  imageLoad () {
    this.setData({
      isLoading: false,
    });
  },
  getUserInfo (e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e);
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true,
    });
  },
  getUserinfo (e) {
    console.log(e);
    console.log(this.is);
    console.log(getApp().globalData);
  },
  tabbarchange (e) {
    app.globalData.tabbarinfo = e.mark.tabinfo;
    this.setData({
      tabbarinfo: app.globalData.tabbarinfo,
    });
    console.log(app.globalData.tabbarinfo);
  },
  wxLogin () {
    var that = this;
    wx.login({
      success (res) {
        if (res.code) {
          that.setData({
            wxCode: res.code,
          });
        } else {
          console.log("获取code失败！" + res.errMsg);
        }
      },
    });
  },
  getBillNum () {
    let that = this;
    customRequest("/yishoudan/user/apply/order/listStatisticsNum", {
      header: 'headers', method: 'GET', data: {
        code: that.data.wxCode,
        // iv: iv,
        // encryptedData: encryptedData,
        type: "yishoudan",
      }
    }).then((res) => {
      if (res.data.status == 200) {
        that.setData({
          underReviewNum: res.data.data.num10,
        });
      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/user/apply/order/listStatisticsNum",
    //   header: app.globalData.headers,
    //   data: {
    //     code: that.data.wxCode,
    //     // iv: iv,
    //     // encryptedData: encryptedData,
    //     type: "yishoudan",
    //   },
    //   success (res) {
    //     console.log(res);
    //     if (res.data.status == 200) {
    //       that.setData({
    //         underReviewNum: res.data.data.num10,
    //       });
    //     }
    //   },
    // });
  },
  getDataNum () {
    let that = this;
    customRequest("/statistics/home", { header: 'headers', method: 'GET', data: {} }).then((res) => {
      if (res.data.status == 200) {
        that.setData({
          map: res.data.data,
        });
      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/statistics/home",
    //   header: app.globalData.headers,
    //   success (res) {
    //     console.log(res);
    //     if (res.data.status == 200) {
    //       that.setData({
    //         map: res.data.data,
    //       });
    //     }
    //   },
    // });
  },
  getPhoneNumber (e) {
    var that = this;
    console.log(e);
    console.log(e.detail.errMsg);
    /*wx.setStorageSync({
            key: "jobDetailStorage",
            data: that.data.recordList[e.currentTarget.dataset.idx]
        });*/

    // wx.setStorageSync("jobDetailStorage", that.data.recordList[e.currentTarget.dataset.idx]);

    // console.log(e);
    // console.log(e.detail.errMsg)
    // console.log(e.detail.iv)
    // console.log(e.detail.encryptedData)
    if ("getPhoneNumber:ok" == e.detail.errMsg) {
      //同意
      var iv = e.detail.iv;
      // console.log(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) => {
              console.log(res);
            });
            if (e.currentTarget.dataset.type == "bill") {
              promise.then((res) => {
                that.setData({
                  isLogin: app.globalData.isLogin,
                });
                wx.navigateTo({
                  url: "/pages/myBill/index?status=" + e.currentTarget.dataset.status,
                  //url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
                });
              });
            } else if (e.currentTarget.dataset.type == "townsman") {
              promise.then((res) => {
                that.setData({
                  isLogin: app.globalData.isLogin,
                });
                wx.navigateTo({
                  url: "/pages/townsMan/index?status=" + e.currentTarget.dataset.status,
                  //url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
                });
              });
            } else if (e.currentTarget.dataset.type == "toUnderReview") {
              promise.then((res) => {
                that.setData({
                  isLogin: app.globalData.isLogin,
                });
                that.toUnderReview();
                // wx.navigateTo({
                // 	url: "/pages/underReview/index?list=" + list,
                // 	//url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
                // });
              });
            } else {
              if (that.data.recordBillType == "photo" || that.data.recordBillType == "record") {
                if (that.data.recordBillType == "photo") {
                  that.chooseIdCard()
                } else {
                  that.navigatorToRecord()
                }
              } else {
                let argument;
                argument = JSON.stringify(e.currentTarget.dataset.info).replace(/\=|\&/g, "3D");
                wx.navigateTo({
                  url: `../newEnroll/index?applyType=2&info=${argument}`,
                });
              }
            }
          })
          // 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) => {
          //       console.log(res);
          //     });
          //     if (e.currentTarget.dataset.type == "bill") {
          //       promise.then((res) => {
          //         that.setData({
          //           isLogin: app.globalData.isLogin,
          //         });
          //         wx.navigateTo({
          //           url: "/pages/myBill/index?status=" + e.currentTarget.dataset.status,
          //           //url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
          //         });
          //       });
          //     } else if (e.currentTarget.dataset.type == "townsman") {
          //       promise.then((res) => {
          //         that.setData({
          //           isLogin: app.globalData.isLogin,
          //         });
          //         wx.navigateTo({
          //           url: "/pages/townsMan/index?status=" + e.currentTarget.dataset.status,
          //           //url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
          //         });
          //       });
          //     } else if (e.currentTarget.dataset.type == "toUnderReview") {
          //       promise.then((res) => {
          //         that.setData({
          //           isLogin: app.globalData.isLogin,
          //         });
          //         that.toUnderReview();
          //         // wx.navigateTo({
          //         // 	url: "/pages/underReview/index?list=" + list,
          //         // 	//url: "../enroll/index?applyType=1&tel=" + res.data.data.phoneNumber
          //         // });
          //       });
          //     } else {
          //       if (that.data.recordBillType == "photo" || that.data.recordBillType == "record") {
          //         if (that.data.recordBillType == "photo") {
          //           that.chooseIdCard()
          //         } else {
          //           that.navigatorToRecord()
          //         }
          //       } else {
          //         let argument;
          //         argument = JSON.stringify(e.currentTarget.dataset.info).replace(/\=|\&/g, "3D");
          //         wx.navigateTo({
          //           url: `../newEnroll/index?applyType=2&info=${argument}`,
          //         });
          //       }
          //     }
          //   },
          //   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);
                  var collected = e.currentTarget.dataset.collected;
                  if (collected) {
                    promise.then((res) => {
                      that.setData({
                        isLogin: app.globalData.isLogin,
                      });
                    });
                  }
                })
                // 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);
                //     var collected = e.currentTarget.dataset.collected;
                //     if (collected) {
                //       promise.then((res) => {
                //         that.setData({
                //           isLogin: app.globalData.isLogin,
                //         });
                //       });
                //     }
                //   },
                //   fail: function (res) {
                //     console.log("获取用户手机号错误");
                //   },
                // });
              } else {
                console.log("获取手机号失败！" + res.errMsg);
              }
            },
          });
        },
      });
    } else {
      //拒绝
      var collected = e.currentTarget.dataset.collected;
      if (collected) {
        try {
          wx.setStorageSync("comeFromPage", "index");
        } catch (e) {
          console.log("index-页面跳转，设置参数错误：", e);
        }
        wx.navigateTo({
          url: "/pages/login/index",
        });
      } else {
        wx.navigateTo({
          url: "../enroll/index?applyType=2",
        });
      }
    }
    return false;
  },
  toUnderReview () {
    let that = this;

    this.setData({
      ["searchParam.status"]: 10,
      ["searchParam.pageSize"]: 100,
    });
    // that.data.searchParam.status = 10
    that.getList(true);

    setTimeout(() => {

    }, 200);
  },
  toTodayData () {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: "/pages/login/index",
      });
    } else {
      wx.navigateTo({
        url: "/subPage/todayData/index",
      });
    }
  },
  goList () {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: "/pages/login/index",
      });
    } else {
      wx.switchTab({
        url: "../myBill/index?status=0",
      });
    }
  },
  getList: function (under) {
    var that = this;
    wx.showLoading({
      title: "加载中",
    });
    customRequest("/yishoudan/user/apply/order/list", { header: 'headers', method: 'GET', data: that.data.searchParam }).then((res) => {
      if (res.data.status == 200) {
        if (res.data.data.recordList != null && res.data.data.recordList.length > 0) {
          res.data.data.recordList.forEach((item) => {
            item["updateTimeStr"] = timeShowXXX(item.updateTime);
            if (item.status == 10) {
              // debugger;
              item["statusText"] = "审核中";
            } else if (item.status == 20) {
              item["statusText"] = "待面试";
            } else if (item.status == 30) {
              item["statusText"] = "待入职";
            } else if (item.status == 40) {
              item["statusText"] = "在职中";
            } else if (item.status == 999) {
              item["statusText"] = "已完成";
            }

            if (app.isNotEmptyCheck(item.userServeRecordDespLatest)) {
              item.userServeRecordDespLatest = item.userServeRecordDespLatest.replace(/「/g, "<span style='color:#4DB54B;margin-right:4px;'>").replace(/」/g, "</span>");
            }
          });
        }
        // console.log(res.data.data);
        if (under) {
          that.setData({
            underReviewList: res.data.data.recordList,
          });
          // if (that.data.underReviewList.length > 0) {
          console.log(that.data.underReviewList);
          let list = JSON.stringify(that.data.underReviewList);
          wx.navigateTo({
            url: "/pages/underReview/index?list=" + list,
          });
          // }
        }
        // wx.hideLoading();=
      } else {
        app.showTips(that, res.data.msg);
      }
      wx.hideLoading();
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/user/apply/order/list",
    //   data: that.data.searchParam,
    //   header: app.globalData.headers,
    //   method: "GET",
    //   success: function (res) {
    //     console.log(res.data);
    //     if (res.data.status == 200) {
    //       if (res.data.data.recordList != null && res.data.data.recordList.length > 0) {
    //         res.data.data.recordList.forEach((item) => {
    //           item["updateTimeStr"] = timeShowXXX(item.updateTime);
    //           if (item.status == 10) {
    //             // debugger;
    //             item["statusText"] = "审核中";
    //           } else if (item.status == 20) {
    //             item["statusText"] = "待面试";
    //           } else if (item.status == 30) {
    //             item["statusText"] = "待入职";
    //           } else if (item.status == 40) {
    //             item["statusText"] = "在职中";
    //           } else if (item.status == 999) {
    //             item["statusText"] = "已完成";
    //           }

    //           if (app.isNotEmptyCheck(item.userServeRecordDespLatest)) {
    //             item.userServeRecordDespLatest = item.userServeRecordDespLatest.replace(/「/g, "<span style='color:#4DB54B;margin-right:4px;'>").replace(/」/g, "</span>");
    //           }
    //         });
    //       }
    //       // console.log(res.data.data);
    //       if (under) {
    //         that.setData({
    //           underReviewList: res.data.data.recordList,
    //         });
    //         // if (that.data.underReviewList.length > 0) {
    //         console.log(that.data.underReviewList);
    //         let list = JSON.stringify(that.data.underReviewList);
    //         wx.navigateTo({
    //           url: "/pages/underReview/index?list=" + list,
    //         });
    //         // }
    //       }
    //       // wx.hideLoading();=
    //     } else {
    //       app.showTips(that, res.data.msg);
    //     }
    //     wx.hideLoading();
    //   },
    // });
  },
});
