var util = require('../../../utils/util');
var api = require('../../../config/api.js');
var check = require('../../../utils/check.js');
var user = require('../../../utils/user.js');
var area = require('../../../utils/area.js');


var app = getApp();
Page({
  data: {
    username: '',
    mobile: '',
    birthday: '',
    code: '',
    nid: '',
    type: 0,
    userInfo: {},
    show: false,
    items: [{
      name: "钟点工",
      value: 1,
      checked:false
    }, {
      name: "白班保姆",
      value: 2,
      checked:false
    }, {
      name: "住家保姆",
      value: 3,
      checked:false
    }],
    address: {
      id: 0,
      areaCode: 0,
      address: '',
      isDefault: 0,
      province: '',
      city: '',
      county: ''
    },
    isread: 0,
    openSelectRegion: false,
    checked: false,
    selectRegionList: [{
        code: 0,
        name: '省份'
      },
      {
        code: 0,
        name: '城市'
      },
      {
        code: 0,
        name: '区县'
      }
    ],
    regionType: 1,
    regionList: [],
    selectRegionDone: false
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数

    /* 页面渲染完成 */
    if (app.globalData.hasLogin) {
      let userInfo = wx.getStorageSync('userInfo');
      this.setData({
        userInfo: userInfo
      })
    }
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
    let that = this;
    //初始化安心包历史数据信息
    let cus = wx.getStorageSync('nurseInfo');
    if (cus) {
      that.setData({
        username: cus.username,
        mobile: cus.mobile,
        nid: cus.nid,
        type:cus.type
      })

      //缓存中 保姆类型  
      console.info(cus)
      let _items= that.data.items;
      let _index=parseInt(cus.type)-1;
      _items[_index].checked=true; 
      that.setData({
        items:_items
      });

      let address = this.data.address;
      address.address = cus.address;
      address.province = cus.province;
      address.city = cus.city;
      address.county = cus.county;
      address.areaCode = cus.regionId;
      that.setData({
        address: address
      });
    }

  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  radioChange(e) {
    console.info(e)
    this.setData({
      type:e.detail.value
    })
  },
  bindinputAddress(event) {
    let address = this.data.address;
    address.address = event.detail.value;
    this.setData({
      address: address
    });
  },
  bindIsRead(e) {
    let that = this;
    this.setData({
      isread: that.data.isread == 0 ? 1 : 0
    });
  },
  setRegionDoneStatus() {
    let that = this;
    let doneStatus = that.data.selectRegionList.every(item => {
      return item.code != 0;
    });

    that.setData({
      selectRegionDone: doneStatus
    })

  },
  chooseRegion() {
    let that = this;
    this.setData({
      openSelectRegion: !this.data.openSelectRegion
    });

    //设置区域选择数据
    let address = this.data.address;
    if (address.areaCode > 0) {
      let selectRegionList = this.data.selectRegionList;
      //console.info(selectRegionList);
      selectRegionList[0].code = address.areaCode.slice(0, 2) + '0000';
      selectRegionList[0].name = address.province;

      selectRegionList[1].code = address.areaCode.slice(0, 4) + '00';
      selectRegionList[1].name = address.city;

      selectRegionList[2].code = address.areaCode;
      selectRegionList[2].name = address.county;

      let regionList = area.getList('county', address.areaCode.slice(0, 4));
      regionList = regionList.map(item => {
        //标记已选择的
        if (address.areaCode === item.code) {
          item.selected = true;
        } else {
          item.selected = false;
        }
        return item;
      })

      this.setData({
        selectRegionList: selectRegionList,
        regionType: 3,
        regionList: regionList
      });

    } else {
      let selectRegionList = [{
          code: 0,
          name: '省份',
        },
        {
          code: 0,
          name: '城市',
        },
        {
          code: 0,
          name: '区县',
        }
      ];

      this.setData({
        selectRegionList: selectRegionList,
        regionType: 1,
        regionList: area.getList('province')
      });
    }

    this.setRegionDoneStatus();
  },
  selectRegionType(event) {
    console.info('selectRegionType');

    let that = this;
    let regionTypeIndex = event.target.dataset.regionTypeIndex;
    let selectRegionList = that.data.selectRegionList;

    //判断是否可点击
    if (regionTypeIndex + 1 == this.data.regionType || (regionTypeIndex - 1 >= 0 && selectRegionList[regionTypeIndex - 1].code <= 0)) {
      return false;
    }

    let selectRegionItem = selectRegionList[regionTypeIndex];
    let code = selectRegionItem.code;
    let regionList;
    if (regionTypeIndex === 0) {
      // 点击省级，取省级
      regionList = area.getList('province');
    } else if (regionTypeIndex === 1) {
      // 点击市级，取市级
      regionList = area.getList('city', code.slice(0, 2));
    } else {
      // 点击县级，取县级
      console.info(code);
      regionList = area.getList('county', code.slice(0, 4));
      console.info(regionList);
    }

    regionList = regionList.map(item => {
      //标记已选择的
      if (that.data.selectRegionList[regionTypeIndex].code == item.code) {
        item.selected = true;
      } else {
        item.selected = false;
      }
      return item;
    })

    this.setData({
      regionList: regionList,
      regionType: regionTypeIndex + 1
    })

    this.setRegionDoneStatus();
  },
  selectRegion(event) {
    let that = this;
    let regionIndex = event.target.dataset.regionIndex;
    let regionItem = this.data.regionList[regionIndex];
    let regionType = this.data.regionType;
    let selectRegionList = this.data.selectRegionList;
    selectRegionList[regionType - 1] = regionItem;

    if (regionType == 3) {
      this.setData({
        selectRegionList: selectRegionList
      })

      let regionList = that.data.regionList.map(item => {
        //标记已选择的
        if (that.data.selectRegionList[that.data.regionType - 1].code == item.code) {
          item.selected = true;
        } else {
          item.selected = false;
        }
        return item;
      })
      this.setData({
        regionList: regionList
      })

      this.setRegionDoneStatus();
      return
    }

    //重置下级区域为空
    selectRegionList.map((item, index) => {
      if (index > regionType - 1) {
        item.code = 0;
        item.name = index == 1 ? '城市' : '区县';
      }
      return item;
    });

    //console.info(selectRegionList);

    this.setData({
      selectRegionList: selectRegionList,
      regionType: regionType + 1
    })


    let code = regionItem.code;
    let regionList = [];
    if (regionType === 1) {
      // 点击省级，取市级
      regionList = area.getList('city', code.slice(0, 2))
    } else {
      // 点击市级，取县级
      regionList = area.getList('county', code.slice(0, 4))
    }

    this.setData({
      regionList: regionList
    })

    this.setRegionDoneStatus();
  },
  doneSelectRegion() {
    if (this.data.selectRegionDone === false) {
      return false;
    }

    let address = this.data.address;
    let selectRegionList = this.data.selectRegionList;
    address.province = selectRegionList[0].name;
    address.city = selectRegionList[1].name;
    address.county = selectRegionList[2].name;
    address.areaCode = selectRegionList[2].code;

    this.setData({
      address: address,
      openSelectRegion: false
    });

  },
  cancelSelectRegion() {
    this.setData({
      openSelectRegion: false,
      regionType: this.data.regionDoneStatus ? 3 : 1
    });

  },
  showPopup() {
    this.setData({
      show: true
    });
  },
  //获取手机号 一键注册
  getPhoneNumber: function (e) {
    console.log(e.detail.encryptedData);
    user.denPhone(e.detail).then(res => {
      this.setData({
        mobile: res.data
      })
    }).catch((err) => {
      console.log(err);
      /*wx.navigateTo({ //授权过期 需要重新授权
        url: '/pages/auth/login/login?reg=1',
      })*/
    });
  },

  requestRegister: function () {
    let that = this;
    let auth = {
      username: that.data.username,
      mobile: that.data.mobile,
      region: that.data.address.province + that.data.address.city + that.data.address.county,
      province: that.data.address.province,
      city: that.data.address.city,
      county: that.data.address.county,
      regionId: that.data.address.areaCode,
      address: that.data.address.address,
      nid: that.data.nid,
      type:that.data.type
    };
    wx.setStorageSync('nurseInfo', auth);

    util.request(api.AuthCert, auth).then(function (res) {
      if (res.errno == 0) {
        wx.showToast({
          title: '实名认证成功',
          icon: 'success',
          duration: 2000,
          complete: function () {
            setTimeout(function () {
              wx.navigateTo({
                url: '/pages/checkout/checkout?nurseId=' + res.data,
              })
            }, 2000);
          }
        });
      } else {
        wx.showModal({
          title: '错误信息',
          content: res.errmsg,
          showCancel: false
        });
      }
    });

  },
  startRegister: function () {
    var that = this;
    if (that.data.username.length < 2) {
      wx.showModal({
        title: '错误信息',
        content: '请输入真实姓名',
        showCancel: false
      });
      return false;
    }

    if (that.data.nid.length != 18 || !check.isCardCheck(that.data.nid)) {
      wx.showModal({
        title: '错误信息',
        content: '身份证号码不正确',
        showCancel: false
      });
      return false;
    }
    if (that.data.mobile.length == 0 || !check.isValidPhone(that.data.mobile)) {
      wx.showModal({
        title: '错误信息',
        content: '手机号输入不正确',
        showCancel: false
      });
      return false;
    }
    if (that.data.address.areaCode == 0) {
      wx.showModal({
        title: '错误信息',
        content: '请选择省市区信息',
        showCancel: false
      });
      return false;
    }
    if (that.data.address.address.length < 5) {
      wx.showModal({
        title: '错误信息',
        content: '请输入详细地址',
        showCancel: false
      });
      return false;
    }

    that.requestRegister();
  },
  bindUsernameInput: function (e) {
    this.setData({
      username: e.detail.value
    });
  },
  bindNidInput: function (e) {
    this.setData({
      nid: e.detail.value
    });
  },
  confirmFn(e) {
    var newTime = new Date(e.detail);
    newTime = util.formetdate(newTime);
    this.setData({
      birthday: newTime,
      show: false
    });
  },
  // 时间-取消按钮
  cancelFn() {
    this.setData({
      show: false
    });
  },
  bindConfirmPasswordInput: function (e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },
  bindMobileInput: function (e) {

    this.setData({
      mobile: e.detail.value
    });
  },
  clearInput: function (e) {
    switch (e.currentTarget.id) {
      case 'clear-username':
        this.setData({
          username: ''
        });
        break;
      case 'clear-password':
        this.setData({
          password: ''
        });
        break;
      case 'clear-confirm-password':
        this.setData({
          confirmPassword: ''
        });
        break;
      case 'clear-mobile':
        this.setData({
          mobile: ''
        });
        break;
      case 'clear-nid':
        this.setData({
          nid: ''
        });
        break;
      case 'clear-address':
        let address = this.data.address;
        address.address = '';
        this.setData({
          address: address
        });
        break;
    }
  }
})