<!--
Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

https://www.mall4j.com/

未经允许，不可做商业用途！

版权所有，侵权必究！
-->

<template>
  <!-- 基本设置 -->
  <view class="Mall4j page-store-settings-basic">
    <uni-forms
      ref="baseInfoFormRef"
      :model-value="baseInfoForm"
      :rules="rules"
      validate-trigger="submit"
    >
      <view class="setting-info-item">
        <uni-forms-item name="merchantName">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              {{ $t('shangJiaMingCheng') }}
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="baseInfoForm.merchantName"
              :placeholder="$t('qingShuRuShangJiaMingCheng')"
              maxlength="10"
              @blur="checkInput('merchantName')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item">
        <uni-forms-item name="shopName">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              {{ $t('dianPuMingCheng') }}
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="baseInfoForm.shopName"
              :placeholder="$t('qingShuRuDianPuMingCheng')"
              maxlength="20"
              @blur="checkInput('shopName')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item">
        <uni-forms-item name="tel">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              {{ $t('lianXiFangShi') }}
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="baseInfoForm.tel"
              :placeholder="$t('qingShuRuLianXiFangShi')"
              maxlength="11"
              @blur="checkInput('tel')"
            />
          </view>
        </uni-forms-item>
      </view>
      <!-- 店铺简介 -->
      <view class="setting-info-item">
        <uni-forms-item name="intro">
          <view class="title">
            <text class="txt">
              {{ $t('dianPuJianJie') }}
            </text>
          </view>
          <view class="textarea-box">
            <textarea
              v-model="baseInfoForm.intro"
              :placeholder="$t('qingShuRuDianPuJianJie')"
              maxlength="200"
              @blur="checkInput('intro')"
            />
          </view>
        </uni-forms-item>
      </view>
      <!-- 店铺logo -->
      <view class="setting-info-item">
        <uni-forms-item name="shopLogo">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              {{ $t('dianPuLogo') }}
            </text>
          </view>
          <view class="upload-image">
            <view class="upload-con">
              <view
                v-if="!baseInfoForm.shopLogo"
                class="upload-btn"
                @tap="uploadImg"
              >
                <view class="up-text text-btn">
                  {{ $t('tianJia-1') }}
                </view>
                <view class="up-text">
                  {{ $t('shangChuanQingXiZhaoPian') }}
                </view>
              </view>
              <view
                v-if="baseInfoForm.shopLogo"
                class="upload-con"
                @tap.stop="previewImg(baseInfoForm.shopLogo)"
              >
                <image
                  :src="util.checkFileUrl(baseInfoForm.shopLogo)"
                  mode="aspectFill"
                  class="up-img-con"
                />
                <view
                  class="del-btn"
                  @click.stop="delLoadImg('shopLogo')"
                />
              </view>
            </view>
          </view>
        </uni-forms-item>
      </view>

      <view
        v-if="util.isAuthorities('shop:shopDetail:save') && (baseInfoForm.shopStatus !== 5)"
        class="footer"
      >
        <button
          type="default"
          class="button"
          hover-class="none"
          @tap="submit"
        >
          {{ $t('baoCun') }}
        </button>
      </view>
    </uni-forms>
  </view>
</template>

<!-- eslint-disable n/no-callback-literal -->
<script setup>
import util from '@/utils/util'

const Data = reactive({
  // 基本信息
  baseInfoForm: {
    merchantName: '',
    shopName: '',
    tel: '',
    email: '',
    province: '',
    provinceId: '',
    city: '',
    cityId: '',
    area: '',
    areaId: '',
    currentAddr: '',
    shopAddress: '',
    shopLogo: '',
    intro: '',
    // 纬度
    shopLat: '',
    // 经度
    shopLng: ''
  },
  rules: {
    // 对表单字段进行必填验证
    merchantName: {
      rules: [
        { required: true, errorMessage: $t('qingShuRuShangJiaMingCheng-0') },
        { minLength: 2, maxLength: 10, errorMessage: $t('shangJiaMingChengChangDuZai_210GeZiFuZhiJian') }
      ]
    },
    shopName: {
      rules: [
        { required: true, errorMessage: $t('qingShuRuDianPuMingCheng-0') },
        { minLength: 2, maxLength: 20, errorMessage: $t('qingShuRu_220ZiYiNeiDeDianPuMingCheng') }
      ]
    },
    tel: {
      rules: [
        { required: true, errorMessage: $t('qingShuRuLianXiFangShi-0') },
        {
          validateFunction: (rule, value, data, callback) => {
            const reg = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
            if (!reg.test(value)) {
              callback($t('qingShuRuZhengQueDeLianXiFangShi'))
              return false
            }
          }
        }
      ]
    },
    shopLogo: {
      rules: [
        { required: true, errorMessage: $t('qingShangChuanDianPuLogo') },
        {
          validateFunction: (rule, value, data, callback) => {
            // console.log(Data.baseInfoForm.shopLogo.trim())
            if (Data.baseInfoForm.shopLogo.trim().length === 0) {
              callback($t('qingShangChuanDianPuLogo-0'))
              return false
            }
          }
        }
      ]
    }
  },
  areaList: [], // 全部地区

  addressShow: false
})

const { baseInfoForm, rules } = toRefs(Data)

const baseInfoFormRef = ref()

onLoad(() => {
  getShopDetailnfo()
  getAreaList()
})

