<template>
  <view class="page-wrapper global-wrapper bgF2">
    <JHeaderTitle :title="storeInfo.storeId ? '编辑门店信息' : '创建门店'" bgColor="#f2f2f2" />
    <JMainCard pd="0" wrapPd="30rpx" v-if="!storeInfo.storeId">
      <view class="select-wrapper" @tap="jumpPage('mch')">
        <view class="select-mch" v-if="mchInfo.mchNo == undefined"> 请选择商户 </view>
        <view class="mch-info" v-else>
          <image src="/static/equipmentImg/mch-list.svg" mode="scaleToFill" />
          <view
            >{{ mchInfo.mchName }} <text>{{ mchInfo.mchNo }}</text>
          </view>
        </view>
        <image src="/static/iconImg/right-arrow.svg" mode="scaleToFill" />
      </view>
    </JMainCard>
    <JMainCard wrapPd=" 0 30rpx" pd="0">
      <JInput
        v-model:value="storeInfo.storeName"
        name="门店名称"
        place="请输入门店名称"
        :rules="{ name: 'storeName', rule: 'REG_NotNUll' }"
        :isBorder="true"
      ></JInput>
      <JInput v-model:value="storeInfo.contactPhone" name="联系人手机号" place="请输入联系人手机号"></JInput>
    </JMainCard>
    <JMainCard pd="0" wrapPd="30rpx">
      <JUpLoad name="门店logo" v-model:value="storeInfo.storeLogo" borderNone />
      <JUpLoad name="门头照" v-model:value="storeInfo.storeOuterImg" />
      <JUpLoad name="门店内景照" v-model:value="storeInfo.storeInnerImg" />
    </JMainCard>
    <JMainCard wrapPd=" 0 30rpx" pd="0">
      <JInput name="门店地址" :isBorder="true">
        <view @tap="getAddress" class="place-text address" v-if="!storeInfo.address"
          >请选择位置 <view class="gps-img"> <image src="/static/iconImg/icon-gps.svg" mode="scaleToFill" /></view
        ></view>
        <view @tap="getAddress" v-else class="place-text address" style="color: #000"
          >{{ storeInfo.address }}
          <view class="gps-img"> <image src="/static/iconImg/icon-gps.svg" mode="scaleToFill" /></view>
        </view>
      </JInput>
    </JMainCard>
    <JMainCard pd="0" wrapPd="30rpx">
      <JInput name="省市区">
        <uni-data-picker
          :localdata="address"
          @change="dataPickerChange($event, 'areaCode')"
          v-slot:default="{ data, error, options }"
        >
          <view class="place-text" v-if="storeInfo.areaCode.length == 0"
            >请选择省市区
            <image src="/static/iconImg/icon-right-jiantou.svg" mode="scaleToFill" />
          </view>
          <view v-else style="font-size: 33rpx">{{ storeInfo.addressInfo || "请选择省市区" }}</view>
        </uni-data-picker>
      </JInput>
      <JInput name="经纬度">
        <view class="place-text" v-if="!storeInfo.lng">选择位置后自动生成</view>
        <view style="font-size: 33rpx" v-else>{{ storeInfo.lng }},{{ storeInfo.lat }}</view>
      </JInput>
    </JMainCard>
    <JButton pd="0 30rpx 50rpx" pdTop="0" @HandleTouch="saveStore">{{
      storeInfo.storeId ? "保存" : "创建门店"
    }}</JButton>
  </view>
</template>

