let app = getApp();
import { timeShowXXX, formatDateYMDHM, getUserApplyOrderStatusById, getUserApplyOrderTypeByType, splitRemark, formatDateYMD } from "../../../utils/dateUtil";
var dateTimePicker = require("../../../utils/dateTimePicker.js");

Page({
  data: {
    testMap: [],
    recordDetail: {},
    iosDialog2: false,
    id: null,
    followrecodelist: [],
    statuschange: 1,
    userinfo: {},
    userinfoList: [],
    currentIndex: 3,
    isShowMore: false,
    drawerShow: false,
    iosDialog1: false,
    interviewTime: "",
    zhedie: false,
    editModal: false,
    serviceInfo: {},
    selectAgencyDrawer: false,
    joinDrawer: false,
    agencyList: [],
    storeInfo: {},
    joinCountList: [{ label: '不参与', value: 0, checked: false }, { label: '参与', value: 1, checked: false }],
    joinVal: 0,
    systemInfo: {},
  },
  showInfo2 (e) {
    console.log(e);
    console.log(JSON.parse(e.currentTarget.dataset.detail));

    this.setData({
      iosDialog2: true,
      recordDetail: JSON.parse(e.currentTarget.dataset.detail),
    });
  },
  copyClose2 () {
    var that = this;

    var text = "姓名：" + that.data.recordDetail.userName + "/" + (that.data.recordDetail.sex == 1 ? "男" : "女") + "/" + that.data.recordDetail.age + "岁" + (that.data.recordDetail.nation == "族" ? "" : "/" + that.data.recordDetail.nation) + "\n电话：" + (that.data.recordDetail.tel == "" || that.data.recordDetail.tel == undefined || that.data.recordDetail.tel == null ? "-" : that.data.recordDetail.tel) + "\n身份证号：" + (that.data.recordDetail.idCard == "" ? "-" : that.data.recordDetail.idCard) + "\n家庭地址：" + (that.data.recordDetail.address == "" || that.data.recordDetail.address == undefined || that.data.recordDetail.address == null ? "-" : that.data.recordDetail.address) + "\n报名岗位：" + that.data.recordDetail.storeJobName + "\n员工薪资：" + (that.data.recordDetail.employeeSalary || '-') + "\n代理政策：" + that.data.recordDetail.policy;

    wx.setClipboardData({
      data: text,
      success (res) {
        wx.getClipboardData({
          success (res) {
            console.log(res.data); // data
            that.close2();
          },
        });
      },
    });
  },
  close2: function () {
    console.log("close");

    this.setData({
      iosDialog2: false,
    });
  },

  changeDateTime (e) {
    var that = this;
    var dateTimeArray = this.data.dateTimeArray,
      dateTime = e.detail.value;
    this.setData({
      // dateTime: e.detail.value,
      currentTime: dateTimeArray[0][dateTime[0]].replace("年", "") + "-" + dateTimeArray[1][dateTime[1]].replace("月", "") + "-" + dateTimeArray[2][dateTime[2]].replace("日", "") + " " + dateTimeArray[3][dateTime[3]],
    });
    console.log(this.data.dateTimeArray);
    console.log(this.data.currentTime);

    var paramData = {};
    paramData["receptionTime"] = this.data.currentTime;
    paramData["orderId"] = that.data.id;
    that.changeStatusTime(paramData);
  },

  changeDateTimeColumn (e) {
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    for (let index = 0; index < dateArr[2].length; index++) {
      dateArr[2][index] = dateArr[2][index] + "日";
    }
    // .replace("年",'').replace("月",'').replace("日",'')

    console.log(dateArr);
    console.log(arr);

    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr,
    });
  },

  changeDateTime2 (e) {
    var that = this;
    var dateTimeArray = this.data.dateTimeArray,
      dateTime = e.detail.value;
    this.setData({
      // dateTime: e.detail.value,
      currentTime2: dateTimeArray[0][dateTime[0]].replace("年", "") + "-" + dateTimeArray[1][dateTime[1]].replace("月", "") + "-" + dateTimeArray[2][dateTime[2]].replace("日", "") + " " + dateTimeArray[3][dateTime[3]],
    });
    console.log(this.data.dateTimeArray);

    var paramData = {};
    paramData["interviewTime"] = this.data.currentTime2;
    paramData["orderId"] = that.data.id;
    that.changeStatusTime(paramData);
  },
  changeStatusTime (data) {
    wx.request({
      url: app.globalData.ip + "/yishoudan/user/apply/order/updateOrder",
      data: data,
      header: app.globalData.headers,
      method: "POST",
      success: function (res) {
        console.log(res);
        if (res.data.status == 200) {
          wx.showToast({
            title: "修改成功",
            icon: "success",
            duration: 1500,
          });
          // that.setData({
          //   storeArray: res.data.data,
          // });
        }
      },
      fail: function (res) { },
    });
  },
  editBill () {
    console.log(this.data.userinfo.status);

    // if (this.data.userinfo.status == 10) {
    wx.navigateTo({
      url: "/pages/billDetail/enroll/index?from=editUser",
    });
    // } else {
    //   this.setData({
    //     editModal: true,
    //   });
    // }
  },
  changeDateTimeColumn2 (e) {
    var arr = this.data.dateTime2,
      dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    for (let index = 0; index < dateArr[2].length; index++) {
      dateArr[2][index] = dateArr[2][index] + "日";
    }
    // .replace("年",'').replace("月",'').replace("日",'')
    this.setData({
      dateTimeArray: dateArr,
      dateTime2: arr,
    });
  },

  ifZhedie () {
    this.setData({
      zhedie: false,
    });
  },
  ifZhankai () {
    this.setData({
      zhedie: true,
    });
  },

  showInfo () {
    this.setData({
      iosDialog1: true,
    });
  },

  copyClose () {
    var that = this;
    var text = "姓名：" + that.data.userinfo.userName + "/" + (that.data.userinfo.sex == 1 ? "男" : "女") + "/" + that.data.userinfo.age + "岁" + (that.data.userinfo.nation == "族" ? "" : "/" + that.data.userinfo.nation) + "\n身份证号：" + (that.data.userinfo.idCard == "" ? "-" : that.data.userinfo.idCard) + "\n企业岗位：" + that.data.userinfo.storeJobName + "\n面试时间：" + that.data.interviewTime + "\n电话：" + (that.data.userinfo.tel == "" ? "-" : that.data.userinfo.tel);

    wx.setClipboardData({
      data: text,
      success (res) {
        wx.getClipboardData({
          success (res) {
            console.log(res.data); // data
            wx.showToast({
              title: "内容已复制",
              icon: "none",
              duration: 1500,
            });
            that.close1();
          },
        });
      },
    });
  },

  showImgs (e) {
    var that = this;
    let curr = [];
    that.data.urls.forEach((item) => {
      curr.push(item.url);
    });
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的 http 链接
      urls: curr, // 需要预览的图片 http 链接列表
    });
  },

  close1: function () {
    console.log("close");

    this.setData({
      iosDialog1: false,
    });
  },

  onLoad: function (options) {
    console.log(options);
    setTimeout(() => {
      console.log(app.globalData.loginUserInfo);
      this.setData({
        loginUserInfo: app.globalData.loginUserInfo,
        serviceInfo: app.globalData.serviceInfo,
      });
      console.log(app.globalData.serviceInfo);
    }, 100);
    this.setData({
      id: options.storeJobId,
    });
  },
  makePhoneCall () {
    var that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.serviceInfo.workPhone || "0371-6611 3723",
    });
  },
  closeEditModal () {
    this.setData({
      editModal: false,
    });
  },
  editUser () {
    wx.navigateTo({
      url: "../newEnroll/enrollEdit/index?from=editUser",
    });
  },
  changeAgency () {
    this.data.agencyList.forEach((item) => {
      item.checked = false
      if (item.aliasName == this.data.userinfo.applyUserName) {
        item.checked = true
      }
    })
    this.setData({
      selectAgencyDrawer: true,
      agencyList: this.data.agencyList
    })
  },
  changeJoin () {
    console.log(this.data.joinCountList);
    this.data.joinCountList.forEach((item) => {
      item.checked = false
      if (item.value == this.data.joinVal) {
        item.checked = true
      }
    })
    this.setData({
      joinDrawer: true,
      joinCountList: this.data.joinCountList
    })
  },
  /**
  * 参与统计变化
  */
  joinCountChange (e) {
    console.log(e);
    this.data.joinVal = this.data.joinCountList[e.detail.value].value
    this.setData({
      joinVal: this.data.joinVal
    })
    this.updateJoinStatus()
    console.log(this.data.joinVal);
  },
  /**
  * 参与统计状态上传
  */
  updateJoinStatus () {
    let that = this

  },
  /**
  * 提交报名人信息
  */
  joinSelect () {
    let that = this
    console.log(this.data.joinCountList);
    this.data.joinCountList.forEach((item) => {
      if (item.checked == true) {
        this.data.joinVal = item.value
      };
    });
    wx.request({
      url: app.globalData.ip + "/yishoudan/user/apply/order/updateStatistic",
      method: "post",
      data: { userApplyOrderId: that.data.userinfo.id, statistic: that.data.joinVal },
      header: app.globalData.headers,
      success: function ({ data }) {
        if (data.status == 200) {
          wx.showToast({
            title: '修改成功',
            icon: 'none'
          })
          that.setData({
            joinDrawer: false
          })
          that.getDetail()
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  joinChange (e) {
    console.log(e);
    this.data.joinCountList.forEach((item) => {
      item.checked = false;
      if (item.value == e.detail.value) {
        item.checked = true;
      }
    });
    this.setData({
      joinCountList: this.data.joinCountList,
    });
  },
  radioChange (e) {
    this.data.agencyList.forEach((item) => {
      item.checked = false;
      if (item.id == e.detail.value) {
        item.checked = true;
      }
    });
    this.setData({
      agencyList: this.data.agencyList,
    });
  },
  getMemberList () {
    let that = this;
    wx.request({
      url: app.globalData.ip + "/yishoudan/user/getAgencyCorpUsers",
      method: "GET",
      header: app.globalData.headers,
      success: function (res) {
        console.log(res);
        if (res.data.status == 200) {
          try {
            res.data.data.recordList.sort((a, b) => {
              return a.agencyRole - b.agencyRole;
            });
            that.setData({
              agencyList: res.data.data.recordList,
            });
          } catch (error) {
            console.log(error);
          }
        }
      },
    });
  },
  /**
  * 报名人抽屉隐藏
  *
  *
  */
  hidedrawershow (e) {
    console.log(e);
    this.setData({
      [e.detail.type]: false
    })
  },
  /**
* 提交报名人信息
*
*/
  subSelect () {
    let that = this
    let id
    console.log(that.data.recordDetail);
    this.data.agencyList.forEach((item) => {
      if (item.checked == true) {
        id = item.id
      };
    });
    wx.request({
      url: app.globalData.ip + `/yishoudan/user/apply/order/updateApplyUser`,
      header: app.globalData.headers,
      method: "post",
      data: {
        userApplyOrderId: that.data.userinfo.id,
        userId: id
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 200) {
          that.setData({
            selectAgencyDrawer: false
          })
          that.getDetail()

        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  getDetail () {
    let that = this;
    console.log(that.data.id);
    wx.request({
      url: app.globalData.ip + `/yishoudan/user/apply/order/details?orderId=${that.data.id}`,
      header: app.globalData.headers,
      method: "get",
      success: function (res) {
        console.log(res);
        if (res.data.status == 200) {
          let followInfo = [];

          let newArr = [];
          res.data.data.serveRecords.forEach((item, index) => {
            // console.log(item);
            if (item.type != 0) {
              item.orderType = getUserApplyOrderTypeByType(item.type);
              item.remark = splitRemark(item.desp);
              newArr.push(item);
            }
          });
          if (res.data.data.serveRecords.legnth > 4) {
            that.data.isShowMore = true;
          }
          res.data.data.serveRecords = newArr;
          res.data.data.serveRecords.forEach((item, index) => {
            item.timeinfo = timeShowXXX(item.createTime);
            if (index <= that.data.currentIndex) {
              followInfo.push(item);
            }
          });
          console.log(res.data.data.serveRecords);
          let userinfo = res.data.data.applyOrder;
          userinfo.agencyName = userinfo.agencyName.replace(userinfo.agencyCode, "");
          console.log(userinfo);
          wx.setStorageSync("storeJobInfoBill", userinfo);
          // loginUserInfo: {
          //   name: "",
          //   address: "",
          //   age: "",
          //   nationality: "",
          //   sex: "",
          //   num: "",
          //   tel: "",
          //   idCardImageUrl: "",
          // },
          let userinfo2 = {};
          userinfo2["name"] = userinfo.userName
          userinfo2["nationality"] = userinfo.nation
          userinfo2["num"] = userinfo.idCard
          userinfo2["currentImg"] = userinfo.idCardImageUrl
          userinfo2["idCardImageUrl"] = userinfo.idCardImageUrl
          userinfo2["sex"] = userinfo.sex
          userinfo2["age"] = userinfo.age
          userinfo2["idCard"] = userinfo.idCard
          userinfo2["userId"] = userinfo.userId
          userinfo2["tel"] = userinfo.tel
          userinfo2["address"] = userinfo.address
          wx.removeStorage({
            key: "townsManInfo",
          });
          wx.removeStorage({
            key: "townsManInfoJob",
          });
          wx.setStorageSync("townsManInfo", { ...userinfo2 });
          // let data = { ...that.data.loginUserInfo, currentImg: that.data.currentImg };
          // console.log(data);
          // wx.setStorage({
          //   key: "townsManInfo",
          //   data,
          // });
          that.getImgs(userinfo.userId);
          if (userinfo.entryTime) {
            userinfo.entryTime = formatDateYMDHM(userinfo.entryTime);
          }
          if (userinfo.leaveTime) {
            userinfo.leaveTime = formatDateYMDHM(userinfo.leaveTime);
          }
          if (userinfo.updateTime) {
            userinfo.updateTime = formatDateYMDHM(userinfo.updateTime);
          }
          if (userinfo.interviewTime) {
            userinfo.interviewTime = formatDateYMDHM(userinfo.interviewTime);
          }
          if (userinfo.createTime) {
            userinfo.createTime = formatDateYMDHM(userinfo.createTime);
          }
          if (userinfo.interviewOperateTime) {
            userinfo.interviewOperateTime = formatDateYMDHM(userinfo.interviewOperateTime);
          }
          if (userinfo.passedOperateTime) {
            userinfo.passedOperateTime = formatDateYMDHM(userinfo.passedOperateTime);
          }
          if (userinfo.receptionTime) {
            userinfo.receptionTime = formatDateYMDHM(userinfo.receptionTime);
          }
          if (userinfo.willEntryTime) {
            userinfo.willEntryTime = formatDateYMDHM(userinfo.willEntryTime);
          }
          if (userinfo.willLeaveTime) {
            userinfo.willLeaveTime = formatDateYMDHM(userinfo.willLeaveTime);
          }

          userinfo.statusName = getUserApplyOrderStatusById(userinfo.status);

          if (userinfo.nation.substr(userinfo.nation.length - 1, 1) != "族" && userinfo.nation.substr(userinfo.nation.length - 1, 1) != "") {
            userinfo.nation = userinfo.nation + "族";
          }
          for (var key in res.data.data.records) {
            // console.log(key, res.data.data.records[key]);
            res.data.data.records[key].forEach((item, index) => {
              item.desp = item.desp.replaceAll("预约接待时间", "预计到达时间");
              if (item.desp.substr(item.desp.length - 3, 3) == "备注：") {
                item.desp = item.desp.replace(/备注：/g, "");
              }

              if (item.type == 1) {
                item["statusText"] = "报名审核中";
              } else if (item.type == 2) {
                item["statusText"] = "待接待";
              } else if (item.type == 3) {
                item["statusText"] = "待入职";
              } else if (item.type == 4) {
                item["statusText"] = "在职中";
              } else if (item.type == 5) {
                item["statusText"] = "已离职";
              } else if (item.type == 9) {
                item["statusText"] = "约离职";
              } else if (item.type == 6) {
                item["statusText"] = "已完成";
              } else if (item.type == 11) {
                item["statusText"] = "审核未通过";
              } else if (item.type == 12) {
                item["statusText"] = "已接到";
              } else if (item.type == 13) {
                item["statusText"] = "未接到";
              } else if (item.type == 14) {
                item["statusText"] = "面试未通过";
              } else if (item.type == 15) {
                item["statusText"] = "未入职";
              }
            });
          }
          that.setData({
            testMap: res.data.data.records,
          });

          that.setData({
            currentTime: userinfo.receptionTime,
            currentTime2: userinfo.interviewTime,
            interviewTime: formatDateYMD(userinfo.interviewTime),
            userinfo: userinfo,
            followrecodelist: res.data.data.serveRecords,
            currentList: followInfo,
            isShowMore: that.data.isShowMore,
            joinVal: userinfo.inStatistic
          });

          // console.log(that.data.userinfo);
          that.getStoreInfo()
        }
      },
    });
  },
  getStoreInfo () {
    let that = this
    wx.request({
      url: app.globalData.ip + `/overall/store/job/getStoreJobDetailById?storeJobId=${that.data.userinfo.storeJobId}`,
      header: app.globalData.headers,
      method: "get",
      success: function (res) {
        console.log(res);
        let data = res.data.data
        if (res.data.status == 200) {
          var telN = data.storeJob.onSiteInfo.split("\n");
          that.data.telStr = [];
          telN.forEach((item, index) => {
            item = item.replace(/\d\./, '')
            that.data.telStr.push(item)
          })
          console.log(that.data.telStr);

          that.data.zhuchangInfo = '驻场:' + that.data.telStr;
          console.log(data.storeJob.onSiteRemark);
          // console.log(data.storeJob.onSiteRemark.split('驻场：'));
          let markList = data.storeJob.onSiteRemark.split('⚠')
          console.log(markList);
          let newMark = markList[0] + `面试时间：${that.data.userinfo.interviewTime}\n\n` + '⚠' + markList[1]
          console.log(newMark);
          that.setData({
            storeInfo: { ...data.storeJob, ...data.jobPoses },
            zhuchangInfo: that.data.zhuchangInfo,
            telStr: that.data.telStr,
            onSiteRemark: newMark,
          })

        }
      },
    })
  },
  setCopy () {
    var that = this;
    wx.setClipboardData({
      data: that.data.onSiteRemark,
      success (res) {
        wx.getClipboardData({
          success (res) {
            console.log(res.data) // data
            wx.showToast({
              title: '内容已复制',
              icon: 'none',
              duration: 1500
            })

          }
        })
      }
    })
  },
  chooseMap2 (e) {
    var that = this;
    wx.setClipboardData({
      data: that.data.onSiteRemark,
      success (res) {
        wx.getClipboardData({
          success (res) {
            wx.showToast({
              title: '内容已复制',
              icon: 'none',
              duration: 1500
            })
            setTimeout(() => {
              console.log(e.currentTarget.dataset.lat);
              if (e.currentTarget.dataset.lat == "") {
                return
              }
              let name = e.currentTarget.dataset.postitle;
              let content = e.currentTarget.dataset.poscontent;
              let lat = e.currentTarget.dataset.lat - 0;
              let lng = e.currentTarget.dataset.lng - 0;
              wx.openLocation({
                latitude: lat,
                longitude: lng,
                name: name,
                address: content,
                scale: 15,
              });
            }, 200)
          }
        })
      }
    })



  },
  changeStatus (e) {
    console.log(e.mark.statuscode);
    this.setData({
      statuschange: e.mark.statuscode,
    });
  },
  getImgs (userId) {
    var that = this;
    wx.request({
      url: app.globalData.ip + "/imgs/list/" + userId + "?type=20",
      header: app.globalData.headers,
      method: "GET",
      success: function (res) {
        console.log(res);
        let currFils = [];
        let regs = /\.(jpg|jpeg|png)(\?.*)?$/;
        if (app.isNotEmptyCheck(res.data.data.userImgs)) {
          res.data.data.userImgs.forEach((item) => {
            if (regs.test(item.url.toLowerCase())) {
              currFils.push({ url: item.url, id: item.id });
            }
          });
        }

        that.setData({
          files: currFils.slice(0, 4),
          urls: currFils,
        });
        // }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  showMore () {
    let that = this;
    console.log(that.data.currentList);
    that.data.currentList = [];
    that.data.currentIndex += 4;
    that.data.followrecodelist.forEach((item, index) => {
      if (index < that.data.currentIndex) {
        that.data.currentList.push(item);
      }
    });
    if (that.data.followrecodelist.length > that.data.currentList.length) {
      that.data.isShowMore = true;
    } else {
      that.data.isShowMore = false;
    }
    that.setData({
      currentList: that.data.currentList,
      currentIndex: that.data.currentIndex,
      isShowMore: that.data.isShowMore,
    });
  },
  showImg () {
    wx.previewImage({
      current: this.data.userinfo.idCardImageUrl, // 当前显示图片的http链接
      urls: [this.data.userinfo.idCardImageUrl], // 需要预览的图片http链接列表
    });
  },
  showDrawer () {
    this.setData({
      drawerShow: true,
    });
  },
  hideDrawer () {
    this.setData({
      drawerShow: false,
    });
  },
  preventTouchMove (e) {
    // e.preventDefault;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onShow: function () {
    this.getDetail();

    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear, this.data.currentTime);
    console.log(obj.dateTimeArray);
    console.log(obj.dateTime);
    for (let index = 0; index < obj.dateTimeArray[0].length; index++) {
      obj.dateTimeArray[0][index] = obj.dateTimeArray[0][index] + "年";
    }
    for (let index = 0; index < obj.dateTimeArray[1].length; index++) {
      obj.dateTimeArray[1][index] = obj.dateTimeArray[1][index] + "月";
    }
    for (let index = 0; index < obj.dateTimeArray[2].length; index++) {
      obj.dateTimeArray[2][index] = obj.dateTimeArray[2][index] + "日";
    }
    let systemInfo = wx.getSystemInfoSync();
    this.getMemberList()
    this.setData({
      systemInfo,
      dateTimeArray: obj.dateTimeArray,
      dateTime: obj.dateTime,
      dateTimeArray2: obj.dateTimeArray,
      dateTime2: obj.dateTime,
    });
  },
  /**
   * 阻止滑动穿透
   *
   *
   */
  modalMove () {
    return false;
  },
  onUnload () {
    wx.removeStorageSync("storeJobInfoBill")
    wx.removeStorageSync("townsManInfo");
  },
  kefu (e) {
    console.log(e);
    let url = e.currentTarget.dataset.customserviceurl
    wx.openCustomerServiceChat({
      extInfo: { url: url || 'https://work.weixin.qq.com/kfid/kfc84d8465f4c633511' },
      showMessageCard: true,
      corpId: 'wwc227639d3a136c8d',
      success (res) {
        console.log('res', res);
      },
      fail (err) {
        console.log('err', err);
      }
    })
  },
});
