// pages/newEnroll/index.js
const app = getApp();
var dateTimePicker = require("../../utils/dateTimePicker.js");
var dateUtil = require("../../utils/dateUtil.js");
import { nationArray } from "../../utils/commonUtil";
import { customRequest } from '../../utils/request.js';
import { baseUrl } from '../../utils/request.js';
const mydate = new Date();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    storeJobInfo: {},
    userInfo: {
      name: "姓名",
      address: "报名老乡地址",
      age: "年龄",
      nationality: "民族",
      sex: "性别",
      num: "-",
      tel: "-",
      idCardImageUrl: "",
    },
    user: app.globalData.user,
    showUpload: true,
    name: "",
    sex: [
      {
        id: 1,
        value: "男",
      },
      {
        id: 2,
        value: "女",
      },
    ],
    imgSrc: "",
    loading: false,
    idInfo: {},
    index: -1,
    agentArray: [],
    // jobIndex: -1,
    jobArray: [
      // {
      // 	id: 1,
      // 	name: "GG",
      // },
    ],
    storeIndex: -1,
    storeArray: [
      // {
      // 	id: 1,
      // 	name: "GG",
      // },
    ],
    dateTimeArray1: null,
    dateTime1: null,
    startYear: 2022,
    endYear: new Date().getFullYear(),
    currentTime: '-',
    currentTime2: '-',
    searchListShow: false,
    searchKeys: "",
    searchKeysA: "",
    inputShowed: false,
    inputVal: "",
    inputShowedA: false,
    inputValA: "",
    storeId: "",
    agentId: "",
    agentName: "",
    storeJobId: "",
    policy: "-",
    currentImg: "",
    nationIndex: -1, // 民族的索引
    managerRoleClassify: app.globalData.loginUserInfo.managerRoleClassify, // 管理员权限
    nationArray,
    currentUser: {},
    jobName: "-",
    switch1Checked: true,
  },
  shrink: function () {
    wx.navigateBack({
      delta: -1,
    })
  },
  radioChange: function (e) {
    const sex = this.data.sex;
    let currentSex = "";
    for (let i = 0, len = sex.length; i < len; ++i) {
      sex[i].checked = sex[i].id == e.detail.value;
      if (sex[i].checked) {
        currentSex = sex[i].value;
      }
    }
    this.setData({
      ["userInfo.sex"]: currentSex,
      sex,
    });
    console.log(e.detail.value);
  },
  chooseIdCard () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success (res) {
        console.log(res);

        that.uploadIdcardImg(res);
      },
    });
  },
  uploadIdcardImg (imgPath) {
    let that = this;
    // tempFilePath可以作为img标签的src属性显示图片
    console.log(imgPath.tempFilePaths[0]);
    const tempFilePaths = imgPath.tempFilePaths;
    wx.showLoading({
      title: "识别中...",
    });
    wx.uploadFile({
      // url: app.globalData.ip + '/commons/idCardOcrRecognize',
      url: baseUrl + "/commons/idCardOcrRecognizeAndUploadToAliyunOss",
      filePath: imgPath.tempFilePaths[0],
      name: "uploadFile",
      header: app.globalData.headers,
      success: function (res) {
        console.log(JSON.parse(res.data));
        var idcard = JSON.parse(res.data);
        idcard.data.tel = ""
        idcard.data.nationality = idcard.data.nationality
        if (idcard.status == 200) {
          that.setData({
            userInfo: idcard.data,
            showUpload: false,
            currentImg: imgPath.tempFilePaths[0],
          });
          that.setStorage();
          console.log(that.data.userInfo);
          that.data.nationArray.forEach((item, index) => {
            if (item.name.includes(that.data.userInfo.nationality)) {
              that.setData({
                nationIndex: index,
              });
            }
          });
          if (that.data.userInfo.nationality.substr(that.data.userInfo.nationality.length - 1, 1) != '族' && that.data.userInfo.nationality.substr(that.data.userInfo.nationality.length - 1, 1) != '') {
            that.data.userInfo.nationality = that.data.userInfo.nationality + '族'
          }
          if (that.data.userInfo.sex == "男") {
            that.data.sex[0].checked = true;
          } else {
            that.data.sex[1].checked = true;
          }
          that.setData({
            userInfo: that.data.userInfo,
            sex: that.data.sex,
            imgSrc: tempFilePaths[0],
          });


        } else {
          wx.showToast({
            duration: 2000,
            title: "身份证未识别",
            icon: "none",
            mask: true,
          });
          // console.log(1);
          //app.showTips(that, res.data.msg);
        }
        wx.hideLoading();
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    console.log(app.globalData.user);
    console.log(options);

    // 先统一给代理名字赋予登陆者的名称
    that.setData({
      agentName: app.globalData.user.userName,
      agentId: app.globalData.user.agencyId
    });
    if (app.isNotEmptyCheck(options.info)) {
      // 如果随路由传过来的信息有更新,赋值新的数据
      console.log(JSON.parse(options.info));

      this.setData({
        storeJobInfo: JSON.parse(options.info),
        storeJobId: JSON.parse(options.info).id,
        jobName: JSON.parse(options.info).jobName,
        inputVal: JSON.parse(options.info).storeName || JSON.parse(options.info).aliasName,
        storeId: JSON.parse(options.info).storeId,
      });
      this.getPolicyByStoreJobId(this.data.storeJobId);
      wx.setStorageSync('storeJobInfo', that.data.storeJobInfo)
    }
    if (app.isNotEmptyCheck(options.agencyInfo)) {
      that.setData({
        agentName: JSON.parse(options.agencyInfo).agencyName,
        agentId: JSON.parse(options.agencyInfo).id,
      });
    }
    if (app.isNotEmptyCheck(options.imgUrl)) {
      let imgUrl = JSON.parse(options.imgUrl);
      that.uploadIdcardImg(imgUrl);
    }
  },
  toJobAndAgencySelect (e) {
    console.log(e);
    console.log(this.data.userInfo);
    this.setStorage().then(() => {
      console.log('--------', 'isIntonavigation');
      wx.navigateTo({
        url: `../recordChoice/index?type=${e.currentTarget.dataset.type}`,
      });
    });
  },
  showImg () {
    wx.previewImage({
      current: this.data.currentImg, // 当前显示图片的 http 链接
      urls: [this.data.currentImg], // 需要预览的图片 http 链接列表
    });
  },
  deleteImg () {
    var that = this;
    wx.showModal({
      title: "提示",
      content: "确定要删除图片吗？",
      confirmColor: "#1890ff",
      success (res) {
        if (res.confirm) {
          that.setData({
            imgSrc: "",
            showUpload: true,
          });
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // let src = wx.getStorageSync("src");
    // console.log(src);
  },
  bothwayBind (e) {
    console.log(e);
    let type = `userInfo.${e.currentTarget.dataset.type}`;
    this.setData({
      [type]: e.detail.value,
    });
  },
  beforeFormSubmit: function (e) {
    var that = this;
    console.log(e);
    that.setData({
      loading: true,
    });

    if (!that.data.switch1Checked) {
      wx.showToast({
        title: "请先阅读并同意《服务协议》及《隐私政策》",
        icon: "none",
        duration: 2000,
      });
    } else if (app.isEmptyCheck(wx.getStorageSync("townsManInfo"))) {
      wx.showToast({
        duration: 2000,
        title: "请补全个人信息",
        icon: "none",
        mask: true,
      });
      that.setData({
        loading: false,
      });
    }
    else if (app.isEmptyCheck(wx.getStorageSync("townsManInfoJob"))) {
      wx.showToast({
        duration: 2000,
        title: "请补全岗位信息",
        icon: "none",
        mask: true,
      });
      that.setData({
        loading: false,
      });
    }
    else {
      setTimeout(() => {
        that.formSubmit(e);
      }, 1);
      e.detail.value["idCardImageUrl"] = that.data.userInfo.idCardImageUrl;
    }
  },
  clear () {
    wx.removeStorageSync('townsManInfo')
  },
  setStorage () {
    let that = this;
    wx.removeStorageSync('townsManInfo')
    return new Promise((resolve, reject) => {
      console.log(that.data.storeJobId);
      let data = { ...that.data.userInfo, currentImg: that.data.currentImg };
      console.log(data);
      wx.setStorage({
        key: "townsManInfo",
        data,
      });
      console.log(wx.getStorageSync("townsManInfo"));
      resolve();
    });
  },
  formSubmit: function (e) {
    var that = this;
    console.log(e);
    console.log(wx.getStorageSync("townsManInfo"))
    console.log(wx.getStorageSync("townsManInfoJob"))
    console.log(that.data.agentName + "+===+" + that.data.agentId)
    that.setData({
      loading: true,
    });
    // return
    wx.showLoading({
      title: "提交中...",
      mask: true,
    });
    let userInfo = wx.getStorageSync("townsManInfo");
    let jobInfo = wx.getStorageSync("townsManInfoJob");

    console.log(that.data.idInfo);
    new Promise(function (resolve, reject) {
      var paramData = {};
      paramData["userName"] = userInfo.name;

      if (userInfo.sex == '1' || userInfo.sex == '男') {
        paramData["sex"] = 1;
      } else {
        paramData["sex"] = 2;
      }

      paramData["age"] = userInfo.age;
      paramData["nation"] = userInfo.nationality;
      paramData["idCard"] = userInfo.num;
      if (app.isNotEmptyCheck(userInfo.imgs)) {
        paramData["imgs"] = userInfo.imgs.toString();
      }

      paramData["tel"] = userInfo.tel;
      paramData["idCardImageUrl"] = userInfo.idCardImageUrl;
      paramData["address"] = userInfo.address;

      paramData["agencyId"] = that.data.agentId;
      paramData["storeJobId"] = jobInfo.storeJobId;
      paramData["policy"] = jobInfo.policy;
      paramData["interviewTime"] = jobInfo.currentTime;
      paramData["receptionTime"] = jobInfo.currentTime2;
      resolve(paramData);
    }).then(function (paramData) {
      console.log(paramData);
      customRequest("/user/apply/order/addByAgency", { header: 'headers', method: 'POST', data: paramData }).then((res) => {

        wx.removeStorageSync('townsManInfo')
        wx.removeStorageSync('townsManInfoJob')

        console.log(res);
        if (res.data.status == 200) {
          wx.hideLoading();
          wx.switchTab({
            url: "/pages/firstBill/index",
          });
          wx.showToast({
            duration: 2000,
            title: "报名成功",
            icon: "success",
            mask: true,
          });
        }
      })
      // wx.request({
      //   url: app.globalData.ip + "/user/apply/order/addByAgency",
      //   header: app.globalData.headers,
      //   data: paramData,
      //   method: "POST",
      //   success: function (res) {

      //     wx.removeStorageSync('townsManInfo')
      //     wx.removeStorageSync('townsManInfoJob')

      //     console.log(res);
      //     if (res.data.status == 200) {
      //       wx.hideLoading();
      //       wx.switchTab({
      //         url: "/pages/workBench/index",
      //       });
      //       wx.showToast({
      //         duration: 2000,
      //         title: "报名成功",
      //         icon: "success",
      //         mask: true,
      //       });
      //     }
      //   },
      // });
    });
    // }
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value,
    });
    if (e.detail.value.length > 0) {
      this.setData({
        searchListShow: true,
      });
      this.getStoreList(e.detail.value);
    } else {
      this.setData({
        searchListShow: false,
      });
    }
  },





  getPolicyByStoreJobId: function (storeJobId) {
    var that = this;
    // 60秒后重新获取验证码
    customRequest("/store/job/getPolicyByStoreJobId",{header:'headers', method: 'GET', data: { storeJobId: storeJobId,}}).then((res)=>{
      if (res.data.status == 200) {
        that.setData({
          policy: res.data.data,
        });
      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/store/job/getPolicyByStoreJobId",
    //   data: {
    //     storeJobId: storeJobId,
    //   },
    //   header: app.globalData.headers,
    //   method: "GET",
    //   success: function (res) {
    //     console.log(res);
    //     if (res.data.status == 200) {
    //       that.setData({
    //         policy: res.data.data,
    //       });
    //     }
    //   },
    //   fail: function (res) {
    //     console.log(res);
    //   },
    // });
  },



  // getAgencyList: function (searchKeys) {
  // 	var that = this;
  // 	that.data.searchKeysA = searchKeys;
  // 	// 60秒后重新获取验证码
  // 	wx.request({x
  // 		url: app.globalData.ip + "/agency/getByPmdUserId",
  // 		data: {
  // 			agencyName: searchKeys,
  // 			// pmdUserId: 101125
  // 		},
  // 		header: app.globalData.headers,
  // 		method: "GET",
  // 		success: function (res) {
  // 			console.log(res);
  // 			if (res.data.status == 200) {
  // 				that.setData({
  // 					agentArray: res.data.data,
  // 				});
  // 			}
  // 		},
  // 		fail: function (res) {},
  // 	});
  // },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    console.log(that.data.managerRoleClassify);
    console.log(app.globalData.loginUserInfo);
    // 获取缓存的报名人信息
    let info = wx.getStorageSync("townsManInfo");
    console.log(info);
    if (app.isNotEmptyCheck(info)) {
      // 统一给代理岗位相关的字段赋值
      that.setData({
        userInfo: info,

      });
      // this.setData({
      // 	userInfo: info,
      // 	currentImg: info.currentImg,
      // 	currentTime: info.currentTime,
      // });
      console.log(info);
      if (info.sex == "1") {
        info.sex = '男'
      } else if (info.sex == "2") {
        info.sex = '女'
      }

      // info.sex = info.sex == '1' ? '男' : '女';
      if (info.nationality.substr(info.nationality.length - 1, 1) != '族' && info.nationality.substr(info.nationality.length - 1, 1) != '') {
        info.nationality = info.nationality + '族'
      }
      that.data.nationArray.forEach((item, index) => {
        if (item.name.indexOf(info.nationality) > -1 && info.nationality != "") {
          console.log("isin");
          that.setData({
            nationIndex: index,
          });
        }
      });
      console.log(that.data.nationIndex);
      this.setData({
        userInfo: info,
        sex: this.data.sex,
      });
    }


    let infoJob = wx.getStorageSync("townsManInfoJob");
    console.log(infoJob);
    if (app.isNotEmptyCheck(infoJob)) {
      // 统一给代理岗位相关的字段赋值
      that.setData({
        storeJobId: infoJob.storeJobId,
        jobName: infoJob.jobName,
        currentImg: infoJob.currentImg,
        currentTime: infoJob.currentTime,
        currentTime2: infoJob.currentTime2,
      });
      this.getPolicyByStoreJobId(that.data.storeJobId);

    }

    // 
    // let info = wx.getStorageSync("townsManInfo");
    // if (app.isNotEmptyCheck(info)) {
    // 	this.setData({
    // 		userInfo: info,
    // 		currentImg: info.currentImg,
    // 		currentTime: info.currentTime,
    // 	});
    // 	console.log(info);
    // 	if (info.sex == "男") {
    // 		this.data.sex[0].checked = true;
    // 	} else if (info.sex == "女") {
    // 		this.data.sex[1].checked = true;
    // 	}
    // 	that.data.nationArray.forEach((item, index) => {
    // 		if (item.name.indexOf(info.nationality) > -1 && info.nationality != "") {
    // 			console.log("isin");
    // 			that.setData({
    // 				nationIndex: index,
    // 			});
    // 		}
    // 	});
    // 	console.log(that.data.nationIndex);
    // 	this.setData({
    // 		sex: this.data.sex,
    // 	});
    // }
    // this.pickerTap();


  },
  switch1Change: function (e) {
    console.log("radio发生change事件，携带value值为：", e.detail.value);
    console.log(e.detail.value);

    var check = this.data.switch1Checked;
    if (check) {
      this.data.switch1Checked = false;
      console.log("已取消选中");
      wx.showToast({
        title: "请先阅读并同意《服务协议》及《隐私政策》",
        icon: "none",
        duration: 2000,
      });
    } else {
      this.data.switch1Checked = true;
      console.log("已选中");
    }
    this.setData({
      switch1Checked: this.data.switch1Checked,
    });

    // if(!e.detail.value){

    // }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function (e) {
    console.log("isHide");
    console.log(e);
    // this.setData({
    // 	userInfo: {
    // 		name: "",
    // 		address: "",
    // 		age: "",
    // 		nationality: "",
    // 		sex: "",
    // 		num: "",
    // 		idCardImageUrl: "",
    // 	},
    // });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // wx.removeStorageSync("townsManInfo");
    // wx.switchTab({
    // 	url: "../firstBill/index",
    // });
    // console.log(wx.getStorageSync("townsManInfo"));
  },

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

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

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