<script setup>
import { ref } from "vue"
import { onShow, onLoad } from "@dcloudio/uni-app"
import { $addMchStore, $updateMchStore, $storeDetails, $mapKey } from "@/http/apiManager.js"
import tool from "@/util/tool.js" // 工具类函数
import JHeaderTitle from "@/components/newComponents/JHeaderTitle/JHeaderTitle.vue" //自定义导航栏
import JInput from "@/components/newComponents/JInput/JInput.vue"
import JButton from "@/components/newComponents/JButton/JButton.vue" //自定义按钮
import JMainCard from "@/components/newComponents/JMainCard/JMainCard.vue"
import JUpLoad from "@/components/newComponents/JUpLoad/JUpLoad.vue"
import address from "@/components/applyJson/address.json" // 地址
import { getMapKey } from "@/hooks/mapInfo.js"
import useStore from "@/hooks/useStore.js"
import { validateArray } from "@/hooks/rules"
const { getStore, clearItem } = useStore()
onLoad((options) => {
  if (options.id) return getStoreInf(options.id)
})
onShow(() => {
  if (getStore("mch")?.mchNo) {
    mchInfo.value = getStore("mch")
    storeInfo.value.mchNo = getStore("mch").mchNo
    clearItem("mch")
  }
})
const title = ref("创建门店")
const mchInfo = ref({})
const storeInfo = ref({
  state: 1,
  areaCode: [],
  addressInfo: "", //只做数据回显使用非必传值
})
const switchState = (e, v) => {
  agentInfo[v] = e.detail.value ? 1 : 0
}
const dataPickerChange = (e, name) => {
  storeInfo.value.addressInfo = ""
  storeInfo.value.areaCode = []
  e.detail.value.forEach((v, i) => {
    storeInfo.value.areaCode.push(v.value)
    storeInfo.value.addressInfo += i == e.detail.value.length - 1 ? v.text : v.text + "/"
  })
  const address = storeInfo.value.addressInfo.split("/").join("")
  getMapKey(address, 1).then((res) => {
    storeInfo.value.lng = parseFloat(res.lon).toFixed(6)
    storeInfo.value.lat = parseFloat(res.lat).toFixed(6)
    storeInfo.value.address = address
  })
}
function getAddress() {
  uni.chooseLocation({
    latitude: storeInfo.value.lat || undefined,
    longitude: storeInfo.value.lng || undefined,
    success: (res) => {
      storeInfo.value.lng = res.longitude.toFixed(6)
      storeInfo.value.lat = res.latitude.toFixed(6)
      storeInfo.value.location = res.longitude + "/" + res.latitude
      storeInfo.value.address = res.address
      getMapKey(res.address, 0).then((res) => {
        storeInfo.value.addressInfo = res.text
        storeInfo.value.areaCode = res.code
      })
    },
    fail: (err) => {
      console.log(err, "error")
    },
  })
}

const saveStore = () => {
  if (validateArray(storeInfo.value)) {
    if (!storeInfo.value.addressInfo) {
      uni.showToast({ title: "请选省市区", icon: "error" })
      return
    } else {
      if (!storeInfo.value.storeId) {
        $addMchStore(storeInfo.value).then(() => {
          uni.showToast({
            title: "新增成功",
          })
          uni.navigateBack()
        })
      } else {
        $updateMchStore(storeInfo.value.storeId, storeInfo.value).then(() => {
          uni.showToast({
            title: "修改成功",
          })
          uni.navigateBack()
        })
      }
    }
  }
}
// 请求门店详情
const getStoreInf = (val) => {
  $storeDetails(val).then(({ bizData }) => {
    storeInfo.value = bizData
    storeInfo.value.addressInfo = tool.addressBack(storeInfo.value.areaCode, address)
  })
}
// 跳转到通用选择页面
const jumpPage = (val) => {
  uni.navigateTo({
    url: `/pageWork/SelectedList/SelectedList?title=${val}&selected=${storeInfo.value.mchNo}`,
  })
}
</script>

<style lang="scss" scoped>
.page-wrapper {
  .select-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    .select-mch {
      margin: 20rpx;
    }
    .mch-info {
      display: flex;
      image {
        width: 93rpx;
        height: 93rpx;
        margin-right: 10rpx;
      }
      view {
        display: flex;
        flex-direction: column;
        font-size: 33rpx;
        font-weight: 700;
        text {
          margin-top: 15rpx;
          color: #8c8c8c;
          font-size: 25rpx;
          font-weight: 500;
        }
      }
    }
    image {
      width: 40rpx;
      height: 40rpx;
    }
    .img-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      width: 93rpx;
      height: 93rpx;
      margin-right: 20rpx;
      image {
        width: 60rpx;
        height: 66rpx;
      }
    }
  }
  .place-text {
    font-size: 33rpx;
    color: #a6a6a6;
    image {
      width: 40rpx;
      height: 40rpx;
    }
  }
}
.address {
  align-self: flex-start;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .gps-img {
    align-self: flex-start;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50rpx;
    height: 100%;
  }
}
</style>
