// pages/myAgent/index.js
const app = getApp();
import dateUtil from "../../utils/dateUtil";
import { customRequest } from '../../utils/request.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    toped: -1,
    statusBarHeight: wx.getStorageSync("statusBarHeight"), // 状态栏高度
    navigationBarHeight: wx.getStorageSync("navigationBarHeight"), // 导航栏高度
    menuButtonHeight: wx.getStorageSync("menuButtonHeight"), // 胶囊按钮高度
    menuButton: wx.getStorageSync("menuButtonInfo"), // 胶囊信息
    chaShowed: false,
    openText: "最近维护",
    chooseActive: 1,
    isOpen: false,
    isTrigger: false,
    pageBean: {},
    inputShowed: false,
    inputVal: "搜索姓名",
    recordList: [],
    currIndex: "0",
    phoneDialog: false,
    searchKeyFlag: false,
    searchParam: {
      pageNum: 1,
      pageSize: 20,
      keys: "",
      searchTag: 1,
      status: -1,
      sortField: "updateTime",
      sortType: "desc",
    },
    isLoading: true,
    hasMoreData: true,
  },
  closeChoose () {
    this.setData({
      isOpen: false,
    });
  },
  openChoose () {
    if (this.data.isOpen) {
      this.setData({
        isOpen: false,
      });
    } else {
      this.setData({
        isOpen: true,
      });
    }
  },
  changeOpenMenu (e) {
    var that = this;
    setTimeout(function () {
      that.closeChoose();
    }, 500);
    let param = this.data.searchParam;
    if (e.currentTarget.dataset.id == 1) {
      //最近维护
      param.sortField = "updateTime";
      param.sortType = "desc";
    } else {
      if (this.data.currIndex == 40) {
        //当前在职
        param.sortField = "entryTime";
      } else if (this.data.currIndex == 48) {
        //准备离职
        param.sortField = "willLeaveTime";
      } else if (this.data.currIndex == 50) {
        //最近离职
        param.sortField = "leaveTime";
      }
      param.sortType = e.currentTarget.dataset.id == 2 ? "desc" : "asc";
    }

    this.setData({
      chooseActive: e.currentTarget.dataset.id,
      openText: e.currentTarget.dataset.text,
      recordList: [],
      searchParam: param,
    });
    this.getList();
  },
  onScrollToLower: function () {
    if (this.data.hasMoreData) {
      this.data.searchParam.pageNum = this.data.searchParam.pageNum + 1;
      this.getList();
    }
  },
  changeMenu (e) {
    var that = this;
    // wx.showLoading({
    // 	title: "加载中...",
    // });
    that.data.searchParam.pageNum = 1;
    that.data.searchParam.searchTag = e.currentTarget.dataset.id;
    that.data.searchParam.status = e.currentTarget.dataset.id;
    // if(e.currentTarget.dataset.id == 40){
    //   this.data.searchParam.status = 40;
    // }else if(e.currentTarget.dataset.id == 1){
    //   this.data.searchParam.status = 48;
    // }else if(e.currentTarget.dataset.id == 2){
    //   this.data.searchParam.status = 50;
    // }

    this.setData({
      currIndex: e.currentTarget.dataset.id,
      recordList: [],
      searchParam: this.data.searchParam,
    });
    this.getList();
  },
  onScrollRefresh () {
    this.data.recordList = [];
    this.data.searchParam.pageNum = 1;
    this.getList();
  },
  searchKey: function (e) {
    console.log(e, this.data.inputVal);
    this.data.recordList = [];
    this.data.searchParam.pageNum = 1;
    this.data.searchParam.keys = this.data.inputVal;
    this.getList();
  },

  showInput: function () {
    this.setData({
      inputShowed: true,
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false,
    });
  },
  clearInput: function () {
    console.log(123);
    this.setData({
      inputVal: "搜索姓名",
      chaShowed: false,
    });
    this.data.recordList = [];
    this.data.searchParam.keys = "";
    this.data.searchParam.pageNum = 1;
    this.getList();
  },
  inputTyping: function (e) {
    console.log(e.detail.value);
    this.setData({
      inputVal: e.detail.value,
    });
    if (this.data.inputVal == "") {
      this.data.searchParam.keys = "";
      this.data.searchParam.pageNum = 1;
      this.getList();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //this.getLocation();
    console.log('options.state',options.state);
    this.setData({
      currIndex: options.state,
      // toped: options.state,
    });
    this.data.searchParam.status = that.data.currIndex;
    that.getList();

    // wx.showLoading({
    // 	title: "加载中...",
    // });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    // if(that.data.currIndex == 1){
    //     this.data.searchParam.status = 48;
    //  }
    console.log(this.data.menuButton);
    console.log('that.data.currIndex',that.data.currIndex);
    // this.data.searchParam.pageNum = 1;
    console.log(this.data.searchParam);

    // if(that.data.currIndex == 0){
    //   this.data.searchParam.status = 0;
    // }else if(that.data.currIndex == 1){
    //   this.data.searchParam.status = 1;
    // }else{
    //   this.data.searchParam.status = 2;
    // }
    console.log(wx.getStorageSync('TOWNSMAN_PAGE_CHANGE'));
    if (wx.getStorageSync('TOWNSMAN_PAGE_CHANGE')) {
      this.setData({
        recordList: [],
        searchParam: { ...this.data.searchParam, pageNum: 1 }
      })
      that.getList();
      wx.removeStorageSync('TOWNSMAN_PAGE_CHANGE')
    }
    try {
      //详情页修改完，在列表更新一下，不请求后台刷新列表
      var value = wx.getStorageSync("storageSyncUpdateUserOfUserDetails");
      if (value) {
        for (var i = 0; i < that.data.recordList.length; i++) {
          if (that.data.recordList[i].id == value.id) {
            that.data.recordList[i].userName = value.userName;
            that.setData({
              recordList: that.data.recordList,
            });

            try {
              wx.removeStorageSync("storageSyncUpdateUserOfUserDetails");
            } catch (e) {
              console.log("详情页修改完，在列表更新一下，不请求后台刷新列表，删除缓存错误:", e);
            }
          }
        }
      }
    } catch (e) {
      console.log("详情页修改完，在列表更新一下，不请求后台刷新列表错误:", e);
    }
  },
  goSearch () {
    wx.navigateTo({
      url: "../search/index?from=townMan",
    });
  },

  goDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    var binded = e.currentTarget.dataset.binded;

    wx.navigateTo({
      // url: '/pages/editAgent/index?agencyId=' + id,
      // url:'/pages/agentDetail/index?agencyId=' + id
      url: "/pages/townsmanDetail/index?userId=" + id + "&binded=" + binded,
    });
  },

  getList: function () {
    var that = this;
    wx.showLoading({
      title: "加载中...",
    });
    that.setData({
      isLoading: true,
    });
    that.data.searchParam.keys = that.data.inputVal == "搜索姓名" ? "" : that.data.inputVal;
    that.data.searchParam.binded = that.data.toped;
    console.log('that.data.searchParam',that.data.searchParam);
    customRequest("/yishoudan/agency/user/list",{header:'headers', method: 'POST', data: that.data.searchParam}).then((res)=>{
      if (res.data.status == 200) {
        that.setData({
          isLoading: false,
          searchKeyFlag: that.data.searchParam.keys ? true : false,
        });
        // if (res.data.data.recordList != null && res.data.data.recordList.length > 0) {
        //   res.data.data.recordList.forEach(item => {
        //     item['updateTimeStr'] = dateUtil.timeShowXXX(item.updateTime);
        //     if (app.isEmptyCheck(item.tel)) {
        //       item.tel = '';
        //     }
        //     if (app.isEmptyCheck(item.userName)) {
        //       item.userName = '';
        //     }
        //   });
        // }

        // res.data.data.recordList.forEach((item,index)=>{
        //  if (app.isNotEmptyCheck(item.userServeRecordDespLatest)) {

        //     if (item.userServeRecordDespLatest.indexOf('「协助报名」') == 0) {
        //       if (app.isNotEmptyCheck(item.agencyUserName)) {
        //         item.agencyUserName = '@' + item.agencyUserName;
        //       } else {
        //         item.agencyUserName = '';
        //       }
        //     }

        //     item.userServeRecordDespLatest = item.userServeRecordDespLatest.replace(/「/g, "<span style='color:#4DB54B;margin-right:4px;'>").replace(/」/g, "</span>" + item.agencyUserName);
        //   }
        // })
        res.data.data.recordList.forEach((item) => {
          //  console.log(item.nation.substr(item.nation.length-1,1));
          if (item.nation.substr(item.nation.length - 1, 1) != "族" && item.nation.substr(item.nation.length - 1, 1) != "") {
            item.nation = item.nation + "族";
          }
        });

        if (res.data.data.recordList != null && res.data.data.recordList.length < 20) {
          var recordListTemp = res.data.data.recordList;
          that.data.recordList = that.data.recordList.concat(recordListTemp);
          that.setData({
            hasMoreData: false,
          });
        } else {
          var recordListTemp = res.data.data.recordList;
          that.data.recordList = that.data.recordList.concat(recordListTemp);
          that.setData({
            hasMoreData: true,
          });
        }

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

        // if (res.data.data.recordList != null && res.data.data.recordList.length < 20) {
        // 	that.setData({
        // 		hasMoreData: false,
        // 	});
        // } else {
        // 	that.setData({
        // 		hasMoreData: true,
        // 	});
        // }
        wx.hideLoading();
      } else {
        app.showTips(that, res.data.msg);
      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/agency/user/list",
    //   data: that.data.searchParam,
    //   header: app.globalData.headers,
    //   success: function (res) {
    //     console.log(res.data);
    //     console.log(res.data.data.recordList);
    //     if (res.data.status == 200) {
    //       that.setData({
    //         isLoading: false,
    //         searchKeyFlag: that.data.searchParam.keys ? true : false,
    //       });
    //       // if (res.data.data.recordList != null && res.data.data.recordList.length > 0) {
    //       //   res.data.data.recordList.forEach(item => {
    //       //     item['updateTimeStr'] = dateUtil.timeShowXXX(item.updateTime);
    //       //     if (app.isEmptyCheck(item.tel)) {
    //       //       item.tel = '';
    //       //     }
    //       //     if (app.isEmptyCheck(item.userName)) {
    //       //       item.userName = '';
    //       //     }
    //       //   });
    //       // }

    //       // res.data.data.recordList.forEach((item,index)=>{
    //       //  if (app.isNotEmptyCheck(item.userServeRecordDespLatest)) {

    //       //     if (item.userServeRecordDespLatest.indexOf('「协助报名」') == 0) {
    //       //       if (app.isNotEmptyCheck(item.agencyUserName)) {
    //       //         item.agencyUserName = '@' + item.agencyUserName;
    //       //       } else {
    //       //         item.agencyUserName = '';
    //       //       }
    //       //     }

    //       //     item.userServeRecordDespLatest = item.userServeRecordDespLatest.replace(/「/g, "<span style='color:#4DB54B;margin-right:4px;'>").replace(/」/g, "</span>" + item.agencyUserName);
    //       //   }
    //       // })
    //       res.data.data.recordList.forEach((item) => {
    //         //  console.log(item.nation.substr(item.nation.length-1,1));
    //         if (item.nation.substr(item.nation.length - 1, 1) != "族" && item.nation.substr(item.nation.length - 1, 1) != "") {
    //           item.nation = item.nation + "族";
    //         }
    //       });

    //       if (res.data.data.recordList != null && res.data.data.recordList.length < 20) {
    //         var recordListTemp = res.data.data.recordList;
    //         that.data.recordList = that.data.recordList.concat(recordListTemp);
    //         that.setData({
    //           hasMoreData: false,
    //         });
    //       } else {
    //         var recordListTemp = res.data.data.recordList;
    //         that.data.recordList = that.data.recordList.concat(recordListTemp);
    //         that.setData({
    //           hasMoreData: true,
    //         });
    //       }

    //       that.setData({
    //         recordList: that.data.recordList,
    //         isLoading: false,
    //         isTrigger: false,
    //       });

    //       // if (res.data.data.recordList != null && res.data.data.recordList.length < 20) {
    //       // 	that.setData({
    //       // 		hasMoreData: false,
    //       // 	});
    //       // } else {
    //       // 	that.setData({
    //       // 		hasMoreData: true,
    //       // 	});
    //       // }
    //       wx.hideLoading();
    //     } else {
    //       app.showTips(that, res.data.msg);
    //     }
    //   },
    //   fail: function (res) {
    //     console.log(res);
    //   },
    // });
  },
  close: function () {
    this.setData({
      phoneDialog: false,
    });
  },
  makePhone: function (e) {
    var that = this;

    // console.log(e);
    // that.setData({
    //   phoneDialog:true,
    //   phone:e.currentTarget.dataset.phone
    // })

    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
    });
  },
  makePhoneCall: function (e) {
    var that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.phone,
    });
  },
  bindCode: function (e) {
    console.log(e);
    wx.navigateToMiniProgram({
      appId: "wxb1f7c694803f6f00", //appid
      path: "/pages/scanQrcode/index?agencyUserId=" + e.currentTarget.dataset.userid, //path
      extraData: {
        //参数
        agencyUserId: e.currentTarget.dataset.userid,
      },
      envVersion: "release", //develop 开发版 trial   体验版 release 正式版
      success (res) {
        console.log("成功");
        // 打开成功
      },
    });
  },

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

  goBack () {
    console.log(123);
    wx.navigateBack({
      delta: 1,
    });
  },
  choosenTop (e) {
    var that = this;
    // that.data.storeJobListSearchForm.pageNum = 1;
    let id = e.currentTarget.dataset.id;
    console.log(id);
    setTimeout(() => {
      that.setData({
        toped: id,
        recordList: [],
        // placeholderText: e.currentTarget.dataset.id == 1 ? "搜索城市/拼音" : "搜索省份/拼音",
        // isScrollTop: false,
      });
      that.getList();
    }, 0);
    // 切换标准 简版 重新查询列表
    // that.data.storeJobListSearchForm.pageNum = 1;
    // that.setData({
    // 	toped: id,
    // 	recordList: [],
    // });
    // that.getJobList();
  },

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return app.sharePageImage()
  },
});
