const _my = require("../../__antmove/api/index.js")(my);
const wx = _my;
// pages/visitor_make/visitor_make.js
import { getBuildingList, getUserWhiteByphoneAndAdminId, visitorySubmit, getVisitoryByUserVisitorListDetailId } from "../../utils/api/api";
import { getContextByAdminId } from "../../utils/api/customField";
import { getThreeCodeByAdminId } from "../../utils/api/three_yards";
const {
  showToast
} = require("../../utils/func/request");
import international from "../../international/appointment_scence/index";
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data() {
    return {
      international: international,
      //国际化语言包
      language: app.data.language,
      isDisabled: false,
      chooseOne: true,
      //展示访客确认页面
      // swiper的index
      currentIndex: 0,
      // swiper滚动长度
      swiperDx: 0,
      // 步骤列表
      stepsList: [{
        name: "访客确认",
        name1: "Visitors confirm",
        complete: false
      }, {
        name: "拜访信息填写",
        name1: "Visit information",
        complete: false
      }],
      // 受访单位列表
      companyList: [],
      companyIndex: 0,
      // 拜访事由列表
      reasonList: [{
        name: "业务洽谈"
      }, {
        name: "会议邀请"
      }, {
        name: "施工安装"
      }, {
        name: "探亲访友"
      }, {
        name: "工作检查"
      }, {
        name: "面试邀请"
      }, {
        name: "快递外卖"
      }, {
        name: "家政保洁"
      }],
      reasonIndex: null,
      // 人员类型列表
      personTypeList: [{
        id: 0,
        name_ch: "访客",
        name_en: "visitors"
      }, {
        id: 1,
        name_ch: "同事",
        name_en: "colleagues"
      }, {
        id: 2,
        name_ch: "亲属",
        name_en: "relatives"
      }],
      personTypIndex: 0,
      // 提交表单
      form: {},
      userInfo: null,
      building_list: [],
      buildingIndex: 0,
      isAudit: false,
      //受邀禁用信息
      auditList: null,
      type: 1,
      //1->访客自主提交 2->访客受邀
      disableComplete: false,
      isShowApplet: false,
      //是否开启自定义字段
      threeCodeList: [],
      //是否开启三码
      startTime: null,
      endTime: null,
      //传入组件的预约开始时间
      hsHour: null, //核酸时长（单位小时）
      carNumberShow: false
    }
  },

  // 获取认证状态
  getCertificationState(e) {
    if (e.detail) {
      showToast("认证成功~");
      wx.setStorageSync("language", app.data.language);
      this.setData({
        isDisabled: true
      });
      this.updateSetting();
    } else {
      showToast("认证失败了，再试一次吧~");
    }
  },
  // 更新个人信息
  updateSetting() {
    let {
      form
    } = this.data;
    if (app.data.language == wx.getStorageSync("language")) {
      if (app.data.language == "en") {
        this.setData({
          userInfo: app.data.userInfo || app.data.temporary_userInfo,
          isDisabled: app.data.userInfo ? true : false
        });
      } else if (app.data.language === "ch") {
        this.setData({
          userInfo: app.data.userInfo,
          isDisabled: app.data.userInfo ? true : false
        });
      }
      if (app.data.userInfo) {
        form.userId = app.data.userInfo.userId;
        form.name = app.data.userInfo.username;
        form.phone = app.data.userInfo.phone;
        form.idNumber = app.data.userInfo.idNumber;
        this.matchCorrectPhone();
        this.matchStepComplete();
      }
    }
    if (app.data.extraMessage) {
      let extraMessage = app.data.extraMessage;
      this.setData({
        "form.company": extraMessage.company,
        "form.carno": extraMessage.carno
      });
      this.matchStepComplete();
    }
  },
  // 判断受邀人的手机号是否和当前用户手机号一致
  matchCorrectPhone() {
    if (app.data.userInfo && this.data.form.correctPhone && this.data.type === 2) {
      if (app.data.userInfo.phone != this.data.form.correctPhone) {
        this.setData({
          disableComplete: true
        });
        wx.showModal({
          title: "提示",
          content: "你暂无权限接受此邀请哦",
          showCancel: false
        });
      }
    }
  },
  // 获取是否可以展示信息
  getUpdateState(e) {
    if (e.detail) {
      this.updateSetting();
    }
  },
  // 获得swiper-item位置
  getSwiperPercent(e) {
    this.setData({
      swiperDx: e.detail.dx
    });
  },
  // 改变swiper
  changeSwiper(e) {
    if (e.detail.current < this.data.currentIndex || this.data.stepsList[e.detail.current].complete) {
      this.setData({
        currentIndex: e.detail.current
      });
    } else {
      this.setData({
        currentIndex: this.data.currentIndex
      });
    }
  },
  // 下一步
  next_step(e) {
    this.setData({
      currentIndex: 1
    });
  },
  // 上一步
  previous_step(e) {
    this.setData({
      currentIndex: 0
    });
  },
  carNumberShowChange(e) {
    this.setData({
      carNumberShow: e.detail
    })
  },
  //获取输入or选择的内容
  getValue(e) {
    var {
      form
    } = this.data;
    switch (e.currentTarget.dataset.type) {
      case "reason":
        this.setData({
          "form.reason": e.detail.name
        });
        // form.reason = e.detail.name
        break;
      case "company":
        this.setData({
          "form.company": e.detail
        });
        break;
      case "visiteeBuilding":
        var index = this.data.building_list.findIndex(item => {
          return item.adminId == e.detail.adminId;
        });
        this.setData({
          "form.visiteeBuilding": e.detail.username,
          "form.visiteeBuildingId": e.detail.adminId,
          companyList: this.data.building_list[index].userWhiteIntervieweeVOList,
          "form.visiteeCompany": this.data.building_list[index].userWhiteIntervieweeVOList[0].companyName,
          "form.userWhitelistId": this.data.building_list[index].userWhiteIntervieweeVOList[0].userWhitelistId,
          "form.visiteeXm": this.data.building_list[index].userWhiteIntervieweeVOList[0].name
        });
        this.getContextByAdminId(e.detail.adminId);
        this.getThreeCodeByAdminId(e.detail.adminId);
        break;
      case "visiteeCompany":
        this.setData({
          "form.visiteeXm": e.detail.name,
          "form.userWhitelistId": e.detail.userWhitelistId
        });
        break;
      case "visiteePhone":
        this.setData({
          "form.phone": e.detail
        });
        this.getUserWhiteByphoneAndAdminId();
        break;
      case "startTime":
        this.setData({
          startTime: e.detail
        });
      default:
        form[e.currentTarget.dataset.type] = e.detail;
        break;
    }
    this.matchStepComplete();
  },
  visiteePhoneFun(e) {
    if(!e.detail.value) {
      return
    }
    this.setData({
      "form.phone": e.detail.value
    });
    this.getUserWhiteByphoneAndAdminId();
  },
  //步骤条判断是否完成
  matchStepComplete() {
    let {
      stepsList,
      disableComplete,
      form,
      isFillFields,
      isthreeYards
    } = this.data;
    stepsList[0].complete = !disableComplete && form.userId && form.name && form.idNumber && form.phone && form.company ? true : false;
    stepsList[1].complete = !disableComplete && form.visiteePhone && form.reason && form.visiteeBuilding && isFillFields && isthreeYards ? true : false;
    this.setData({
      stepsList
    });
  },
  getUserWhiteByphoneAndAdminId(type) {
    wx.showLoading({
      title: "获取中..."
    });
    var {
      form
    } = this.data;
    let data = {
      // adminId: form.visiteeBuildingId, //楼宇id
      phone: form.phone
    };
    getUserWhiteByphoneAndAdminId(data).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        form.visiteePhone = form.phone;
        form.visiteeBuilding = res.data[this.data.buildingIndex].username;
        form.visiteeBuildingId = res.data[this.data.buildingIndex].adminId;
        form.visiteeCompany = res.data[this.data.buildingIndex].userWhiteIntervieweeVOList[this.data.companyIndex].companyName;
        form.userWhitelistId = res.data[this.data.buildingIndex].userWhiteIntervieweeVOList[this.data.companyIndex].userWhitelistId;
        form.visiteeXm = res.data[this.data.buildingIndex].userWhiteIntervieweeVOList[this.data.companyIndex].name;
        this.setData({
          form: form,
          companyList: res.data[this.data.buildingIndex].userWhiteIntervieweeVOList,
          companyIndex: 0,
          building_list: res.data,
          buildingIndex: 0
        });
        this.getContextByAdminId(res.data[this.data.buildingIndex].adminId);
        this.getThreeCodeByAdminId(res.data[this.data.buildingIndex].adminId);
      } else {
        showToast(res.msg);
        this.setData({
          companyList: null,
          companyIndex: 0,
          building_list: null,
          buildingIndex: 0,
          threeCodeList: [],
          hsHour: null,
          isShowApplet: false
        });
      }
    });
  },
  //提交申请
  submit() {
    const that = this;
    let {
      form,
      isthreeYards,
      isFillFields
    } = this.data;
    wx.requestSubscribeMessage({
      entityIds: ["95a6bdda7c7d49bfa4c0014f5e035601", "63ecddec46ef4424a13fcb966ecd1bc4"],
      success(res) {
        if(res.behavior === 'cancel') {
          return
        }
        form.addCustomList = isFillFields == true ? null : isFillFields;
        form.hs = isthreeYards.hs || null;
        form.hsPhoto = isthreeYards.hsPhoto || null;
        form.jkm = isthreeYards.jkm || null;
        form.jkmPhoto = isthreeYards.jkmPhoto || null;
        form.xc = isthreeYards.xc || null;
        form.xcPhoto = isthreeYards.xcPhoto || null;
        form.xcPhone = isthreeYards.xcPhone || null;
        visitorySubmit(that.data.form).then(res => {
          if (res.code === 200) {
            let extraMessage = {
              company: that.data.form.company,
              carno: that.data.form.carno,
              type: 2
            };
            app.data.extraMessage = extraMessage;
            wx.setStorageSync("extraMessage", extraMessage);
            my.alert({
              title: "提示",
              content: that.data.type === 1 ? "您的预约已提交，请耐心等待常客审核吧~" : "您已成功接受邀请啦~",
              success() {
                if (that.data.type === 1) {
                  my.navigateBack()
                }
              }
            })
          } else {
            showToast(res.msg);
          }
        });
      }
    });
  },
  // 获取常客信息
  getVisitoryByUserVisitorListDetailId(id) {
    var {
      form
    } = this.data;
    getVisitoryByUserVisitorListDetailId({
      userVisitorListDetailId: id
    }).then(res => {
      form.userVisitorListDetailId = res.data.id;
      form.correctPhone = res.data.phone;
      form.visiteePhone = res.data.visiteePhone;
      form.visiteeBuilding = res.data.visiteeBuilding;
      form.visiteeBuildingId = res.data.visiteeBuildingId;
      form.visiteeCompany = res.data.visiteeCompany;
      form.visiteeXm = res.data.visiteeXm;
      form.userWhitelistId = res.data.userWhitelistId;
      form.startTime = res.data.startTime;
      form.endTime = res.data.endTime;
      form.reason = res.data.reason;
      // form.personnelType = res.data.personnelType;
      let building_list = [{
        adminId: res.data.visiteeBuildingId,
        username: res.data.visiteeBuilding
      }];
      this.reasonEcho(res.data.reason);
      let companyList = [{
        adminId: res.data.visiteeCompanyId,
        companyName: res.data.visiteeCompany
      }];
      this.setData({
        form,
        building_list: building_list,
        buildingIndex: 0,
        companyList: companyList,
        companyIndex: 0,
        isAudit: true,
        personTypIndex: res.data.personnelType
      });
      // this.getBuildingList({
      //     adminId: res.data.visiteeBuildingId,
      //     name: res.data.visiteeBuilding
      // });
      this.matchCorrectPhone();
      this.getContextByAdminId(res.data.visiteeBuildingId);
      this.getThreeCodeByAdminId(res.data.visiteeBuildingId);
    });
  },
  // 来访事由
  reasonEcho(name) {
    let reason = {
      name
    };
    let index = this.data.reasonList.map(item => {
      return JSON.stringify(item);
    }).indexOf(JSON.stringify(reason));
    if (index > -1) {
      this.setData({
        reasonIndex: index
      });
    }
  },
  // 更具楼宇id检查楼宇列表是否有符合条件的对象及获得其数组下标
  getBuildingList(buildingObj) {
    getBuildingList().then(res => {
      this.setData({
        building_list: res.data
      });
      if (!buildingObj) return;
      console.log(buildingObj);
      let index = res.data.map(item => {
        return JSON.stringify(item);
      }).indexOf(JSON.stringify(buildingObj));
      if (index > -1) {
        this.setData({
          buildingIndex: index,
          "form.visiteeBuildingId": buildingObj.adminId,
          "form.visiteeBuilding": buildingObj.name
        });
        this.matchStepComplete();
      }
    });
  },
  //获取是否有自定义字段
  getContextByAdminId(orgId) {
    wx.showLoading({
      title: "检查配置中.."
    });
    getContextByAdminId(orgId).then(res => {
      if (res.code == 200) {
        this.setData({
          isShowApplet: res.data,
          isFillFields: !res.data
        });
        this.matchStepComplete();
      } else {
        showToast(res.msg);
      }
      wx.hideLoading();
    });
  },
  // 判断自定义字段是否填写完成
  isFillFields(e) {
    this.data.isFillFields = e.detail;
    this.matchStepComplete();
  },
  // 查询三码信息
  getThreeCodeByAdminId(adminId) {
    wx.showLoading({
      title: "检查配置中.."
    });
    getThreeCodeByAdminId({
      adminId
    }).then(res => {
      wx.hideLoading();
      this.setData({
        threeCodeList: res.data.threeCodeList,
        hsHour: res.data.hsHour
      });
      if (res.data.threeCodeList.length == 0) {
        this.data.isthreeYards = true;
        this.matchStepComplete();
      }
    });
  },
  // 三码填写内容
  isthreeYards(e) {
    this.data.isthreeYards = e.detail;
    this.matchStepComplete();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // options = {
    //     userVisitorDetailId: 13499
    // }
    if(!options || !options.formMain) {
      let launchOptions = my.getLaunchOptionsSync()
      if(!launchOptions.query) {
        launchOptions = my.getEnterOptionsSync()
      }
      if (launchOptions.query && launchOptions.query.userVisitorDetailId) {
        this.getVisitoryByUserVisitorListDetailId(launchOptions.query.userVisitorDetailId);
        this.setData({
          type: 2
        });
      }
    }
    this.updateSetting();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideBackHome()
    this.setData({
      language: app.data.language
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  antmoveAction: function () {
    //执行时动态赋值，请勿删除
  }
});