// packageH/installationSever/installationSeverApply/installationSeverApply.js

var app = getApp();
var location = require("../../../mybehaviors/location/location");

Page({
  behaviors: [location],

  /**
   * 页面的初始数据
   */
  data: {
    //  shop_commission:false,//是否开启平台提成
    customer_open: true,
    // service_QRcode: '',
    // service_mobile: '',

    // msgText: 0,
    // pass_safe: 0,
    // showtips: true,
    // swlist: [],
    swlis: [],
    // shenqShow: false,

    uploadUrl: "",
    o2o_status: 1,

    //定位信息
    address: "",
    point: {
      lat: "",
      lng: "",
    },
    city: "",
    title: "",
    noIs: true,
    bor: true,
    showDel: false,
    applyModel: {
      name: "", //姓名
      mobile: "", //手机号
      id_card_number: "", //身份证
      user_comment: "", //备注

      lng: "",
      lat: "",

      id_card_image_front: "", //身份证正面
      id_card_image_back: "", //身份证反面

      other_image: [], //其他图片

      //省市区 街道id
      provinceId: "",
      cityId: "",
      districtId: "",
      streetId: "",
      address: "",
    },

    strShow: false,
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    districtVal: [],
    streetShow: false,
    addressShow: false,
    addressName: "",
    provice: "",
    // beginTimeshow: false,
    // endTimeshow: false,
    imageUrl: "",
    // hotelTitleType: '',
    // levelShow: false,

    goods_id: "",
    status: false, // 申请后是否跳页面

    explainFlag: false, //协议弹窗
    slideList: [], //轮播图列表

    apply_id: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try {
      wx.removeStorageSync("applyaddresspoint");
    } catch (e) {
      // Do something when catch error
    }
    this.setData({
      uploadUrl: "upload.uploadPic",
    });
    //加载地址数据初始化
    this._initAddressInfo();
    this.getData();
    this._getLocation((mapdata, e) => {
      this.setData({
        "applyModel.lng": e.lng,
        "applyModel.lat": e.lat,
        mapdata_address: mapdata.address,
      });
    });
    //  this.setWatcher(this.data, this.watch);
  },

  async cancelApply() {
    let confirmFlag = await app.confirm("确定取消审核吗?");
    if (confirmFlag == false) return;
    let { apply_id } = this.data;
    let urlStr = app.getNetAddresss("plugin.live-install.frontend.worker-apply.cancelApply");
    app._getNetWork({
      url: urlStr,
      data: {
        apply_id,
      },
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return;
        this.goHome();
      },
    });
  },

  setExplainFlag() {
    this.setData({
      explainFlag: !this.data.explainFlag,
    });
  },

  showdel(e) {
    console.log(e);
    this.setData({
      showDel: true,
    });
  },

  delIntu_2(e) {
    var delpaths = this.data.showpaths_two;
    let del = e.currentTarget.id;
    delpaths.splice(del, 1);
    this.setData({
      showpaths_two: delpaths,
      "applyModel.other_image": delpaths,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    try {
      var value = wx.getStorageSync("applyaddresspoint");
      if (value) {
        this.setData({
          "applyModel.lng": value.point.lng,
          "applyModel.lat": value.point.lat,
          mapdata_address: value.address,
        });
        console.log(this.data.applyModel);
        // Do something with return value
      }
    } catch (e) {
      console.log(e);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  toGeolocation() {
    wx.navigateTo({
      url: "/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=storeApply",
    });
  },
  tapUrl(e) {
    let link = e.currentTarget.dataset.url;
    if (link == "") return false;
    wx.navigateTo({
      url: link,
    });
  },
  //获取数据
  getData() {
    let urlStr = app.getNetAddresss("plugin.live-install.frontend.worker-apply.getWorkerApply");

    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);
        let apply_text = res.data.apply_text.replace(/<img/g, '<img style="max-width:100%"') ;
        this.setData({
          slideList: res.data.slide_list,
          o2o_status: res.data.apply_data.apply_id > 0 ? 2 : 1,
          apply_id: res.data.apply_data.apply_id,
          apply_text:apply_text
        });
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },


  nameinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.name": val,
    });
  },
  mobileinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.mobile": val,
    });
  },
  idcardnumberinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.id_card_number": val,
    });
  },

  addressShowbtn() {
    this.setData({
      addressShow: true,
    });
  },
  //所在地选择显示
  showAddBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].showAdd"]: true,
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      addressShow: false,
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json,
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
        console.log("over", that.data.selectAddressData);
      },
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  //城市结果
  resultAdd: function () {
    let seleData = this.data.selectAddressData;
    let retCity = seleData[0].name + " " + seleData[1].name + " " + seleData[2].name;
    this.setData({
      addressName: retCity,
      provice: seleData[0].name,
      city: seleData[1].name,
      district: seleData[2].name,
    });
    this.setData({
      "applyModel.provinceId": seleData[0].id,
      "applyModel.cityId": seleData[1].id,
      "applyModel.districtId": seleData[2].id,
      addressShow: false,
    });
    this.getStreet(seleData[2].id);
  },
  //获取街道
  getStreet(param) {
    let that = this;
    let urlStr = "";
    urlStr += app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              strShow: true,
            });
          } else {
            that.setData({
              strShow: false,
            });
          }
        } else {
          that.setData({
            strShow: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  streetShowbtn() {
    this.setData({
      streetShow: true,
    });
  },
  treetShowLeft() {
    this.setData({
      streetShow: false,
    });
  },
  streetConfirm(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      street: item.areaname,
      "applyModel.streetId": item.id,
      streetShow: false,
    });
  },
  addressinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.address": val,
    });
  },

  // 其他图片
  onRead_6() {
    let that = this;
    // let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 9,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        // var tempFilePaths = res.tempFilePaths
        that.unload({
          tempFilePaths: res.tempFilePaths,
        });
      },
    });
  },

  //多张上传方法
  unload(data) {
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[i],
      name: "file",
      formData: null,
      success(resdata) {
        var res = JSON.parse(resdata.data);
        console.log(res.data.img_url);

        that.data.swlis.push(res.data.img_url);
        that.setData({
          showpaths_two: that.data.swlis,
          "applyModel.other_image": that.data.swlis,
        });
        console.log(that.data.applyModel);
      },
      fail(e) {
        fail++;
      },
      complete(e) {
        i++;
        if (i == data.tempFilePaths.length) {
          //当图片传完时，停止调用
          console.log("执行完毕");
          console.log("成功：" + success + " 失败：" + fail);
        } else {
          //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.unload(data); //递归，回调自己
        }
      },
    });
  },

  onRead_4() {
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        // wx.compressImage({
        // 	src: tempFilePaths[0], // 图片路径
        // 	quality: 60, // 压缩质量
        // 	success(e) {
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result == 1) {
              that.setData({
                fileList4: photourl,
                "applyModel.id_card_image_front": res.data.img_url,
              });
              console.log(that.data.applyModel.idCardImg);
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            }
          },
        });
        // },
        // fail(e) {

        // },
        // complete(e) {

        // }
        // })
      },
    });
  },
  onRead_5() {
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        // wx.compressImage({
        // 	src: tempFilePaths[0], // 图片路径
        // 	quality: 60, // 压缩质量
        // 	success(e) {
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result == 1) {
              that.setData({
                fileList5: res.data.img_url,
                "applyModel.id_card_image_back": res.data.img_url,
              });
              console.log(that.data.applyModel);
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            }
          },
        });
      },
      // fail(e) {

      // 		},
      // 		complete(e) {

      // 		}
      // 	})
      // }
    });
  },
  remarkinp(e) {
    let val = e.detail.value;
    console.log(val);
    this.setData({
      "applyModel.user_comment": val,
    });
  },

  Chooseinp(e) {
    let Bol = e.detail;
    this.setData({
      agreementChoose: Bol,
    });
  },
  //提交数据
  setApplyData() {
    console.log(this.data.applyModel);

    if (app._isTextEmpty(this.data.applyModel.name)) return app.tips("请填写姓名");

    if (app._isTextEmpty(this.data.applyModel.mobile)) return app.tips("请填写手机号");

    if (app._isMoblie(this.data.applyModel.mobile)) return app.tips("请输入正确的手机号");

    if (app._isTextEmpty(this.data.applyModel.id_card_number)) return app.tips("请填写身份证号");

    if (app._isTextEmpty(this.data.applyModel.provinceId) || app._isTextEmpty(this.data.applyModel.cityId) || app._isTextEmpty(this.data.applyModel.districtId)) return app.tips("请选择省市区");

    if (app._isTextEmpty(this.data.applyModel.streetId)) return app.tips("请选择街道");

    if (app._isTextEmpty(this.data.applyModel.address)) return app.tips("请填写详细地址");

    if (app._isTextEmpty(this.data.applyModel.lng) || app._isTextEmpty(this.data.applyModel.lat)) return app.tips("经纬度不能为空");

    if (app._isTextEmpty(this.data.applyModel.id_card_image_front)) return app.tips("请上传身份证正面");
    if (app._isTextEmpty(this.data.applyModel.id_card_image_back)) return app.tips("请上传身份证反面");

    if (!this.data.agreementChoose) return app.tips("请同意申请协议");

    let json = JSON.parse(JSON.stringify(this.data.applyModel));
    json.longitude = json.lng;
    json.latitude = json.lat;
    let urlStr = app.getNetAddresss("plugin.live-install.frontend.worker-apply.addApply");

    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return;
        setTimeout(() => {
          //要延时执行的代码
          this.goHome();
        }, 1500); //延迟时间
      },
      fail: function (res) {},
    });
  },

  // 去订单页面
  goOrder() {
    let submitActionTag = "-2"; // 立即购买
    let _optionsId = "";
    let _total = 1;
    let _goodsId = this.data.goods_id;
    wx.redirectTo({
      url: "/packageD/buy/myOrder_v2/myOrder_v2?tag=" + submitActionTag + "&goodsId=" + _goodsId + "&optionsId=" + _optionsId + "&total=" + _total,
    });
  },
  //去商城
  goHome() {
    wx.reLaunch({
      url: "/packageG/index/index",
    });
  },

  watch: {
    "shenqShow,categoryShow,addressShow,streetShow,levelShow,show1": function (newVal, oldVla) {
      console.log("刷新改变");
      setTimeout(() => {
        this.setData({
          coverViewFlag: newVal,
        });
      }, 1000);
    },
  },
  /**
   * 设置监听器
   */
  setWatcher(data, watch) {
    // 接收index.js传过来的data对象和watch对象
    Object.keys(watch).forEach((v) => {
      // 将watch对象内的key遍历
      let names = v.split(",");
      for (let i = 0; i < names.length; i++) {
        this.observe(data, names[i], watch[v]); // 监听data内的v属性，传入watch内对应函数以调用
      }
    });
  },
  /**
   * 监听属性 并执行监听函数
   */
  observe(obj, key, watchFun) {
    let that = this;
    var val = obj[key]; // 给该属性设默认值
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      set: function (value) {
        val = value;
        watchFun.call(that, value, val); // 赋值(set)时，调用对应函数
      },
      get: function () {
        return val;
      },
    });
  },
});
