const app = getApp();
const webSocket = require('../../utils/websocket.js');
Page({

  data: {
    heightid: 0,
    heightArray: [], // 身高-数据
    heightindex: [0, 0],  // 身高-下标


    Ageid: 0,
    AgeArray: [],    //  年龄-数据
    AgeIndex: [0, 0],    //  年龄-下标

    // MarriageArray: [], // 婚史-数据
    // Marriageindex: '',  // 婚史-下标

    EducationArray: [], // 学历-数据
    Educationindex: '',  // 学历-下标

    inputValue: '', //用户ID
    sex: 0,   //  性别  
    age: 0,      //  年龄  
    height: 0,      //  身高  



    education: 0,    //  学历  
    educationid: 0,
    // marry: 0,    //   婚史 
    // idmarry: 0,
    income: 0,
    // income: '',     //  收入 
    // occupation: '',     //  职业  

    // home: '', //列表信息

    // tab: [true, true, true, true],

    home: [], //定义列表信息数组

    // tabTxt: ['性别', '年龄', '婚史', '特色'],//tab文案
    page: 1,//当前页码
    limit: 10,//获取条数
    morehide: true,   //暂无更多信息显示隐藏
    moreTxt: '',



    // 省市区
    city: 0,     // 市  要传的数据
    provinceName: '',     // 省 要传的数据
    cityName: '',     // 市  要传的数据
    areaName: '',     // 区 要传的数据

    provincedata: '', //省数据
    provinceid: 1,   //省选中ID
    provincetext: '北京', //省 名字
    citydata: '', //市数据
    cityidx: '', //市选中ID
    citytext: '', //市 名字
    areadata: '', //区数据

    scrolltop: '', //市区滚动条
    hiddenName: true, //显示隐藏

  },


  onShow: function (options) {
    var that = this;
    // webSocket.connectSocket();
    var _trigger = app.globalData.trigger      //    搜索或清空
    // console.log(_trigger);
    if (_trigger == true){
      that.onLoad();
    } 
    app.globalData.trigger = false;


  },
 
 
//  触发聊天
  onReady: function (options){
    webSocket.connectSocket();
  },

  onLoad: function (options) {
    var that = this;



    that.Getlocation();   //获取地理位置

    that.setData({
      page: 1,//当前页码
    })


    var _Selection = app.globalData.Selection      //  是否选中     1选中 0没选中
    var _income = app.globalData.income      //  收入  


    // if (app.globalData.idmarry) {
    //   that.setData({
    //     idmarry: app.globalData.idmarry
    //   })
    // }

    if (app.globalData.educationid) {
      that.setData({
        educationid: app.globalData.educationid
      })
    }

    if (app.globalData.inputValue) {    //用户ID
      that.setData({
        inputValue: app.globalData.inputValue
      })
    }



    if (app.globalData.income) {
      that.setData({
        income: _income,
      })
    } else if (app.globalData.income == 0 && _Selection == 1) {     //判断筛选页面  是否清空数据   同时 是否选中,而不是返回
      that.setData({
        income: _income,
      })
    }
    // console.log(_Selection)

    var _city = app.globalData.city      //  市 
    var _provincename = app.globalData.provinceName  //  省 名称
    var _cityname = app.globalData.cityName   //  市 名称
    var _areaname = app.globalData.areaName      //  区  名称

    if (_provincename ||  _cityname && _Selection == 1) {
      that.setData({
        city: _city,
        provinceName: _provincename,  // 省名称
        cityName: _cityname, // 市名称
        areaName: _areaname,  // 区名称
      })
      console.log(_provincename)
      console.log(_cityname)
    } else if (_provincename == '' && _cityname == '' &&  _Selection == 1){
      that.setData({
        city: _city,
        provinceName: _provincename,  // 省名称
        cityName: _cityname, // 市名称
        areaName: _areaname,  // 区名称
      })

    }




    //  年龄 ajax
    let Age_url = 'public/paramsgather?type=age';
    let Age_data = {};


    if (app.globalData.age) {    //判断 是否从筛选页面传来的参数

      var _age = app.globalData.age      //  年龄  

      var agenewArry = _age.split("-");  //转成数组
      var _age_min = agenewArry[0]
      var _age_max = agenewArry[1]

      // console.log(_age_min)
      // console.log(_age_max)
      that.setData({
        Ageid: 0,
        age: _age
      })
    } else if (app.globalData.age == 0 && _Selection == 1) {     //判断筛选页面  是否清空数据   同时 是否选中,而不是返回
      var _age = app.globalData.age      //  年龄  

      that.setData({
        age: _age,
        Ageid: 0,
        AgeIndex: ['', '']
      })
    }

    app.postRequest(Age_url, Age_data, function (res) {   //  年龄 ajax
      if (res.code == 201) {

        if (app.globalData.age) {

          let newarray = ['不限'];
          var res_data = newarray.concat(res.data);      //在原有的数据上 凭借上 不限

          let newarray1 = ['以上'];
          var res_data1 = newarray1.concat(res.data);      //在原有的数据上 凭借上 以上


          let min = data_processing(res_data, _age_min);      //已选中的数据处理  min
          let max = data_processing(res_data1, _age_max);   //已选中的数据处理  max

          that.setData({
            AgeIndex: [min, max]
          })
        }

        let dictObject = res.data;    //对象不能直接使用  以下转成数组
        // 对象转成数组
        var createArr = []
        for (let i in dictObject) {
          createArr.push(dictObject[i] + "岁");
        }

        let bx = ['不限'];
        var Unlimited = bx.concat(createArr);

        let ys = ['以上'];
        var Above = ys.concat(createArr);

        that.setData({
          AgeArray: [Unlimited, Above],
        })

        // console.log(createArr);           
      }

    })


    //  身高 ajax
    let height_url = 'public/paramsgather?type=height';
    let height_data = {
      pid: '0'
    };

    if (app.globalData.height) {    //判断 是否从筛选页面传来的参数
      // console.log(app.globalData.height);
      var _height = app.globalData.height      //  身高  

      var heightnewArry = _height.split("-");  //转成数组
      var heightSmall = heightnewArry[0]
      var heightlarge = heightnewArry[1]

      // console.log(heightSmall)
      // console.log(heightlarge)
      that.setData({
        height: _height,
        heightid: 0
      })
    } else if (app.globalData.height == 0 && _Selection == 1) {     //判断筛选页面  是否清空数据   同时 是否选中,而不是返回
      var _height = app.globalData.height      //  身高  
      that.setData({
        height: _height,
        heightid: 0,
        heightindex: ['', ''],  // 身高-下标
      })
    }

    app.postRequest(height_url, height_data, function (res) {      //  身高 ajax
      if (res.code == 201) {

        if (app.globalData.height) {

          let newarray = ['不限'];
          var res_data = newarray.concat(res.data);      //在原有的数据上 凭借上 不限

          let newarray1 = ['以上'];
          var res_data1 = newarray1.concat(res.data);      //在原有的数据上 凭借上 以上


          let min = data_processing(res_data, heightSmall);      //已选中的数据处理  min
          let max = data_processing(res_data1, heightlarge);   //已选中的数据处理  max

          that.setData({
            heightindex: [min, max]
          })

        }


        let dictObject = res.data;        //对象不能直接使用  以下转成数组
        // 对象转成数组
        var createArr = []
        for (let i in dictObject) {
          createArr.push(dictObject[i] + "cm");
        }

        let bx = ['不限'];
        var Unlimited = bx.concat(createArr);

        let ys = ['以上'];
        var Above = ys.concat(createArr);

        // console.log(createArr);
        that.setData({
          heightArray: [Unlimited, Above],
        })

      }

    })


    //  婚史 ajax
    // let Marriage_url = 'public/paramsgather?type=marriage';
    // let Marriage_data = {};

    // if (app.globalData.marry) {    //判断 是否从筛选页面传来的参数
    //   // console.log(app.globalData.marry);
    //   var _marry = app.globalData.marry      //  婚姻 

    //   that.setData({
    //     marry: _marry
    //   })
    // } else if (app.globalData.marry == 0 && _Selection == 1) {     //判断筛选页面  是否清空数据   同时 是否选中,而不是返回
    //   var _marry = app.globalData.marry   //  婚姻 
    //   that.setData({
    //     marry: _marry,
    //     Marriageindex: "",  // 身高-下标
    //   })
    // }

    // app.postRequest(Marriage_url, Marriage_data, function (res) {      //  婚史 ajax
    //   if (res.code == 201) {
    //     if (app.globalData.marry) {
    //       for (let i = 0; i < res.data.length; i++) {    //已选中的数据处理
    //         if (i == _marry) {
    //           that.setData({
    //             Marriageindex: i,
    //           })
    //         }
    //       }
    //     }

    //     that.setData({
    //       MarriageArray: res.data,
    //       idmarry: that.data.idmarry,
    //     })
    //   }
    // })


    //  学历 ajax
    let Education_url = 'public/paramsgather?type=xueli';
    let Education_data = {};

    if (app.globalData.education) {    //判断 是否从筛选页面传来的参数
      // console.log(app.globalData.marry);
      var _education = app.globalData.education      //  学历 

      that.setData({
        education: _education
      })
    } else if (app.globalData.education == 0 && _Selection == 1) {     //判断筛选页面  是否清空数据   同时 是否选中,而不是返回
      var _education = app.globalData.education   //  学历 
      that.setData({
        education: _education,
        Educationindex: "",  // 学历-下标
      })
    }

    app.postRequest(Education_url, Education_data, function (res) {      //  学历 ajax
      if (res.code == 201) {

        var obj = { id: 0, education_name: '不限' };
        var datares = res.data;
        datares.unshift(obj)

        if (app.globalData.education) {


          for (let i = 0; i < datares.length; i++) {    //已选中的数据处理
            if (datares[i].id == _education) {
              that.setData({
                Educationindex: i,
              })
            }
          }
        }

        that.setData({
          EducationArray: datares,
          educationid: that.data.educationid,
        })
      }
    })





    that.list();
  },




  heightEvent: function (e) {   //  身高   
    var that = this;
    // console.log(this);
    // console.log(e);
    // console.log(this.data.heightArray[e.detail.value]);
    // console.log('picker发送选择改变,携带值为', e.detail.value)
    var _value = e.detail.value;  //发送选择改变,携带值为
    var heightSmall = this.data.heightArray[0][e.detail.value[0]].substring(0, 3);
    var heightlarge = this.data.heightArray[1][e.detail.value[1]].substring(0, 3);

    // console.log(heightdata)
    if (heightSmall > heightlarge && heightSmall != '不限' && heightlarge != '以上') {     //判断  最小值  大于  最大值  数据互换
      //  console.log('调换')
      var heightdata = heightlarge + '-' + heightSmall;
      that.Exchange(_value);    // 调用数组调换

    } else {

      var heightdata = heightSmall + '-' + heightlarge;

    }


    that.setData({
      heightindex: _value,
      height: heightdata,
      heightid: 1,
    })

    that.list();

    app.globalData.Selection = 0;    //  是否选中  
    app.globalData.height = 0;    //  身高  
  },



  // 年龄双选
  AgeEvent: function (e) {
    var that = this;
    var _value = e.detail.value;  //发送选择改变,携带值为
    // console.log('picker发送选择改变,携带值为', e.detail.value)
    var Small = this.data.AgeArray[0][e.detail.value[0]].substring(0, 2);
    var large = this.data.AgeArray[1][e.detail.value[1]].substring(0, 2);

    // console.log(Agedata);
    if (Small > large && Small != '不限' && large != '以上') {     //判断  最小值  大于  最大值  数据互换
      //  console.log('调换')
      var Agedata = large + '-' + Small;
      that.Exchange(_value);    // 调用数组调换

    } else {

      var Agedata = Small + '-' + large;    //否则正常选中

    }





    that.setData({
      AgeIndex: _value,
      age: Agedata,
      Ageid: 1,
      page: 1,

    })

    that.list();  //调用筛选

    app.globalData.Selection = 0;    //  是否选中  
    app.globalData.age = 0;    //  年龄  
  },



  // 数组数据调换
  Exchange: function (data) {
    for (var i = 0; i < data.length / 2; i++) {
      var data_i = data[i];
      data[i] = data[data.length - 1 - i];
      data[data.length - 1 - i] = data_i;
    }
    return;
  },


  // MarriageEvent: function (e) {   //  婚史    单项选择器
  //   var that = this;
  //   // console.log(this);
  //   // console.log(e);
  //   // console.log(this.data.MarriageArray[e.detail.value]);
  //   // console.log('picker发送选择改变,携带值为', e.detail.value)
  //   this.setData({
  //     Marriageindex: e.detail.value,
  //     marry: e.detail.value,
  //     page: 1,
  //     idmarry: 1,
  //   })

  //   that.list(); //调用筛选

  //   app.globalData.Selection = 0;    //  是否选中  
  //   app.globalData.marry = 0  //  婚史  
  // },



  EducationEvent: function (e) {   //  学历    单项选择器
    var that = this;
    // console.log(this);
    // console.log(e);
    // console.log(this.data.EducationArray[e.detail.value].id);
    // console.log('picker发送选择改变,携带值为', e.detail.value)
    this.setData({
      Educationindex: e.detail.value,
      education: this.data.EducationArray[e.detail.value].id,
      page: 1,
      educationid: 1,
    })

    that.list(); //调用筛选


    app.globalData.Selection = 0;    //  是否选中  
    app.globalData.education = 0  //  学历  
  },





  More: function () {
    var that = this;
    // console.log(that.data.age);



    // console.log(that.data.provinceName);
    // console.log(that.data.cityName);
    // console.log(that.data.areaName);
    // '&marry=' + that.data.marry + '&idmarry=' + that.data.idmarry + 

    wx.navigateTo({
      url: '/pages/index_screen/index_screen?age=' + that.data.age + '&height=' + that.data.height + '&education=' + that.data.education + '&income=' + that.data.income + '&educationid=' + that.data.educationid +'&city=' + that.data.city +  '&provinceName=' + that.data.provinceName + '&cityName=' + that.data.cityName + '&areaName=' + that.data.areaName +  ''
    })


  },



  //  上拉加载更多
  onReachBottom() {
    var that = this;

    let _age = transformation(that.data.age)      //不限以上 转换成0
    let _height = transformation(that.data.height)      //不限以上 转换成0
    let _income = transformation(that.data.income)      //不限以上 转换成0


    that.showLoading();   //提示加载中
    //  列表信息


    var home_url = 'circle/friend/home';

    if (that.data.inputValue) {    //判断 搜索用户ID存在  只传用户ID

      var home_data = {
        page: (that.data.page++) + 1,
        limit: that.data.limit,
        number: that.data.inputValue,   //  性别  
      };

      // console.log('用户ID');


    } else {     //否则 传常规选择

      var home_data = {
        page: (that.data.page++) + 1,
        limit: that.data.limit,
        age: _age,      //  年龄  
        height: _height,   //  身高  
        // marry: that.data.marry,    //   婚史 
        education: that.data.education,    //  学历  
        income: _income,  //收入
        city: that.data.city,                    // 市
      };

      // console.log('选择');

    }


    app.postRequest(home_url, home_data, function (res) {

      if (res.code == 201) {
        // console.log(res.data);
        var home = that.data.home

        // var moreTxt = '';
        // if (0 < (res.data.length < 10)) {
        //   moreTxt = res.msg;
        //   // console.log('无')
        // } else {
        //   moreTxt = ''
        //   // console.log('有')
        // }

        // 设置数据
        for (var i = 0; i < res.data.length; i++) {
          home.push(res.data[i]);
        }

        that.setData({
          home: home,
          morehide: true,
        })

        that.cancelLoading();   //数据加载完关闭
        return;
      }


      that.cancelLoading();   //数据加载完关闭

      that.setData({
        home_code: res.code,
        morehide: false,
        moreTxt: res.msg,
      })



    })
  },





  list: function () {
    var that = this;

    let _age = transformation(that.data.age)       //不限以上 转换成0
    let _height = transformation(that.data.height)       //不限以上 转换成0
    let _income = transformation(that.data.income)      //不限以上 转换成0

    that.showLoading();   //提示加载中
    //  列表信息
    let home_url = 'circle/friend/home';

    if (that.data.inputValue) {    //判断 搜索用户ID存在  只传用户ID

      var home_data = {
        page: that.data.page,
        limit: that.data.limit,
        number: that.data.inputValue,   //  性别  
      };

    } else {     //否则 传常规选择

      var home_data = {
        page: that.data.page,
        limit: that.data.limit,
        age: _age,      //  年龄  
        height: _height,   //  身高  
        // marry: that.data.marry,    //   婚史 
        education: that.data.education,    //  学历  
        income: _income,  //收入
        city: that.data.city,                    // 市
      };

    }


    app.postRequest(home_url, home_data, function (res) {
      that.setData({
        inputValue: '',
      })

      var moreTxt = '';
      
      if (res.code == 201) {

   
        // if (res.data.length < 10) {
        //   moreTxt = res.msg
        // } else {
        //   moreTxt = ''
        // }

        // console.log(res.data);
        that.setData({
          home: res.data,
          morehide: true,
          home_code: res.code,
        })

        that.cancelLoading();   //数据加载完关闭

        return;
      }

      that.cancelLoading();   //数据加载完关闭



      that.setData({
        home: res.data,
        morehide: false,
        moreTxt: res.msg,
      })



  


    })

  },

  // 加载
  showLoading: function () {

    wx.showLoading({

      title: '加载中',

      icon: 'loading'

    });

  },
  // 关闭加载
  cancelLoading: function () {
    wx.hideLoading();
  },




  // 省市区三级联动 点击弹窗
  linkage: function (e) {
    var that = this;
    let citypid_url = 'public/citypid';
    let citypid_data = {};
    app.postRequest(citypid_url, citypid_data, function (res) {      //  省市区三级联动 ajax
      if (res.code == 201) {

        that.setData({
          provincedata: res.data,   // 省数据
        })

        // console.log(res.data)
        that.provinceOn();
      }
    })

  },


  // 省事件
  provinceOn: function (e) {
    var that = this;
    // console.log(e);
    if (e) {
      that.setData({
        provinceid: e.currentTarget.dataset.id,    //省ID
        provincetext: e.currentTarget.dataset.text,   //省名字
      })
    }
    // console.log(that.data.provinceid);
    // console.log(that.data.provincetext)

    let citypid_url = 'public/citypid';
    let citypid_data = {
      pid: that.data.provinceid,
    };
    app.postRequest(citypid_url, citypid_data, function (res) {      //  省市区三级联动 ajax
      if (res.code == 201) {

        that.setData({
          hiddenName: false,
          citydata: res.data,   // 市数据
          scrolltop: 0,    //市区滚动条
          areadata: '',    //区域数据清空
          cityidx: '',   // idx  选中清空
        })

        // console.log(res.data)

      }
    })

  },

  // 市事件
  cityOn: function (e) {
    var that = this;
    var _cityidx = that.data.cityidx
    var cityid = e.currentTarget.dataset.id;     //市ID
    var citytext = e.currentTarget.dataset.text;     //市名字
    var _index = e.currentTarget.dataset.index + 1;     //下标
    // console.log(_index);
    // console.log(_index*42,);
    // console.log(_cityidx);
    // console.log(cityid);
    that.setData({
      cityidx: cityid,  // 市  选中
      citytext: citytext, // 市 选中名字
      areadata: '',    //区域数据清空
    })

    let citypid_url = 'public/citypid';
    let citypid_data = {
      pid: cityid,
    };
    app.postRequest(citypid_url, citypid_data, function (res) {      //  省市区三级联动 ajax
      if (res.code == 201) {

        if (_cityidx == cityid) {
          that.setData({
            areadata: '',   // 区数据
            cityidx: '',   // idx  选中清空
          })
        } else {
          that.setData({
            areadata: res.data,   // 区数据
            scrolltop: _index * 42,
          })
          // console.log('执行')
          //   console.log(_index * 42);
        }
        // console.log(res.data)
      }

    })

  },


  //区选中事件
  areaOn: function (e) {
    var that = this;

    var _style = e.currentTarget.dataset.style;
    // console.log(_style);


    var regionid = e.currentTarget.dataset.id;     //传递地区ID
    // console.log(regionid);


    switch (_style) {

      case 'provinceLx':
        // console.log('省');
        that.setData({
          city: regionid,
          provinceName: that.data.provincetext, // 省名字
          cityName: '',   // 市名字清空
          areaName: "",  //  区名字
          page: 1,
        })
        break;

      case 'cityLx':
        // console.log('市');
        that.setData({
          city: regionid,
          provinceName: that.data.provincetext, // 省名字
          cityName: that.data.citytext, // 省名字
          areaName: "",  //  区名字
          page: 1,
        })
        break;

      case 'areaLx':
        // console.log('区');
        var areatext = e.currentTarget.dataset.text;     //区名字
        that.setData({
          city: regionid,
          provinceName: that.data.provincetext, // 省名字
          cityName: that.data.citytext, // 省名字
          areaName: areatext,   //  区名字
          page: 1,
        })
        break;

    }
    
    // console.log(that.data.city)
    // console.log(that.data.provinceName)
    // console.log(that.data.cityName)
    // console.log(that.data.areaName)

    that.list(); //调用筛选

    that.setData({
      hiddenName: true,
      provinceid: 1,
      provincetext: '北京', //省 名字
      cityidx: 0,
      citytext: '',
    })

    app.globalData.Selection = 0;    //  是否选中  
  },

  //省市区不限
  regionBx: function () {
    var that = this;
    that.setData({
      hiddenName: true,
      provinceid: 1,
      provincetext: '北京', //省 名字
      cityidx: 0,
      citytext: '',

      provinceName:'', // 省名字
      city: 0,   // 市数据清空
      cityName: '',   // 市名字清空
      areaName: "",  //  区名字
      page: 1,//当前页码
    })

    that.list(); //调用筛选
  },


  //省市区关闭
  Close: function () {
    var that = this;
    that.setData({
      hiddenName: true,
      provinceid: 1,
      provincetext: '北京', //省 名字
      cityidx: 0,
      citytext: '',

    })
  },



  Getlocation: function () {

    wx.getSetting({
      success: (res) => {
        // console.log(JSON.stringify(res))
        // console.log(res)
        // console.log(res.authSetting['scope.userLocation'])
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (!res.authSetting['scope.userLocation']) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请前往授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {

                wx.getLocation({

                  success: function (res) {
                    // console.log(res.latitude)
                    // console.log(res.longitude)
                    getApp().getDistrict(res.latitude, res.longitude);

                  },

                })


              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
        }
        else {
          //调用wx.getLocation的API
        }
      }
    })

  },


})

var data_processing = function (data, min_max, ) {
  for (let i = 0; i < data.length; i++) {    //已选中的数据处理
    if (data[i] == min_max) {
      return i;
    }
  }
}


var transformation = function (resdata) {
  if (resdata) {
    let newArry = resdata.split("-");  //转成数组

    if (newArry[0] == '不限' || newArry[0] == undefined) {
      var _min = 0
    } else {
      var _min = newArry[0];
    }

    if (newArry[1] == '以上' || newArry[1] == undefined) {
      var _max = 0
    } else {
      var _max = newArry[1];
    }

    resdata = _min + '-' + _max
  }
  return resdata;


}