<template>
  <view class="page-shop-adminsistration">
    <form class="msg-box">
      <view class="msg-tit">
        <view class="shop-icon">
          <image src="/static/images/icon/shop-icon.png" />
        </view>
        <view class="shop-msg-tit">
          店铺管理
        </view>
      </view>
      <!-- 自提点名称 -->
      <view class="msg-cont-box">
        <label class="cont-txt">门店名称</label>
        <input
          type="text"
          class="cont-int"
          :value="stationName"
          maxlength="50"
          placeholder="输入自提点名称"
          @input="onBindStationNameInt"
        >
      </view>
      <!-- 自提点图片 -->
      <view class="msg-cont-box">
        <label class="cont-txt">门店图片</label>
        <!-- 上传文件 -->
        <view class="upload-files align-top">
          <!-- 预览图片 -->
          <view
            v-if="logoImg.path"
            class="preview-img-box preview-logo"
          >
            <image
              class="preview-img"
              :src="logoImg.url"
              mode="aspectFill"
            />
            <!-- 删除 -->
            <image
              class="preview-img-del"
              data-type="logoImg"
              src="/static/images/icon/close2.png"
              @tap="onRemoveImage"
            />
          </view>
          <!-- 上传 -->
          <view
            v-if="!logoImg.path "
            class="upload-icon upload-logo"
            data-type="logoImg"
            @tap="onGetUploadImg"
          >
            +
          </view>
        </view>
        <!-- 上传文件end -->
      </view>
      <!-- /自提点图片 -->
      <!-- 状态 -->
      <view class="msg-cont-box">
        <label class="cont-txt">状态</label>
        <radio-group class="station-status">
          <label class="radio">
            <radio
              :checked="stationStatus===1"
              color="#e43130"
              @tap="onStatusChange(1)"
            />营业
          </label>
          <label class="radio right-radio">
            <radio
              :checked="stationStatus===0"
              color="#e43130"
              @tap="onStatusChange(0)"
            />关闭
          </label>
        </radio-group>
      </view>
      <!-- 电话号码 -->
      <view class="msg-cont-box">
        <label class="cont-txt">电话号码</label>
        <input
          type="number"
          placeholder="区号"
          :value="stationOwnerAreaCode"
          class="cont-left"
          maxlength="5"
          @input="onBindStationOwnerAreaCodeInt"
        >
        <view class="num-line" />
        <input
          type="number"
          placeholder="电话/手机号码"
          :value="stationOwnerPhoneValue"
          class="cont-right"
          maxlength="11"
          @input="onBindStationOwnerPhoneInt"
        >
      </view>
      <!-- 营业时间 -->
      <view class="msg-cont-box">
        <label class="cont-txt">营业时间</label>
        <view class="picker-section">
          <picker
            mode="time"
            :value="stationStartTime"
            @change="onBindStartTimeChange"
          >
            <view class="picker">
              开始<text class="station-time">
                {{ tsDate(stationStartTime) }}
              </text>
            </view>
          </picker>
        </view>
        <view class="picker-section">
          <picker
            mode="time"
            :start="stationStartTime"
            @change="onBindEndTimeChange"
          >
            <view class="picker">
              结束<text class="station-time">
                {{ tsDate(stationEndTime) }}
              </text>
            </view>
          </picker>
        </view>
      </view>
      <!-- 店铺地址 -->
      <view
        class="msg-cont-box addr"
        @tap="translate"
      >
        <label class="cont-txt">所在地区</label>
        <!-- 展示 -->
        <view class="pca">
          {{ province }} {{ city }} {{ area }}
        </view>
        <view class="arrow">
          <area-picker
            v-model:show-picker="showPicker"
            v-model:value="addressValue"
            :class-list="['areaPicker']"
            @change="addressChange"
          />
        </view>
      </view>
      <!-- 详细地址 -->
      <view class="msg-cont-box">
        <label class="cont-txt">详细地址</label>
        <input
          type="text"
          :value="stationAddrValue"
          class="cont-int"
          placeholder="填写详细地址"
          @input="onBindStationAddrInt"
        >
      </view>
      <!-- 经纬度(调用微信地图获取) -->
      <view class="msg-cont-box wx-map clearfix">
        <view class="cont-txt">
          地理位置
        </view>
        <view
          v-if="latitude"
          class="show-location"
        >
          <view>{{ '纬度：' + latitude }}</view>
          <view>{{ '经度：' + longitude }}</view>
        </view>
        <view
          class="map"
          @tap="onChooseLocation"
        >
          点击获取位置
        </view>
      </view>
    </form>
    <!-- 提交申请 -->
    <view class="apply-btn">
      <view
        class="btn"
        @tap="onSubmitApply"
      >
        提交修改
      </view>
    </view>
  </view>
