const _my = require("../../__antmove/api/index.js")(my);
const wx = _my;
const app = getApp();
const {
  getBuildingList,
  userWhiteCheck,
  getCompanyList
} = require("../../utils/api/api");
import international from "../../international/appointment_scence/index";
import { showToast } from "../../utils/func/request";
import { getContextByAdminId } from "../../utils/api/customField";
import { getThreeCodeByAdminId } from "../../utils/api/three_yards";
const {
  desensitization
} = require("../../utils/util");
// pages/make_appointment/changeUserInfo/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    international: international,
    language: "ch",
    isDisabled: false,
    isSubmit: false,
    userInfo: null,
    adminInfo: app.data.adminInfo,
    phone: app.data.userInfo ? app.data.userInfo.phone : null,
    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: app.data.temporary_adminInfo || null,
    //判断是否是扫描进来
    newCompanyList: [] //允许被显示的企业列表
  },

  // 获取认证状态
  getCertificationState(e) {
    let that = this;
    if (e.detail) {
      wx.showModal({
        title: "温馨提醒",
        content: app.data.language === "ch" ? "认证成功~" : "change person message successfully ~",
        showCancel: false,
        success() {
          wx.setStorageSync("language", app.data.language);
          //返回上一页
          wx.navigateBack({
            delta: 1
          });
        }
      });
    } else {
      wx.showModal({
        title: "温馨提醒",
        content: app.data.language === "ch" ? "认证失败，再试一次吧~" : "change failed , please try again ~",
        showCancel: false
      });
    }
  },
  // 获取是否可以展示信息
  getUpdateState(e) {
    if (e.detail) {
      this.setData({
        language: app.data.language,
        userInfo: app.data.temporary_userInfo,
        isDisabled: false
      });
    }
  },
  //更新视图
  updateSetting() {
    this.setData({
      language: app.data.language,
      userInfo: app.data.userInfo,
      isDisabled: true
    });
  },
  //获取输入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.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
    });
  },
  // 提交
  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
      };
      wx.showLoading({
        title: "加载中..."
      });
      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({
                companyName: companyName
              });
            }
          });
        } else {
          showToast(res.msg);
        }
      }).finally(() => {
        wx.hideLoading();
      });
    } 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
              });
              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 if (app.data.adminInfo) {
            let index = res.data.findIndex(item => {
              return item.adminId === app.data.adminInfo.companyAdminId;
            });
            if (index > -1) {
              companyIndex = index;
              this.setData({
                companyAdminId: res.data[index].adminId
              });
              this.data.companyName = res.data[index].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 (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);
        }
      } else if (res.data.length === 1) {
        this.setData({
          buildingAdminId: res.data[0].adminId
        });
        this.data.buildingName = res.data[0].name;
        this.getCompanyList();
        this.getContextByAdminId(this.data.buildingAdminId);
        this.getThreeCodeByAdminId(this.data.buildingAdminId);
        buildingIndex = 0;
      } else if (app.data.adminInfo) {
        let index = res.data.findIndex(item => {
          return item.adminId === app.data.adminInfo.adminId;
        });
        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
      });
    });
  },
  //获取是否有自定义字段
  getContextByAdminId(orgId) {
    return getContextByAdminId(orgId).then(res => {
      this.setData({
        isShowApplet: res.data,
        isFillFields: !res.data
      });
      this.canOperation();
    });
  },
  // 判断是否填写完成
  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"
      };
      this.canOperation();
      //暂时关闭常客三码功能-d

      this.setData({
        threeCodeList: res.data.threeCodeList,
        hsHour: res.data.hsHour
      });
      //暂时关闭常客三码功能-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) {
    let userInfo = JSON.parse(JSON.stringify(app.data.userInfo));
    if (userInfo) {
      userInfo.username = desensitization(userInfo.username, 1, 2);
      userInfo.idNumber = desensitization(userInfo.idNumber, 6, 14);
      userInfo.phone = desensitization(userInfo.phone, 3, 7);
    }
    this.setData({
      language: app.data.language,
      userInfo: app.data.language === "ch" ? userInfo : null,
      isDisabled: false,
      adminInfo: app.data.adminInfo
    });
    this.getBuildingList();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  antmoveAction: function () {
    //执行时动态赋值，请勿删除
  }
});