const app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    startDate: "",
    endDate: "",
    shopName: "", //商店名称
    shopAddress: "", //商店地址
    index: null,
    date: '2021-08-08', //营业时间
    shopLicensePhotos: [], //商店营业执照
    shopLogoPhotos: [], //商店Logo
    textareaBValue: '', //店铺简介,
    isBusiness: true, //是否开业
    selTradeId: '', //行业类型
    shopVideos: [], //宣传视频
    selTemplateId: '1',
    selTradeNames: '请选择行业',
    areaList: [], //地区列表
    area2List: [], //二级区域
    area3List: [], //三级区域
    area1: '请选择省份', //一级区域
    area2: '请选择盟市', //一级区域
    area3: '请选择旗县区', //一级区域
    area1Id: '',
    area2Id: '',
    area3Id: '',
    templeteList: [], //展示模板样式
    industryList: [], //行业
    picker: null,
    imgUrl: app.urls.baseImgUrl
  },
  onLoad(options) {
    this.getShopList()
  },
  getShopList() {
    wx.showLoading({
      title: '加载中...',
    })
    app.http.get(app.urls.getMineShopList, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        if (res.data.rows.length > 0) {
          //跳转商店详情
          wx.redirectTo({
            url: '/pages/mine/shop/mineshop?shopId=' + res.data.rows[0].shopId,
          })
        } else {
          //先判断是否有商店
          this.getAreaDiction('0', 1)
          this.getIndesutryAll()
        }
      })
      .catch(err => {
        wx.hideLoading({})
        wx.showToast({
          title: '数据有误',
        })
        wx.navigateBack({})
      })
  },
  getIndesutryAll() {
    wx.showLoading({
      title: '加载中...',
    })
    var _self = this
    app.http.get(app.urls.getIndustryAll, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        _self.buildIndustryData(res.data)
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  buildIndustryData(data) {
    var _self = this
    var first = {}
    var second = {}

    first.values = data
    first.className = 'column1'
    second.values = data[0].subList
    second.className = 'column2'
    second.defaultIndex = 0
    _self.data.industryList.push(first, second)
    _self.setData({
      industryList: _self.data.industryList
    })
  },
  onHide(e) {
    this.setData({
      isShowIndustry: false
    })
  },
  showChooseTrade(e) {
    this.setData({
      isShowIndustry: true
    })
  },
  onChange(event) {
    var _self = this
    const {
      picker,
      value,
      index
    } = event.detail;
    _self.setData({
      picker: picker
    })
    picker.setColumnValues(1, value[0].subList);
  },
  confirmIndustry() {
    //确定选择行业
    var _self = this
    var value = _self.selectComponent('#picker').getValues()
    if (value[1]) {
      //获取行业模板
      _self.getTempleteList(value[1].industryId)
      _self.setData({
        selTradeId: value[1].industryId,
        selTradeNames: value[1].industryName,
        isShowIndustry: false
      })
    } else {
      wx.showToast({
        title: '请选择行业',
      })
    }
  },
  cancelIndustry() {
    //取消选择行业
    this.setData({
      isShowIndustry: false
    })
  },
  getTempleteList(id) {
    var _self = this
    _self.setData({
      templeteList: []
    })
    wx.showLoading({
      title: '加载中...',
    })
    app.http.get(app.urls.getTempleteList.format({
        industryId: id
      }), {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        res.data.forEach(it => {
          it.checked = false
        })
        res.data[0].checked = true
        _self.setData({
          templeteList: res.data,
          selTemplateId: res.data[0].shopTemplateConfigId
        })
        console.log(_self.data.templeteList)
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  PickerChange(e) {
    this.setData({
      index: e.detail.value
    })
  },
  // 商店注册
  RegisterShop() {
    if (this.checkParams()) {
      wx.showLoading({
        title: '注册中...'
      })
      let _self = this
      let industryIds = _self.data.selTradeId
      app.http.post(app.urls.doSaveShop, {
          header: {
            token: app.globalData.token
          },
          data: {
            shopName: _self.data.shopName,
            shopAddress: _self.data.shopAddress,
            shopSummary: _self.data.textareaBValue,
            openDate: _self.data.date,
            shopLogo: _self.data.shopLogoPhotos[0].id,
            industryIds: industryIds,
            shopTemplateId: _self.data.selTemplateId,
            isOpen: _self.data.isBusiness ? '1' : '0',
            shopVideo: _self.data.shopVideos.length > 0 ? _self.data.shopVideos[0].id : '',
            area: _self.data.area1Id,
            areaName: _self.data.area1,
            areaCity: _self.data.area2Id,
            areaCityName: _self.data.area2,
            areaCounty: _self.data.area3Id,
            areaCountyName: _self.data.area3,
          }
        })
        .then(res => {
          wx.hideLoading({})
          wx.showToast({
            title: '注册成功',
            icon: 'success',
            success(res) {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        })
        .catch(err => {
          wx.hideLoading({})
        })
    }
  },
  //选择模板样式
  choosetemplate(e) {
    this.setData({
      selTemplateId: e.detail.value
    })
  },
  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },

  checkIsBusiness(e) {
    this.setData({
      isBusiness: e.detail.value
    })
  },
  //选择营业执照
  ChooseLicenseP() {
    let _self = this
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        res.tempFilePaths.forEach(element => {
          _self.doUploadImg(1, element)
        });
      }
    });
  },
  //选择logo
  ChooseLogoP() {
    let _self = this
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        res.tempFilePaths.forEach(element => {
          _self.doUploadImg(2, element)
        });
      }
    });
  },
  //删除Logo
  DelLogoP(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除该图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.shopLogoPhotos.splice(e.currentTarget.dataset.index, 1)
          this.setData({
            shopLogoPhotos: this.data.shopLogoPhotos
          })
        }
      }
    })
  },
  //删除营业执照
  DelLicenseP(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除该图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.shopLicensePhotos.splice(e.currentTarget.dataset.index, 1)
          this.setData({
            shopLicensePhotos: this.data.shopLicensePhotos
          })
        }
      }
    })
  },
  //进行图片上传 type 1 营业执照   2 logo
  doUploadImg(type, path) {
    wx.showLoading({
      title: '上传中...',
    })
    let _self = this
    app.http.upload(app.urls.doUploadImg, {
        name: 'image',
        path: path,
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        var id = JSON.parse(res).data
        let pathStr = app.urls.baseImgUrl + id
        let item = {
          id: id,
          path: pathStr
        }
        if (type == 2) {
          //Logo
          let tempList = _self.data.shopLogoPhotos.concat(item)
          _self.setData({
            shopLogoPhotos: tempList
          })
        } else {
          //营业执照
          let tempList = _self.data.shopLicensePhotos.concat(item)
          _self.setData({
            shopLicensePhotos: tempList
          })
        }
      })
      .catch(err => {
        wx.hideLoading({})
        wx.showToast({
          title: '上传失败,请重试',
          icon: 'none'
        })
      })
  },
  inputWatch(e) {
    let key = e.currentTarget.dataset.model
    this.setData({
      [key]: e.detail.value
    })
  },
  ViewLogoImg(e) {
    var tempList = [e.currentTarget.dataset.url]
    wx.previewImage({
      urls: tempList,
      current: e.currentTarget.dataset.url
    });
  },
  ViewLicImg(e) {
    var tempList = [e.currentTarget.dataset.url]
    wx.previewImage({
      urls: tempList,
      current: e.currentTarget.dataset.url
    });
  },
  viewVideo(e) {
    var tempList = [{
      url: e.currentTarget.dataset.url,
      type: 'video'
    }]
    wx.previewMedia({
      sources: tempList,
      current: 0,
      showmenu: false
    })
  },
  delVideo(e) {
    let _self = this
    wx.showModal({
      title: '提示',
      content: '确定要删除该视频吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          _self.data.shopVideos.splice(e.currentTarget.dataset.index, 1)
          _self.setData({
            shopVideos: _self.data.shopVideos
          })
        }
      }
    })
  },
  textareaBInput(e) {
    this.setData({
      textareaBValue: e.detail.value
    })
  },
  checkParams() {
    var _self = this
    if (_self.data.shopName == '') {
      wx.showToast({
        title: '商店名称为必填项',
        icon: 'none'
      })
      return false
    }
    if (_self.data.area1Id == '') {
      wx.showToast({
        title: '请选择省份',
        icon: 'none'
      })
      return false
    }
    if (_self.data.area2Id == '') {
      wx.showToast({
        title: '请选择盟市',
        icon: 'none'
      })
      return false
    }
    if (_self.data.area3Id == '') {
      wx.showToast({
        title: '请选择旗县区',
        icon: 'none'
      })
      return false
    }
    if (_self.data.shopAddress == '') {
      wx.showToast({
        title: '店铺地址为必填项',
        icon: 'none'
      })
      return false
    }
    if (_self.data.selTradeId == 0) {
      wx.showToast({
        title: '请选择行业',
        icon: 'none'
      })
      return false
    }
    if (_self.data.date == '') {
      wx.showToast({
        title: '请选择开业时间',
        icon: 'none'
      })
      return false
    }
    if (_self.data.shopLogoPhotos.length <= 0) {
      wx.showToast({
        title: '请上传店铺Logo',
        icon: 'none'
      })
      return false
    }

    return true
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },


  getAreaDiction(id, type) {
    var _self = this
    wx.showLoading({
      title: '加载中...',
    })
    app.http.get(app.urls.getAreaDictionaryList.format({
        areaParentId: id
      }), {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        if (type == 1) {
          _self.setData({
            areaList: res.data
          })
        } else if (type == 2) {
          _self.setData({
            area2List: res.data
          })
        } else {
          _self.setData({
            area3List: res.data
          })
        }

      })
      .catch(err => {
        console.log(err)
      })
  },
  //选择视屏
  chooseVideo() {
    let _self = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'], //从相册选择
      maxDuration: 30,
      success: (res) => {
        _self.doUploadVideo(res)
      }
    });
  },
  doUploadVideo(e) {
    wx.showLoading({
      title: '上传中...',
    })
    let _self = this
    app.http.upload(app.urls.doUploadVideo, {
        name: 'video',
        path: e.tempFiles[0].tempFilePath,
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.hideLoading({})
        var id = JSON.parse(res).data
        let pathStr = e.tempFiles[0].thumbTempFilePath
        let videoU = app.urls.baseImgUrl + id
        let item = {
          id: id,
          path: pathStr,
          videoUrl: videoU
        }
        let tempList = _self.data.shopVideos.concat(item)
        _self.setData({
          shopVideos: tempList
        })
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  showTemplete(e) {
    var item = e.currentTarget.dataset.path
    var path = []
    path.push(item)
    wx.previewImage({
      urls: path,
    })
  },
  changeTemplete(e) {
    var _self = this
    var item = e.currentTarget.dataset.item
    _self.data.templeteList.forEach(it => {
      if (it.shopTemplateConfigId != item.shopTemplateConfigId) {
        it.checked = false
      } else {
        it.checked = true
      }
    })
    _self.setData({
      selTemplateId: item.shopTemplateConfigId,
      templeteList: _self.data.templeteList
    })
  },
  provinceChange(e) {
    var _self = this
    var index = e.detail.value
    var item = _self.data.areaList[index]
    _self.setData({
      area1: item.areaName,
      area1Id: item.areaId,
      area2Id: '',
      area2: '请选择盟市',
      area3Id: '',
      area3: '请选择旗县区',
      area3List: []
    })
    _self.getAreaDiction(_self.data.area1Id, 2)
  },
  cityChange(e) {
    var _self = this
    var index = e.detail.value
    var item = _self.data.area2List[index]
    _self.setData({
      area2: item.areaName,
      area2Id: item.areaId,
      area3Id: '',
      area3: '请选择旗县区'
    })
    _self.getAreaDiction(_self.data.area2Id, 3)
  },
  districtChange(e) {
    var _self = this
    var index = e.detail.value
    var item = _self.data.area3List[index]
    _self.setData({
      area3: item.areaName,
      area3Id: item.areaId
    })
  }
})