</template>
<script setup>
import AreaPicker from '@/components/area-picker/area-picker.vue'
import util from '@/utils/util.js'
const tsDate = (value) => {
  if (value) {
    try {
      value = value.split(':')
      value.pop()
      return value.join(':')
    } catch {
      return value
    }
  }
  return value
}
let t = 0
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL
let stationId = 0 // 自提点Id
const stationStatus = ref(1) // 自提点状态  0:关闭 1:营业
const stationName = ref('') // 自提点名称
const logoImg = ref({}) // 自提点logo
const stationOwnerAreaCode = ref('') // 电话区号
const stationOwnerPhoneValue = ref('') // 电话/手机号码
const stationStartTime = ref('') // 开始营业时间
const stationEndTime = ref('') // 打烊的时间
const provinceId = ref(0)
let cityId = 0
let areaId = 0
const province = ref('')
const city = ref('')
const area = ref('')
const stationAddrValue = ref('') // 详细地址
const latitude = ref('') // 经度
const longitude = ref('') // 纬度
const animation = ref('')
let tempFiles = null
let type = ''
const addressChange = (address) => {
  province.value = address[0].areaName
  city.value = address[1].areaName
  area.value = address[2].areaName
  provinceId.value = address[0].areaId
  cityId = address[1].areaId
  areaId = address[2].areaId
}
/**
 * 生命周期函数--监听页面加载
 */
onLoad(async (options) => {
  await onGetStationInfo(options)// 获取自提点信息
})
/**
   * 生命周期函数--监听页面初次渲染完成
   */
onReady(() => {
  // 底部弹框动画
  animation.value = uni.createAnimation({
    transformOrigin: '50% 50%',
    duration: 0,
    timingFunction: 'ease',
    delay: 0
  })
  animation.value.translateY(200 + 'vh').step()
  animation.value = animation.value.export()
})
/* 自提点信息 */
const onGetStationInfo = (options) => {
  uni.showLoading()
  http.request({
    url: '/mall4cloud_order/station',
    method: 'GET',
    data: {}
  }).then(async ({ data }) => {
    const timeDate = JSON.parse(data.timeInfo)
    stationId = data.stationId
    stationName.value = data.stationName || ''
    logoImg.value.url = import.meta.env.VITE_APP_RESOURCES_URL + data.imgUrl
    logoImg.value.path = data.imgUrl
    stationStatus.value = data.status
    stationOwnerAreaCode.value = data.mobilePrefix
    stationOwnerPhoneValue.value = data.mobile || ''
    stationStartTime.value = util.formatTime(timeDate.shopTime[0]).split(' ')[1]// 切割返回的营业时间
    stationEndTime.value = util.formatTime(timeDate.shopTime[1]).split(' ')[1]// 切割返回的打烊时间
    provinceId.value = data.provinceId
    cityId = data.cityId
    areaId = data.areaId
    province.value = data.province
    city.value = data.city
    area.value = data.area
    stationAddrValue.value = data.addr || ''
    latitude.value = data.lat
    longitude.value = data.lng
    uni.hideLoading()
    addressValue.value = [data.provinceId, data.cityId, data.areaId]
    if (options.module && uni.getStorageSync('cloudSetStationLocationFlag')) {
      afterLoc(options)
    }
  })
}
/**
 * 获取到定位后的回调
 * loc 定位信息
 */
const afterLoc = (loc) => {
  if (loc && loc.module === 'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
    stationAddrValue.value = loc.addr
    latitude.value = loc.latng.split(',')[0]
    longitude.value = loc.latng.split(',')[1]
    util.area(loc.addr, loc.name).then(res => {
      if (!res) return
      const addrReplacrstr = res[0].name + res[1].name + res[2].name
      stationAddrValue.value = stationAddrValue.value.replace(addrReplacrstr, '') || loc.poiname
      province.value = res[0].name
      city.value = res[1].name
      area.value = res[2].name
      provinceId.value = res[0].areaId
      cityId = res[1].areaId
      areaId = res[2].areaId
    })
    uni.setStorageSync('cloudSetStationLocationFlag', false)
  }
}
/* 改变自提点状态 */
const onStatusChange = (v) => {
  stationStatus.value = v
}
/**
 * 请求接口传数据
 */
