// pages/openAShop/openAShop.js
var http = require('../../utils/http.js');
var config = require("../../utils/config.js");
const util = require('../../utils/util.js');
var index = [18, 0, 0];

var t = 0;
var show = false;
var moveY = 200;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    logoImg: {},
    idcardFrontImg: {},
    idcardBackImg: {},
    bussLicenImg: {},
    value: [0, 0, 0],
    provArray: [],
    cityArray: [],
    areaArray: [],
    province: "",
    city: "",
    area: "",
    provinceId: 0,
    cityId: 0,
    areaId: 0,
    latitude: '', //经度
    longitude: '', //纬度
    mapAddress: '', //地图定位详细地址
    mapAddrName: '', //地图上的地址名称
    shopNameValue: '', //店铺名字
    shopDescribeValue: '', //店铺描述
    shopAddrValue: '', //详细地址
    shopOwnerValue: '', //店主姓名
    shopOwnerPhoneValue: '', //店主联系电话
    auditRemarks: ""
  },

  /**
   * 请求接口传数据
   */
  submitApply: function() {
    if (this.data.shopNameValue.trim().length < 2 || this.data.shopNameValue.trim().length > 10) {
      wx.showToast({
        title: '请输入正确的店铺名称',
        icon: "none"
      })
    } else if (this.data.shopDescribeValue.trim().length < 10 || this.data.shopDescribeValue.trim().length > 200) {
      wx.showToast({
        title: '请输入正确店铺描述',
        icon: "none"
      })
    } else if (!this.data.logoImg.path) {
      wx.showToast({
        title: '请上传店铺LOGO',
        icon: "none"
      })
    } else if (this.data.shopAddrValue.trim().length < 5) {
      wx.showToast({
        title: '请输入正确的详细地址：不得少于5字',
        icon: "none"
      })
    } else if (this.data.latitude == '') {
      wx.showToast({
        title: '请选择地理位置',
        icon: "none"
      })
    } else if (this.data.shopOwnerPhoneValue.trim().length < 7) {
      wx.showToast({
        title: '请输入正确的联系电话',
        icon: "none"
      })
    } else if (!this.data.bussLicenImg.path) {
      wx.showToast({
        title: '请上传营业执照',
        icon: "none"
      })
    } else if (!this.data.idcardFrontImg.path || !this.data.idcardBackImg.path) {
      wx.showToast({
        title: '请上传身份证正反两面',
        icon: "none"
      })
    } else {
      wx.showLoading();
      var params = {
        url: "/p/shop/apply",
        method: "POST",
        data: {
          "area": this.data.area,
          "areaId": this.data.areaId,
          "businessLicense": this.data.bussLicenImg.path,
          "city": this.data.city,
          "cityId": this.data.cityId,
          "identityCardFront": this.data.idcardFrontImg.path,
          "identityCardLater": this.data.idcardBackImg.path,
          "intro": this.data.shopDescribeValue.trim(),
          "province": this.data.province,
          "provinceId": this.data.provinceId,
          "shopAddress": this.data.shopAddrValue,
          "shopLogo": this.data.logoImg.path,
          "shopName": this.data.shopNameValue.trim(),
          "shopPhotos": "",
          "tel": this.data.shopOwnerPhoneValue.trim(),
          "shopLat": this.data.latitude,
          "shopLng": this.data.longitude,
        },
        callBack: function(res) {
          wx.hideLoading();
          wx.showModal({
            title: '提交成功，等待审核',
            content: '',
            showCancel: false,
            success: function() {
              wx.switchTab({
                url: '/pages/user/user',
              })
            }
          })

        }
      }
      http.request(params);
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.shopAuditStatus == -1) {
      wx.showModal({
        title: '提示',
        content: '您的开店申请审核未通过，请您修改申请信息后再次提交开店申请',
        success: (res) => {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.showLoading();
            var params = {
              url: "/p/shop",
              method: "GET",
              data: {},
              callBack: (res) => {
                wx.hideLoading();
                this.setData({
                  logoImg: {
                    url: res.shopLogo,
                    path: res.shopLogo.indexOf(config.picDomain) > -1 ? res.shopLogo.replace(config.picDomain,'') : res.shopLogo
                  },
                  idcardFrontImg: {
                    url: res.identityCardFront,
                    path: res.identityCardFront.indexOf(config.picDomain) > -1 ? res.identityCardFront.replace(config.picDomain,'') : res.identityCardFront
                  },
                  idcardBackImg: {
                    url: res.identityCardLater,
                    path: res.identityCardLater.indexOf(config.picDomain) > -1 ? res.identityCardLater.replace(config.picDomain,'') : res.identityCardLater
                  },
                  bussLicenImg: {
                    url: res.businessLicense,
                    path: res.businessLicense.indexOf(config.picDomain) > -1 ? res.businessLicense.replace(config.picDomain,'') : res.businessLicense
                  },
                  province: res.province,
                  city: res.city,
                  area: res.area,
                  provinceId: res.provinceId,
                  cityId: res.cityId,
                  areaId: res.areaId,
                  latitude: res.shopLat,
                  longitude: res.shopLng,
                  shopNameValue: res.shopName, //店铺名字
                  shopDescribeValue: res.intro, //店铺描述
                  shopAddrValue: res.shopAddress, //详细地址
                  shopOwnerPhoneValue: res.tel
                });
                this.initCityData(this.data.provinceId, this.data.cityId, this.data.areaId);
                this.getAuditMsg();
              }
            }
          } else if (res.cancel) {
            console.log('用户点击取消')
            wx.switchTab({
              url: '/pages/user/user',
            })
          }
          http.request(params);
        }
      })
    } else {
      this.initCityData(this.data.provinceId, this.data.cityId, this.data.areaId);
    }
  },

  getAuditMsg() {
    http.request({
      url: "/p/shop/shopAudit",
      method: "GET",
      data: {},
      callBack: (res) => {
        this.setData({
          auditRemarks: res.remarks
        });
      }
    });
  },

  /**
   * 获取经纬度
   */
  chooseLocation: function(e) {
    var that = this
    wx.chooseLocation({
      success: function (res) {
        console.log('succes1')
        console.log(res)
        that.setMapData(res)
      },
      fail: function () {
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']) {
              console.log("f1")
              wx.authorize({
                scope: 'scope.userLocation',
                success() {
                  wx.chooseLocation({
                    success: function (res) {
                      that.setMapData(res)
                    },
                  })
                  console.log('success2')
                },
                fail() {
                  wx.showToast({
                    title: '请在「右上角」 - 「关于」 - 「右上角」 - 「设置」授予获取位置信息的权限',
                    icon: 'none'
                  })
                }
              })
            }
          }
        })
      }
    })
  },
  setMapData(res) {
    var latitude = res.latitude
    var longitude = res.longitude
    var address = res.address
    var name = res.name
    console.log("经度：" + latitude, "纬度：" + longitude, "详细地址：" + address)
    this.setData({
      latitude: latitude,
      longitude: longitude,
      mapAddress: address,
      mapAddrName: name
    })
  },
  /**
   * 获取input数据
   */
  bindShopNameInt: function(e) {
    this.setData({
      shopNameValue: e.detail.value
    })
  },
  bindShopDescribeInt: function(e) {
    this.setData({
      shopDescribeValue: e.detail.value
    })
  },
  bindShopAddrInt: function(e) {
    this.setData({
      shopAddrValue: e.detail.value
    })
  },
  bindShopOwnerInt: function(e) {
    this.setData({
      shopOwnerValue: e.detail.value
    })
  },
  bindShopOwnerPhoneInt: function(e) {
    this.setData({
      shopOwnerPhoneValue: e.detail.value
    })
  },


  /**
   * 上传图片
   */
  getUploadImg: function(e) {
    const type = e.target.dataset.type

    console.log(type);
    var ths = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        // 图片的本地临时文件路径列表
        var tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          mask: true
        })
        var params = {
          url: "/p/file/upload",
          filePath: tempFilePaths[0],
          name: 'file',
          callBack: function(res2) {
            wx.hideLoading();
            var img = {};
            img.path = JSON.parse(res2).filePath;
            img.url = JSON.parse(res2).resourcesUrl + JSON.parse(res2).filePath;
            if (type == 'bussLicenImg') {
              ths.setData({
                bussLicenImg: img
              })
            } else if (type == 'logoImg') {
              ths.setData({
                logoImg: img
              })
            } else if (type == 'idcardFrontImg') {
              ths.setData({
                idcardFrontImg: img
              })
            } else if (type == 'idcardBackImg') {
              ths.setData({
                idcardBackImg: img
              })
            }
          }
        };
        http.upload(params);
      }
    })
  },

  /**
   * 删除图片
   */
  removeImage: function(e) {
    const type = e.target.dataset.type
    if (type == 'logoImg') {
      this.setData({
        logoImg: {}
      });
    } else if (type == 'idcardFrontImg') {
      this.setData({
        idcardFrontImg: {}
      });
    } else if (type == 'idcardBackImg') {
      this.setData({
        idcardBackImg: {}
      });
    } else if (type == 'bussLicenImg') {
      this.setData({
        bussLicenImg: {}
      });
    }
    console.log('删除图片')
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // 底部弹框动画
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 0,
      timingFunction: "ease",
      delay: 0
    })
    this.animation.translateY(200 + 'vh').step();
    this.setData({
      animation: this.animation.export(),
      show: show
    })
  },

  /**
   * 获取省市区
   */
  initCityData: function(provinceId, cityId, areaId) {
    var ths = this;
    wx.showLoading();
    var params = {
      url: "/p/area/listByPid",
      method: "GET",
      data: {
        pid: 0
      },
      callBack: function(res) {
        //console.log(res)
        ths.setData({
          provArray: res
        });
        if (provinceId) {
          for (var index in res) {
            if (res[index].areaId == provinceId) {
              ths.setData({
                value: [index, ths.data.value[1], ths.data.value[2]]
              });
            }
          }
        }
        ths.getCityArray(provinceId ? provinceId : res[0].areaId, cityId, areaId);
        wx.hideLoading();
      }
    }
    http.request(params);
  },


  /**
   * 滑动事件
   */
  bindChange: function(e) {
    var ths = this;
    var val = e.detail.value

    //判断滑动的是第几个column
    //若省份column做了滑动则定位到地级市和区县第一位
    if (index[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
      //更新数据
      ths.getCityArray(this.data.provArray[val[0]].areaId); //获取地级市数据
    } else { //若省份column未做滑动，地级市做了滑动则定位区县第一位
      if (index[1] != val[1]) {
        val[2] = 0;
        //更新数据
        ths.getAreaArray(this.data.cityArray[val[1]].areaId); //获取区县数据
      } else {

      }
    }
    index = val;
    this.setData({
      value: [val[0], val[1], val[2]],
    })
    ths.setData({
      province: ths.data.provArray[ths.data.value[0]].areaName,
      city: ths.data.cityArray[ths.data.value[1]].areaName,
      area: ths.data.areaArray[ths.data.value[2]].areaName,
      provinceId: ths.data.provArray[ths.data.value[0]].areaId,
      cityId: ths.data.cityArray[ths.data.value[1]].areaId,
      areaId: ths.data.areaArray[ths.data.value[2]].areaId
    })
  },


  /**
   * 根据省份ID获取 城市数据
   */
  getCityArray: function(provinceId, cityId, areaId) {
    var ths = this;
    var params = {
      url: "/p/area/listByPid",
      method: "GET",
      data: {
        pid: provinceId
      },
      callBack: function(res) {
        //console.log(res)
        ths.setData({
          cityArray: res
        });
        if (cityId) {
          for (var index in res) {
            if (res[index].areaId == cityId) {
              ths.setData({
                value: [ths.data.value[0], index, ths.data.value[2]]
              });
            }
          }
        }
        ths.getAreaArray(cityId ? cityId : res[0].areaId, areaId);
        wx.hideLoading();
      }
    }
    http.request(params);
  },

  /**
   * 根据城市ID获取 区数据
   */
  getAreaArray: function(cityId, areaId) {
    var ths = this;
    var params = {
      url: "/p/area/listByPid",
      method: "GET",
      data: {
        pid: cityId
      },
      callBack: function(res) {
        //console.log(res)
        ths.setData({
          areaArray: res
        });
        if (areaId) {

          for (var _index in res) {
            if (res[_index].areaId == areaId) {
              ths.setData({
                value: [ths.data.value[0], ths.data.value[1], _index]
              });
            }
          }

          index = ths.data.value;

          ths.setData({
            province: ths.data.province,
            city: ths.data.city,
            area: ths.data.area,
            provinceId: ths.data.provinceId,
            cityId: ths.data.cityId,
            areaId: ths.data.areaId
          })

        } else {
          ths.setData({
            province: ths.data.provArray[ths.data.value[0]].areaName,
            city: ths.data.cityArray[ths.data.value[1]].areaName,
            area: ths.data.areaArray[ths.data.value[2]].areaName,
            provinceId: ths.data.provArray[ths.data.value[0]].areaId,
            cityId: ths.data.cityArray[ths.data.value[1]].areaId,
            areaId: ths.data.areaArray[ths.data.value[2]].areaId
          })
        }

        wx.hideLoading();
      }
    }
    http.request(params);
  },


  /**
   * 移动按钮点击事件
   */
  translate: function(e) {
    if (t == 0) {
      moveY = 0;
      show = false;
      t = 1;
    } else {
      moveY = 200;
      show = true;
      t = 0;
    }
    this.setData({
      show: true
    });
    // this.animation.translate(arr[0], arr[1]).step();
    this.animationEvents(this, moveY, show);

  },


  /**
   * 隐藏弹窗浮层
   */
  hiddenFloatView(e) {
    //console.log(e);
    moveY = 200;
    show = true;
    t = 0;
    this.animationEvents(this, moveY, show);

  },


  /**
   * 动画事件
   */
  animationEvents: function(that, moveY, show) {
    //console.log("moveY:" + moveY + "\nshow:" + show);
    that.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 400,
      timingFunction: "ease",
      delay: 0
    })
    that.animation.translateY(moveY + 'vh').step()

    that.setData({
      animation: that.animation.export()
    })

  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})