onShow(() => {
  if (uni.getStorageSync('bbcLocInfo')) {
    const loc = uni.getStorageSync('bbcLocInfo')
    const shopAddress = setAddress(loc.poiaddress)
    Data.baseInfoForm.shopAddress = shopAddress
    Data.baseInfoForm.shopLat = loc.latlng.lat
    Data.baseInfoForm.shopLng = loc.latlng.lng
    uni.removeStorageSync('bbcLocInfo')
  }
  uni.setNavigationBarTitle({
    title: $t('jiBenXinXi')
  })
})

onReady(() => {
  // 需要在onReady中设置规则
  baseInfoFormRef.value.setRules(Data.rules)
})

// 获取全部地区数据
const getAreaList = () => {
  http.request({
    url: '/admin/area/listAreaOfEnable',
    method: 'GET'
  }).then(({ data }) => {
    Data.areaList = data
  })
}

/**
* 上传图片
*/
const uploadImg = () => {
  util.chooseImage({}).then((data) => {
    // 店铺logo
    Data.baseInfoForm.shopLogo = data[0].filePath
  })
}

/**
* 删除图片
*
*/
const delLoadImg = (type) => {
  Data.baseInfoForm[type] = ''
}

// 详细地址反显
const setAddress = (address) => {
  if (!Data.areaList.length) return address

  let poiaddress = address.toString()
  const data = {
    province: '', // 省
    provinceId: '', // 省id
    city: '', // 市
    cityId: '', // 市id
    area: '', // 区
    areaId: '' // 区id
  }
  for (let i = 0; i < Data.areaList.length; i++) {
    if (poiaddress.indexOf(Data.areaList[i].areaName) === 0) {
      data.province = Data.areaList[i].areaName
      data.provinceId = Data.areaList[i].areaId
      poiaddress = poiaddress.replace(Data.areaList[i].areaName, '')
      for (let x = 0; x < Data.areaList[i].areas.length; x++) {
        let isGetCity = false
        if (poiaddress.indexOf(Data.areaList[i].areas[x].areaName) === 0) {
          data.city = Data.areaList[i].areas[x].areaName
          data.cityId = Data.areaList[i].areas[x].areaId
          poiaddress = poiaddress.replace(Data.areaList[i].areas[x].areaName, '')
          isGetCity = true
        }
        // 如果市级只有一个，直接选中
        if (Data.areaList[i].areas.length === 1) {
          data.city = Data.areaList[i].areas[x].areaName
          data.cityId = Data.areaList[i].areas[x].areaId
          poiaddress = poiaddress.replace(Data.areaList[i].areas[x].areaName, '')
          isGetCity = true
        }
        if (isGetCity) {
          for (let y = 0; y < Data.areaList[i].areas[x].areas.length; y++) {
            // eslint-disable-next-line max-depth
            if (poiaddress.indexOf(Data.areaList[i].areas[x].areas[y].areaName) === 0) {
              data.area = Data.areaList[i].areas[x].areas[y].areaName
              data.areaId = Data.areaList[i].areas[x].areas[y].areaId
              poiaddress = poiaddress.replace(Data.areaList[i].areas[x].areas[y].areaName, '')
              break
            }
          }
          break
        }
      }
      break
    }
  }
  if (data.provinceId && data.cityId && data.areaId) {
    Data.baseInfoForm.currentAddr = `${data.province} ${data.city} ${data.area}`
    Data.baseInfoForm = { ...Data.baseInfoForm, ...data }
    address = poiaddress
  }
  return address
}

/**
* 输入框空格校验
*/
const checkInput = (type) => {
  const reg = /^\s+$/g
  if (type === 'merchantName' && reg.test(Data.baseInfoForm.merchantName)) {
    Data.baseInfoForm.merchantName = ''
  }
  if (type === 'shopName' && reg.test(Data.baseInfoForm.shopName)) {
    Data.baseInfoForm.shopName = ''
  }
  if (type === 'tel' && reg.test(Data.baseInfoForm.tel)) {
    Data.baseInfoForm.tel = ''
  }
  if (type === 'email' && reg.test(Data.baseInfoForm.email)) {
    Data.baseInfoForm.email = ''
  }
  if (type === 'shopAddress' && reg.test(Data.baseInfoForm.shopAddress)) {
    Data.baseInfoForm.shopAddress = ''
  }
  if (type === 'intro' && reg.test(Data.baseInfoForm.intro)) {
    Data.baseInfoForm.intro = ''
  }
}

/**
* 提交表单
*/
const submit = () => {
  baseInfoFormRef.value.validate().then(() => {
    putShopDetail()
  })
}

/**
* 获取店铺信息
*/
const getShopDetailnfo = () => {
  http.request({
    url: '/shop/shopDetail/info',
    method: 'GET'
  }).then(({ data: res }) => {
    Data.baseInfoForm = res
    if (res.province && res.city && res.area) {
      Data.baseInfoForm.currentAddr = `${res.province} ${res.city} ${res.area}`
    }
  })
}

/**
* 修改店铺基本信息
*/
const putShopDetail = () => {
  const data = JSON.parse(JSON.stringify(Data.baseInfoForm))
  delete data.currentAddr
  http.request({
    url: '/shop/shopDetail',
    method: 'PUT',
    data
  }).then(() => {
    uni.showToast({
      title: $t('xiuGaiChengGong-0')
    })
  })
}

// 图片预览hooks
const { previewImg } = usePreviewImg()
</script>

<style lang="scss" scoped>
@use "store-settings-basic";
</style>