const onSubmitApply = () => {
  if (stationName.value.trim().length < 2) {
    wx.showToast({
      title: '请输入至少两位数字字母汉字组成的自提点名称',
      icon: 'none'
    })
  } else if (stationOwnerPhoneValue.value.trim().length === 0) {
    wx.showToast({
      title: '请输入电话号码',
      icon: 'none'
    })
  } else if (!stationStartTime.value || !stationEndTime.value) {
    wx.showToast({
      title: '请选择营业时间',
      icon: 'none'
    })
  } else if (stationStartTime.value === stationEndTime.value) {
    uni.showToast({
      title: '开始时间不能等于结束时间',
      icon: 'none'
    })
  } else if (!province.value && !city.value && !area.value) {
    wx.showToast({
      title: '请选择所在地区',
      icon: 'none'
    })
  } else if (stationAddrValue.value.trim().length < 2) {
    wx.showToast({
      title: '请输入正确的详细地址：不得少于2字',
      icon: 'none'
    })
  } else if (latitude.value === '' && longitude.value === '') {
    wx.showToast({
      title: '请选择地理位置',
      icon: 'none'
    })
  } else {
    let timeDate = {}
    timeDate.shopTime = []
    // 获取当前时间的年月日
    const date = new Date()
    const fragTime = util.formatTime(date.getTime()).split(' ')[0]
    timeDate.shopTime[0] = util.dateToTimestamp(fragTime + ' ' + stationStartTime.value)
    timeDate.shopTime[1] = util.dateToTimestamp(fragTime + ' ' + stationEndTime.value)
    timeDate = JSON.stringify(timeDate)
    uni.showLoading()
    http.request({
      url: '/mall4cloud_order/station',
      method: 'PUT',
      data: {
        stationId,
        stationName: stationName.value,
        imgUrl: logoImg.value.path || '',
        status: stationStatus.value,
        mobilePrefix: stationOwnerAreaCode.value,
        mobile: stationOwnerPhoneValue.value,
        timeInfo: timeDate,
        provinceId: provinceId.value,
        cityId,
        areaId,
        province: province.value,
        city: city.value,
        area: area.value,
        addr: stationAddrValue.value,
        lat: latitude.value,
        lng: longitude.value
      }
    }).then(() => {
      uni.hideLoading()
      uni.showToast({
        title: '修改成功',
        icon: 'success'
      })
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/index/index'
        })
      }, 1500)
    })
  }
}
/**
 * 获取经纬度
 */
const key = import.meta.env.VITE_APP_MAP_KEY
const onChooseLocation = () => {
  uni.setStorageSync('cloudSetStationLocationFlag', true)
  window.location.replace(`https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=${location.href}&key=${key}&referer=myapp`)
}
/**
  * 获取input数据
  */
// 获取自提点名称
const onBindStationNameInt = (e) => {
  stationName.value = e.detail.value
}
// 获取区号
const onBindStationOwnerAreaCodeInt = (e) => {
  stationOwnerAreaCode.value = e.detail.value
}
// 获取电话/手机号码
const onBindStationOwnerPhoneInt = (e) => {
  stationOwnerPhoneValue.value = e.detail.value
}
// 获取营业开始时间
const onBindStartTimeChange = (e) => {
  stationStartTime.value = e.detail.value + ':00'
  stationEndTime.value = ''
}
// 获取营业结束时间
const onBindEndTimeChange = (e) => {
  stationEndTime.value = e.detail.value + ':00'
}
// 详细地址
const onBindStationAddrInt = (e) => {
  stationAddrValue.value = e.detail.value
}
/**
 * 上传图片
 */
let ossList = []
const onGetUploadImg = (e) => {
  type = e.target.dataset.type
  wx.chooseImage({
    count: 1, // 默认9
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: function (res) {
      // 图片的本地临时文件路径列表
      tempFiles = res.tempFiles
      uni.showLoading({
        mask: true
      })
      const fileNames = tempFiles?.map(item => item.name).join(',')
      http.request({
        url: '/mall4cloud_biz/ua/oss/get_batch_pre_sign_url',
        method: 'GET',
        data: {
          fileNames // 需要获取token的文件名
        }
      }).then(({ data }) => {
        uni.hideLoading()
        ossList = data
        onConfirmUpload()
      })
    }
  })
}
const onUploadSuccess = (filePath) => {
  const img = {}
  img.path = filePath
  img.url = resourcesUrl + filePath
  if (type === 'logoImg') {
    logoImg.value = img
  }
}
/**
 * 确认上传
 */
const onConfirmUpload = () => {
  if (ossList.length <= 0) {
    // message('数据异常，请刷新后重试')
    uni.showToast({
      title: '数据异常，请刷新后重试',
      icon: 'error',
      duration: 2000
    })
  }

  // 文件上传
  util.awsUpload(ossList, tempFiles).then(() => {
    const filePath = '/' + ossList[0].dir + ossList[0].fileName
    onUploadSuccess(filePath)
  })
}

/**
 * 删除图片
 */
const onRemoveImage = (e) => {
  const type = e.target.dataset.type
  if (type === 'logoImg') {
    logoImg.value = {}
  }
}
/**
 * 移动按钮点击事件
 */
const translate = () => {
  if (t === 0) {
    t = 1
  } else {
    t = 0
  }
  showPicker.value = true
}
const addressValue = ref([])
const showPicker = ref(false)
onHide(() => {
  showPicker.value = false
})
</script>
<style lang="scss" scoped>
@import "./shop-adminsistration.scss";
</style>
