const _my = require("../../__antmove/api/index.js")(my);
const wx = _my;
// pages/regular_register/regular_register.js
import international from "../../international/appointment_scence/index";
const {
  getBuildingList,
  userWhiteCheck,
  getCompanyList
} = require("../../utils/api/api");
const {
  showToast
} = require("../../utils/func/request");
const {
  throttle
} = require("../../utils/throttle/throttle");
import { getContextByAdminId } from "../../utils/api/customField";
import { getThreeCodeByAdminId } from "../../utils/api/three_yards";
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    international: international,
    //国际化语言包
    language: "ch",
    isDisabled: false,
    isSubmit: false,
    showMyFun: false,
    // 功能列表
    component_list: [{
      id: 1,
      name_ch: "重新下发",
      name_en: "Again issued",
      icon: "../../static/mine/deliver_again.png",
      url: ""
    }, {
      id: 2,
      name_ch: "认证信息",
      name_en: "Authentication information",
      icon: "../../static/mine/certification_msg.png",
      url: ""
    }, {
      id: 3,
      name_ch: "邀请人员",
      name_en: "Invite people",
      icon: "../../static/mine/my_appointment.png",
      url: ""
    }],
    building_list: [],
    //楼宇列表
    buildingAdminId: null,
    buildingName: null,
    buildingIndex: null,
    companyList: [],
    //公司列表
    companyAdminId: null,
    companyName: null,
    //是否显示企业名称&存储企业名称
    companyIndex: null,
    isRegularQRCode: false,
    //是否是扫企业常客码进入，需满足扫码的企业id和选择的企业id必需相同&常客的type必需为1
    isShowApplet: false,
    //是否开启自定义字段
    threeCodeList: [],
    //是否开启三码
    temporary_adminInfo: null,
    //判断是否是扫描进来
    newCompanyList: [] //允许被显示的企业列表
  },

  // 更新个人信息
  updateSetting() {
    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.adminInfo) {
        this.setData({
          showMyFun: true,
          companyName: app.data.adminInfo.companyName
        });
      }
    }
    if (app.data.userInfo && !app.data.adminInfo) {
      this.getBuildingList();
    }
  },
  // 获取是否可以展示信息
  getUpdateState(e) {
    if (e.detail) {
      this.updateSetting();
    }
  },
  // 获取认证状态
  getCertificationState(e) {
    if (e.detail) {
      showToast("认证成功~");
      wx.setStorageSync("language", app.data.language);
      this.setData({
        isDisabled: true
      });
      this.updateSetting();
    } else {
      showToast("认证失败了，再试一次吧~");
    }
  },
  //获取输入or选择的内容
  getValue(e) {
    switch (e.currentTarget.dataset.type) {
      case "buildingAdminId":
        this.setData({
          buildingAdminId: e.detail.adminId,
          buildingName: e.detail.name
        });
        this.getCompanyList();
        this.getContextByAdminId(e.detail.adminId);
        this.getThreeCodeByAdminId(e.detail.adminId);
        break;
      case "companyAdminId":
        this.setData({
          companyAdminId: e.detail.adminId
        });
        // this.data.companyAdminId = e.detail.adminId
        this.data.companyName = e.detail.name;
        break;
      default:
        form[e.currentTarget.dataset.type] = e.detail;
        break;
    }
    this.canOperation();
  },
  // 判断提交按钮是否禁用
  canOperation() {
    let {
      buildingAdminId,
      companyAdminId,
      isSubmit,
      isRegularQRCode,
      isFillFields,
      isthreeYards
    } = this.data;
    isSubmit = buildingAdminId != null && companyAdminId != null && isFillFields && isthreeYards ? true : false;
    isRegularQRCode = app.data.temporary_adminInfo && app.data.temporary_adminInfo.visiteeCompanyId === companyAdminId && app.data.type === 1;
    this.setData({
      isSubmit,
      isRegularQRCode
    });
    // my.alert({
    //   title:'canOperation-->isSubmit',
    //   content: `isSubmit=${isSubmit},buildingAdminId=${buildingAdminId},companyAdminId=${companyAdminId},isFillFields=${isFillFields},isthreeYards=${!!isthreeYards}`,
    // });
  },
  // 提交
  sure() {
    let {
      buildingAdminId,
      buildingName,
      companyAdminId,
      companyName,
      isRegularQRCode,
      isFillFields,
      isthreeYards
    } = this.data;
    if (buildingAdminId && companyAdminId) {
      let data = {
        adminId: buildingAdminId,
        userId: app.data.userInfo.userId,
        companyAdminId: companyAdminId,
        type: isRegularQRCode ? 1 : 0,
        addCustomList: isFillFields == true ? null : isFillFields,
        hs: isthreeYards.hs || null,
        hsPhoto: isthreeYards.hsPhoto || null,
        jkm: isthreeYards.jkm || null,
        jkmPhoto: isthreeYards.jkmPhoto || null,
        xc: isthreeYards.xc || null,
        xcPhoto: isthreeYards.xcPhoto || null,
        xcPhone: isthreeYards.xcPhone || null
      };
      userWhiteCheck(data).then(res => {
        const that = this;
        if (res.code == 200) {
          let adminInfo = {
            adminId: buildingAdminId,
            buildingName: buildingName,
            companyAdminId: companyAdminId,
            companyName: res.data[0].companyName,
            userWhitelistId: res.data[0].userWhitelistId
          };
          wx.setStorageSync("adminInfo", adminInfo);
          app.data.adminInfo = adminInfo;
          my.alert({
            title: '提示',
            content: '恭喜绑定企业成功~',
            complete() {
              that.setData({
                showMyFun: true,
                companyName: companyName
              });
              wx.requestSubscribeMessage({
                entityIds: ["9d4ddcd78f66444482ad66c5a262ffed"],
                success(res) {},
                complete() {}
              });
            }
          });
        } else {
          showToast(res.msg);
        }
      });
    } else {
      showToast("请选择所在楼宇");
    }
  },
  // 查找企业
  getCompanyList() {
    wx.showLoading({
      title: "获取企业列表..."
    });
    this.setData({
      companyAdminId: null
    });
    this.data.companyName = null;
    let data = {
      adminId: this.data.buildingAdminId
    };
    getCompanyList(data).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        let companyIndex = null;
        let newCompanyList = [];
        if (res.data.length > 0) {
          res.data.forEach(item => {
            if (item.isCanSearch) {
              newCompanyList.push(item);
            }
          });
          if (app.data.temporary_adminInfo) {
            let index = res.data.findIndex(item => {
              return item.adminId === app.data.temporary_adminInfo.visiteeCompanyId;
            });
            if (index > -1) {
              companyIndex = index;
              this.setData({
                companyAdminId: res.data[index].adminId,
                companyName: res.data[index].name
              });
              // this.data.companyName = res.data[index].name;
            }
          } else if (newCompanyList.length === 1) {
            companyIndex = 0;
            this.setData({
              companyAdminId: newCompanyList[0].adminId
            });
            this.data.companyName = newCompanyList[0].name;
          }
        } else {
          showToast("该楼宇下暂无企业");
        }
        this.canOperation();
        this.setData({
          companyList: res.data,
          companyIndex: companyIndex,
          newCompanyList
        });
      } else {
        showToast(res.msg);
      }
    });
  },
  // 获取楼宇列表
  getBuildingList() {
    getBuildingList().then(res => {
      let buildingIndex = null;
      if (res.data.length === 1) {
        this.data.buildingName = res.data[0].name;
        this.setData({
          buildingAdminId: res.data[0].adminId
        });
        this.getCompanyList();
        this.getContextByAdminId(this.data.buildingAdminId);
        this.getThreeCodeByAdminId(this.data.buildingAdminId);
        buildingIndex = 0;
      } else if (app.data.temporary_adminInfo) {
        let index = res.data.findIndex(item => {
          return item.adminId === app.data.temporary_adminInfo.visiteeBuildingId;
        });
        if (index > -1) {
          buildingIndex = index;
          this.setData({
            buildingAdminId: res.data[index].adminId
          });
          this.data.buildingName = res.data[index].name;
          this.getCompanyList();
          this.getContextByAdminId(this.data.buildingAdminId);
          this.getThreeCodeByAdminId(this.data.buildingAdminId);
        }
      }
      this.setData({
        building_list: res.data,
        buildingIndex: buildingIndex
      });
    });
  },
  goto(e) {
    let id = e.currentTarget.dataset.id;
    let url = "";
    if (id == 1) {
      this.doPass();
      return;
    } else if (id == 2) {
      url = "/pages/regular_msg/regular_msg";
    } else if (id == 3) {
      wx.requestSubscribeMessage({
        entityIds: ["486ef1e5652a4629b6e95245f7cb44a9"],
        success(res) {
          if(res.behavior === 'subscribe') {
            url = "/pages/regular_invite/regular_invite";
            wx.navigateTo({
              url
            })
            return
          }
        }
      });
    }
    if(!url) {
      return
    }
    wx.navigateTo({
      url
    });
  },
  //人脸下发
  doPass: throttle(function () {
    let data = {
      adminId: app.data.adminInfo.adminId,
      userId: app.data.userInfo.userId,
      companyAdminId: app.data.adminInfo.companyAdminId,
      // 写死的数据
      hsPhoto: "http://hanghui.oss-cn-gz-ysgzlt-d01-a.ltops.gzdata.com.cn/photo/20221125/66bb7a8feac6425d9b87f57351d4ca08.jpg",
      jkm: "绿码",
      xc: "1"
    };
    wx.showLoading({
      title: "申报中.."
    });
    userWhiteCheck(data).then(res => {
      if (res.code == 200) {
        this.data.timeCount = 30;
        this.countDown();
        this.data.userInfo.createTime = res.data.date;
        my.alert({
          content: '恭喜申报成功，您已获得闸机快速通行权限，如有疑问，请就近联系管理人员',
          complete() {}
        });
      } else {
        this.data.userInfo.createTime = "";
        wx.showModal({
          content: res.msg,
          showCancel: false
        });
      }
      wx.setStorageSync("userInfo", this.data.userInfo);
      this.getUserInfo();
    }).catch(err => {}).finally(() => {
      wx.hideLoading();
    });
  }, 30000),
  //申报倒计时
  countDown() {
    let {
      timeCount
    } = this.data;
    if (timeCount > 0) {
      setTimeout(() => {
        timeCount--;
        this.setData({
          timeCount
        });
        this.countDown();
      }, 1000);
    }
  },
  //获取是否有自定义字段
  getContextByAdminId(orgId) {
    return getContextByAdminId(orgId).then(res => {
      if (res.code == 200) {
        this.setData({
          isShowApplet: res.data,
          isFillFields: !res.data
        });
        this.canOperation();
      } else {
        showToast(res.msg);
      }
    });
  },
  // 判断是否填写完成
  isFillFields(e) {
    this.data.isFillFields = e.detail;
    this.canOperation();
  },
  // 查询三码信息
  getThreeCodeByAdminId(adminId) {
    getThreeCodeByAdminId({
      adminId
    }).then(res => {
      //暂时关闭常客三码功能-s
      res.data.threeCodeList = [];
      this.data.isthreeYards = {
        hsPhoto: "http://hanghui.oss-cn-gz-ysgzlt-d01-a.ltops.gzdata.com.cn/photo/20221125/66bb7a8feac6425d9b87f57351d4ca08.jpg",
        jkm: "绿码",
        xc: "1"
      };
      //暂时关闭常客三码功能-d
      this.setData({
        threeCodeList: res.data.threeCodeList,
        hsHour: res.data.hsHour
      });
      this.canOperation();
      //暂时关闭常客三码功能-s
      // if (res.data.threeCodeList.length == 0) {
      //     this.data.isthreeYards = true
      //     this.canOperation()
      // }
      //暂时关闭常客三码功能-d
    });
  },

  // 三码填写内容
  isthreeYards(e) {
    this.data.isthreeYards = e.detail;
    this.canOperation();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.updateSetting();
    this.setData({
      language: app.data.language,
      temporary_adminInfo: app.data.temporary_adminInfo
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  antmoveAction: function () {
    //执行时动态赋值，请勿删除
  }
});