const app = getApp()
const utils = require("../../utils/util.js")
Page({
  data: {
    selectedTag: '',
    showCustomInput: false,
    customTagLength: 0,
    showDrawer: false,
    showPreview: false,
    // 是否可以切换水务公司
    isChange: true,

    // 新增数据
    waterCompany: '',
    waterCompanyList: app.globalData.waterCompanys,
    //当前用户的默认水务公司的下标
    waterCompanyIndex: [0],
    waterCompanyId: app.globalData.launchPara,
    showWaterCompanyPicker: false,
    
    huHao: '',
    huMing: '',
    customTag: '',
    tagLength: 0,
    showQueryMethods: false,
    // 水站联系方式
    phoneQueryList: [
    ],
    // 户号预览图地址
    ylt:''
  },

  selectTag(e) {
    const tag = e.currentTarget.dataset.tag;
    this.setData({
      selectedTag: tag,
      showCustomInput: tag === '自定义'
    });
  },

  onCustomInput(e) {
    const value = e.detail.value;
    this.setData({
      customTagLength: value.length,
      customTag: value
    });
  },

  // 显示抽屉
  showDrawer() {
    this.setData({
      showDrawer: true
    });
  },

  // 隐藏抽屉
  hideDrawer() {
    this.setData({
      showDrawer: false
    });
  },

  // 拨打电话
  makePhoneCall(e) {
    const phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    });
  },

  // 修改预览图片方法
  previewImage: function() {
    this.setData({
      showPreview: true
    });
  },

  // 关闭预览
  closePreview: function() {
    this.setData({
      showPreview: false
    });
  },

  // 防止点击图片内容时关闭预览
  preventBubble: function() {
    return;
  },

  // 显示水站公司选择器
  showWaterCompanyPicker: function() {
    
    this.setData({
      showWaterCompanyPicker: true,
      waterCompanyIndex: this.data.waterCompanyIndex
    });
  },

  // 隐藏水站公司选择器
  hideWaterCompanyPicker: function() {
    this.setData({
      showWaterCompanyPicker: false
    });
  },

  // 水站公司选择变化
  onWaterCompanyChange: function(e) {
    
    this.setData({
      waterCompanyIndex: e.detail.value
    });
  },

  // 确认水站公司选择
  confirmWaterCompany: function(e) {
    
    const index = this.data.waterCompanyIndex[0];
    this.setData({
      waterCompanyIndex: this.data.waterCompanyIndex,
      waterCompany: this.data.waterCompanyList[index].name,
      showWaterCompanyPicker: false,
      phoneQueryList:  this.data.waterCompanyList[index].businessPoint.map((data,index)=>{
        return  {
          id: index+1,
          name:  index+1+'、'+data.address,
          phone: data.cphone,
          time: data.worktime
        }
      }),
      ylt:app.globalData.imgPreviewUrl+this.data.waterCompanyList[index].swCompanyInfo.overduenoticeimage.split("-;-")[1]
      
    });
  },

  // 户号输入
  onHuHaoInput: function(e) {
    this.setData({
      huHao: e.detail.value
    });
  },

  // 户名输入
  onHuMingInput: function(e) {
    this.setData({
      huMing: e.detail.value
    });
  },

  // 确认绑定
  confirmBinding: function() {
    // 验证必填字段
    if (!this.data.waterCompany) {
      wx.showToast({
        title: '请选择水站公司',
        icon: 'none'
      });
      return;
    }

    if (!this.data.huHao) {
      wx.showToast({
        title: '请输入户号',
        icon: 'none'
      });
      return;
    }

    if (!this.data.huMing) {
      wx.showToast({
        title: '请输入户名',
        icon: 'none'
      });
      return;
    }

    // 处理分组信息
    let groupInfo = this.data.selectedTag;
    if (this.data.selectedTag === '自定义' && this.data.customTag) {
      groupInfo = this.data.customTag;
    }

    // 提交数据
    wx.showLoading({
      title: '绑定中...',
    });
    // 调用绑定接口
    wx.request({
      url: app.globalData.interfaceUrls.accountBind,
      method: 'POST',
      data: {
        bindWaterCompany: this.data.waterCompanyList[this.data.waterCompanyIndex[0]].id,
        accountNum: this.data.huHao,
        accountName: this.data.huMing,
        groupType: groupInfo,
        openId: app.globalData.userWxInfo.openId,
        defaultAccount: 0,
        otherDsKey: (app.globalData.bindAccountInfo||[]).map(data=>data.dsKey)
      },
      header: {
        'content-type': 'application/json', // 默认值
        'token':app.globalData.userWxInfo.token,
        'source':"wc",
        '!SAAS_LOGIN_TOKEN_!':this.data.waterCompanyList[this.data.waterCompanyIndex[0]].id
      },
      success (res) {
        wx.hideLoading();
        let apiReturnData=res.data
        if(apiReturnData.code=='200'){
          wx.hideLoading();
          utils.simleInfo('绑定成功')
          app.globalData.currentAccountInfo=apiReturnData.data[0];
          setTimeout(function(){
            app.globalData.refresh=1;
            wx.switchTab({
              url: '/pages/homepage/homepage',
            });
          },2000)
        }else{
          wx.showToast({
            title: apiReturnData.msg,
            icon: 'error',
            duration: 2000
          })
          wx.hideLoading();
        }
      },fail(error) {
        wx.hideLoading()
        utils.simleInfo('登录失败，请稍后再试')
      }
    })
  },

  onLoad: function() {
    // 延迟设置导航栏，确保页面已完全加载
    setTimeout(() => {
      wx.setNavigationBarTitle({
        title: '户号绑定'
      });
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#0066FF'
      });
    }, 100);
    if(app.globalData.launchPara){
      this.setData({
        waterCompanyIndex:[app.globalData.waterCompanys.findIndex(data=>data.id==app.globalData.launchPara)],
        waterCompany: app.globalData.waterCompanys.filter(data=>data.id==app.globalData.launchPara)[0].name,
        isChange:false,
        phoneQueryList: app.globalData.waterCompanys.filter(data=>data.id==app.globalData.launchPara)[0].businessPoint.map((data,index)=>{
          return  {
            id: index+1,
            name: data.address,
            phone: data.contactphone,
            time: data.worktime
          }
        }),
        ylt:app.globalData.imgPreviewUrl+app.globalData.waterCompanys.filter(data=>data.id==app.globalData.launchPara)[0].swCompanyInfo.overduenoticeimage.split("-;-")[1]
      });
    }
  },

  // 添加返回方法
  navigateBack: function() {
    wx.navigateBack();
  },

  onTagInput(e) {
    this.setData({
      tagLength: e.detail.value.length
    });
  },

  showQueryMethodsModal() {
    this.setData({
      showQueryMethods: true
    });
  },

  closeQueryMethods() {
    this.setData({
      showQueryMethods: false
    });
  }
});
