// pages/mine/mine.js
const app = getApp();
import { timeShowXXX } from "../../utils/dateUtil";
const commonUtil = require("../../utils/commonUtil.js");

import { customRequest } from '../../utils/request.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    appId: app.globalData.appId,

    isopen: 1, // 账户余额是否显示
    iosDialog: false,
    iosDialogTobe: false,
    isLoading: true, // 成为代理loading效果
    isLogin: app.globalData.isLogin,
    // user:app.globalData.user,
    serviceInfo: {},
    map: { num10: "0", num20: "0", num25: "0", num30: "0", num40: "0", num999: "0", user999: "0", user40: "0", user48: "0", user50: "0", billStatus10Salary: "0", billStatus30Salary: "0" },
    motto: "Hello World",
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse("button.open-type.getUserInfo"),
    canIUseGetUserProfile: false,
    // 如需尝试获取用户信息可改为false
    underReviewNum: -1,
    underReviewList: [],
    searchParam: {},
    recordBillType: "",
    configInfo: {},
    teamList: [],
    drawerShow: false,
    tabGroup: [
      {
        name: '全部',
        key: '0',
        picked: ''
      },
      {
        name: '在招中',
        key: '1',
        picked: '1'
      },
      {
        name: '已停招',
        key: '2',
        picked: '0'
      },
    ],
    choiceCollect: '0',
    storeJobListSearchForm: {
      pageNum: 1,
      pageSize: 20,
      classify: 1,
      sex: -1,
      workTypeStr: "",
      lat: "",
      lng: "",
      jobClassify: "",
      sortTag: 0,
      jobRequestLabelIds: "",
      cityName: "",
      brandIds: "",
      jobCategoryLabelIds: "",
      ucj: 0,
    },
    recordList: []
    // agencyStatus: 0, // 是否是代理判断
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    setTimeout(() => {
      console.log(app.globalData.loginUserInfo);
      this.setData({
        isLogin: app.globalData.isLogin,
        hasUserInfo: app.globalData.hasUserInfo,
        // agencyStatus: app.globalData.loginUserInfo.agencyStatus,
        userInfo: app.globalData.loginUserInfo,
        serviceInfo: app.globalData.serviceInfo,
        corpUserFlag: app.globalData.loginUserInfo.corpUserFlag,
        loginUserInfo: wx.getStorageSync("loginUser")
      });
      if (app.globalData.isLogin) {
        this.getTeamList()
        this.getJobList()

      }
    }, 100);
  },
  hidedrawershow (e) {
    console.log(e);
    this.setData({
      [e.detail.type]: false
    })
    console.log(this.data.drawerShow);
  },
  showToggle () {
    if (this.data.isLogin) {
      this.getTabBar().setData({
        isShow: false,
      });
      this.setData({
        drawerShow: true
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/index'
      })
    }

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("isshow");
    let that = this;

    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 4,
        isShow: true
      });
    }
    wx.setStorageSync("comeFromPage", "me");
    if (wx.getStorageSync("configInfo")) {
      this.setData({
        configInfo: { ...wx.getStorageSync("configInfo"), biao: false },
      });
      console.log('configInfo', this.data.configInfo);
    }
    wx.setStorageSync('BILLFROM', 'mine')

    // wx.showTabBar({
    //   success(e) {},
    // });
    // if (!app.globalData.isLogin) {
    //   wx.setStorageSync('comeFromPage', "me")
    //   wx.redirectTo({
    // 		url: "/pages/login/index",
    // 	});
    // } else {
    // 	wx.switchTab({
    // 		url: "/pages/mine/index",
    // 	});
    // }
    // let serviceInfo =  wx.getStorageSync('ServiceInfo')
    setTimeout(() => {
      if (app.globalData.isLogin) {
        console.log(that.data.userInfo);
        that.setData({
          isLogin: app.globalData.isLogin,
          hasUserInfo: app.globalData.hasUserInfo,
          // agencyStatus: app.globalData.loginUserInfo.agencyStatus,
          userInfo: app.globalData.loginUserInfo,
          serviceInfo: app.globalData.serviceInfo,
          corpUserFlag: app.globalData.loginUserInfo.corpUserFlag,
        });
        that.getDataNum();
      } else {
        // 由于 userLogin 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        // app.userLoginCallback = (res) => {
        setTimeout(() => {
          console.log(that.data.userInfo);
          that.setData({
            isLogin: app.globalData.isLogin,
            hasUserInfo: app.globalData.hasUserInfo,
            userInfo: app.globalData.loginUserInfo,
            // agencyStatus: app.globalData.agencyStatus,
            serviceInfo: app.globalData.serviceInfo,
          });
        }, 100);
        // };
      }
      console.log(that.data.serviceInfo);
      // this.watch();
    }, 100);
    // this.getConfigInfo();

  },

  watch () {
    // var obj = app.globalData;
    // this.setData({
    // 	isLogin: obj.isLogin,
    // });
  },

  onTabItemTap (item) {
    console.log(item.index);
    console.log(item.pagePath);
    console.log(item.text);
  },


  getTeamList () {
    let that = this
    customRequest("/yishoudan/agency/group/user/listByUser", { header: 'headers', method: 'GET', data: {} }).then((res) => {
      console.log(res);
      res.data.data.forEach(item => {
        if (item.id == app.globalData.loginUserInfo.user.agencyId) {
          item.checked = true;
        }
      });
      console.log('res.data.data', res.data.data);
      that.setData({
        teamList: res.data.data
      })
    })
  },
  checkToken (_item) {
    let that = this
    wx.setStorageSync("LOGINUSER_ID", _item.id);
    customRequest('/appLoginByToken', { header: 'headers', method: 'GET', data: {} }).then((res) => {
      console.log(res);
      app.globalData.agencyStatus = res.data.data.agencyStatus;
      app.globalData.loginUserInfo = res.data.data;
      wx.setStorageSync("loginUser", res.data.data);
      wx.setStorageSync("LOGINUSER_ID", res.data.data.user.agencyId);
      this.getTabBar().setData({
        isShow: true,
      });
      this.setData({
        drawerShow: false
      })
      that.onLoad()
      that.onShow()

    })
  },
  toogleTeam (e) {
    console.log(e);
    let that = this
    let item = e.currentTarget.dataset.item;
    console.log(item);
    if (wx.getStorageSync("LOGINUSER_ID") == item.id) {
      return false
    }
    wx.showLoading({
      title: '切换中...',
    });
    customRequest(`/yishoudan/agency/group/user/changeGroup/${item.id}`, { header: 'headers', method: 'GET', data: {} }).then((res) => {
      console.log(res);
      if (res.data.status == 200) {
        that.checkToken(item)
        app.getConfigInfo()
        app.getServiceInfo()
        wx.hideLoading();
        wx.showToast({
          title: '切换成功',
          icon: 'success',
          duration: 2000
        })
        // that.data.teamList.forEach(item => {
        //   item.checked = false
        //   if (item.id == item.id) {
        //     item.checked = true;
        //   }
        // })
        // that.setData({
        //   teamList: that.data.teamList
        // })
      } else {
        that.getTeamList()
      }
    })
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log(123);

    this.setData({
      iosDialog: false,
      iosDialogTobe: false,
    });
    wx.onAppRoute({
      success (item) {
        console.log(item);
      },
      fail: function (item) {
        console.log(item);
      },
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // var that = this;
    // console.log(that.data.isLogin)
    // if(!that.data.isLogin){
    //   wx.setStorageSync('comeFromPage', "me")
    //   wx.redirectTo({
    // 		url: "/pages/login/index",
    // 	});
    // }
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
    return app.sharePageImage()
  },
  showbalance (e) {
    this.setData({
      isopen: e.mark.open,
    });
  },
  showdialog () {
    this.setData({
      iosDialog: true,
    });
  },
  fabu () {

    // wx.navigateTo({
    //   url: '/pages/publishJob/index'
    // })  
    if (this.data.userInfo.agencyStatus != 1) {
      wx.showModal({
        title: '',
        content: `您现在还不是伯才用户，加入伯才后可新增职位`,
        cancelColor: "#333333",
        confirmText: "加入伯才",
        confirmColor: "#1890ff",
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: '/pages/tobeAgency/index'
            })

          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/mineJob/index'
      })
    }

  },
  showTobe () {
    if (this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/tobeAgency/index'
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/index'
      })
    }

    // this.setData({
    //   iosDialogTobe: true,
    // });
  },
  closeDialog () {
    this.setData({
      iosDialog: false,
      iosDialogTobe: false,
    });
  },
  login () {
    // this.setData({
    //   isLogin:true
    // })

    app.globalData.isLogin = true;
    wx.reLaunch({
      url: "/pages/mine/index",
    });
  },

  makePhoneCall () {
    console.log(1);
    var that = this;
    wx.makePhoneCall({
      // number: that.data.jobDetail.assistantUserTel + ""
      phoneNumber: that.data.serviceInfo.workPhone || "0371-6611 3723",
    });
  },
  /**
   * 前往工单页面
   *
   *
   */
  goList () {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: "/pages/login/index",
      });
    } else {
      wx.switchTab({
        url: "../myBill/index?status=0",
      });
    }
  },

  /**
   * 获取各个数量
   *
   *
   */
  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,
        });
        console.log('getDataNum', 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,
    //       });
    //     }
    //   },
    // });
  },
  /**
   * 二维码加载laoding隐藏
   *
   *
   */
  imageLoad () {
    this.setData({
      isLoading: false,
    });
  },
  addJob () {
    if (this.data.userInfo.agencyStatus != 1) {
      wx.showModal({
        title: '',
        content: `您现在还不是伯才用户，加入伯才后可新增职位`,
        cancelColor: "#333333",
        confirmText: "加入伯才",
        confirmColor: "#1890ff",
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: '/pages/tobeAgency/index'
            })

          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })

    } else {
      wx.navigateTo({
        url: '/pages/publishJob/index'
      })
    }
  },
  toTodayData () {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: "/pages/login/index",
      });
    } else {
      wx.navigateTo({
        url: "/subPage/todayData/index",
      });
    }
  },
  modalMove () {
    return false;
  },
  collectChange (e) {  // if (that.data.isLogin || (!that.data.isLogin && e.currentTarget.dataset.item.key == 0)) {
    let that = this
    if (e.currentTarget.dataset.item) {
      let item = e.currentTarget.dataset.item
      that.data.choiceCollect = item.key;
      // that.data.storeJobListSearchForm.ucj = e.currentTarget.dataset.id;
      that.data.storeJobListSearchForm.sortTag = item.key;
      that.data.storeJobListSearchForm.picked = item.picked;
      that.data.storeJobListSearchForm.pageNum = 1;
      that.setData({
        choiceCollect: that.data.choiceCollect,
        storeJobListSearchForm: that.data.storeJobListSearchForm,
        recordList: [],
        hasMoreData: true,
      });
      that.getJobList();
    }
  },
  getJobList ($type) {
    let that = this
    customRequest("/yishoudan/custom/job/listV2", {
      method: 'post',
      header: 'headers',
      data: {
        ...that.data.storeJobListSearchForm,
        // recruitment: 1
      }
    }).then((res) => {
      console.log("职位列表↓↓↓↓");
      console.log(res);
      if ($type == 'search') {
        that.setData({
          // isSwiper: true,
          // inputVal: ''
        })
      }
      let data = res.data.data
      that.setData({
        totalPage: data.pageCount,
        currPage: data.currentPage,
      });

      setTimeout(function () {
        that.setData({
          triggered: false,
        });
      }, 1000);
      if (data.recordList) {
        data.recordList.forEach((i) => {
          i.minMonthlyPay = i.minMonthlyPay / 100
          i.maxMonthlyPay = i.maxMonthlyPay / 100
          if (i.jobSpecialLabelNames && i.jobSpecialLabelNames.length > 0) {
            i.labelGroup = i.jobSpecialLabelNames.split(', ').filter((itm, inx) => {
              return inx < 6
            }).map(itm => {
              return itm
            })
          } else {
            i.labelGroup = [];
          }
        })
      }
      if (
        data.recordList == null ||
        data.recordList.length == 0 ||
        data.recordList.length <
        that.data.storeJobListSearchForm.pageSize
      ) {
        console.log('from 搜索')
        var jobListTemp = commonUtil.disposeJobListData(
          data.recordList
        );

        that.data.recordList = that.data.recordList.concat(jobListTemp);

        that.setData({
          recordList: that.data.recordList,
          hasMoreData: false,
          isTrigger: false,
        });
      } else {
        console.log('from 其他')
        var jobListTemp = commonUtil.disposeJobListData(
          data.recordList
        );
        that.data.recordList = that.data.recordList.concat(jobListTemp);

        that.setData({
          recordList: that.data.recordList,
          hasMoreData: true,
          isTrigger: false,
        });
      }

      that.setData({
        loading: false,
        pageShow: true,
        storeJobListSearchForm: that.data.storeJobListSearchForm,
      });


      that.data.recordList.forEach((item, index) => {
        // console.log(item);
        // item.logoStr = item.jobName.slice(0,2)
        if (
          app.isNotEmptyCheck(item.returnFeeType) ||
          item.returnFeeType == "0" ||
          item.returnFee == "0"
        ) {
          item["fuWuFei"] = commonUtil.getReturnFeeTypeName1ById(
            item.returnFeeType,
            item.returnFee / 100
          );

        } else {
          item["fuWuFei"] = "";
        }
        // 简版弹窗通告显示
        if (item.id == that.data.currentJobDrawer.id) {
          item["jobDesp"] = item.jobDesp
            .replace(/\*\*\*\*\*/g, "")
            .split("————————")[0];
          // 展示用字段
          item["jobDesp1"] = item.jobDesp.replace(
            "⚠",
            "<i class='t-icon t-icon-zhuyi' style='margin-bottom:-2px;width:17px;height:17px;background-repeat:no-repeat;background-size:100% 100%'></i>"
          );
          item["jobDesp1"] = item.jobDesp1.replace(
            "[红包]",
            "<i class='t-icon t-icon-hongbao' style='margin-bottom:-2px;width:17px;height:17px;background-repeat:no-repeat;background-size:100% 100%'></i>"
          );
          that.data.currentJobDrawer = {
            ...item,
            index: that.data.currentJobDrawer.index ?
              that.data.currentJobDrawer.index : null,
          };
        }
      });
      console.log(' that.data.recordList', that.data.recordList);
      that.setData({
        recordList: that.data.recordList,
        currentJobDrawer: that.data.currentJobDrawer,
      });
      wx.hideLoading({
        success: (res) => { },
      });
      resolve();
      that.getTag();
      // if (that.data.recordList.length < data.recordCount) {
      // 	that.setData({
      // 		hasMoreData: true,
      // 	});
      // } else {
      // 	that.setData({
      // 		hasMoreData: false,
      // 	});
      // }
    })
  }
});
