<template>
  <view class="page-wrapper global-wrapper bgF2">
    <JHeaderTitle :title="createInfo.trmId ? '修改辅助终端' : '创建辅助终端'" bgColor="#f2f2f2" />
    <JMainCard pd="0" :wrapPd="createInfo.trmType == 2 ? '30rpx' : '0 30rpx'">
      <JInput name="终端类型">
        <view class="tips" :class="{ selected: typeInfo.name }" @tap="sType.open(typeInfo.i)"
          >{{ typeInfo.name || "请选择终端类型" }}
          <image src="/static/iconImg/icon-right-jiantou.svg" mode="scaleToFill" />
        </view>
      </JInput>
    </JMainCard>
    <JMainCard wrapPd="0 30rpx" pd="0" v-if="createInfo.trmType == 2">
      <view
        class="select-wrapper"
        @tap="
          jumpPage('POS', posInfo.deviceId, {
            deviceType: 3,
            mchNo: information.mchNo,
            storeId: information.storeId,
            appId: information.appId,
          })
        "
      >
        <view class="select-mch" v-if="!posInfo.appId"> 请选择扫码POS </view>
        <view class="mch-info" v-else>
          <image src="/static/equipmentImg/pos-open.svg" mode="scaleToFill" />
          <view
            >{{ posInfo.deviceName }} <text>{{ posInfo.deviceNo }}</text>
          </view>
        </view>
        <image src="/static/iconImg/right-arrow.svg" mode="scaleToFill" />
      </view>
    </JMainCard>
    <JMainCard pd="0" wrapPd="30rpx" v-if="createInfo.trmType">
      <JInput
        name="设备名称"
        place="请输入设备名称"
        v-model:value="createInfo.trmName"
        :isBorder="true"
        :rules="{ name: 'trmName', rule: 'REG_NotNUll' }"
      ></JInput>
      <JInput
        name="设备号"
        v-if="createInfo.trmType == 1"
        v-model:value="createInfo.trmNo"
        place="请输入设备号"
        :rules="{ name: 'trmNo', rule: 'REG_NotNUll' }"
      ></JInput>
      <JInput name="是否门店默认" v-if="!createInfo.trmId">
        <view class="state-text">
          {{ createInfo.defaultFlag == 1 ? "是" : "否" }}
          <switch
            :checked="createInfo.defaultFlag == 1 ? true : false"
            style="margin-left: 20rpx; transform: scale(1.2)"
            color="#7737fe"
            @change="change($event, 'defaultFlag')"
          />
        </view>
      </JInput>
      <JInput name="设备状态">
        <view class="state-text">
          {{ createInfo.state == 1 ? "启用" : "禁用" }}
          <switch
            :checked="createInfo.state == 1 ? true : false"
            style="margin-left: 20rpx; transform: scale(1.2)"
            color="#7737fe"
            @change="change($event, 'state')"
          />
        </view>
      </JInput>
    </JMainCard>
    <JMainCard wrapPd=" 0 30rpx" pd=" 0" v-if="createInfo.trmType">
      <JInput name="布放位置" :isBorder="true" :rules="{ name: 'detailAddress', rule: 'REG_NotNUll' }">
        <view @tap="getAddress" class="place-text address" v-if="!createInfo.detailAddress"
          >请选择位置 <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"
          >{{ createInfo.detailAddress }}
          <view class="gps-img"> <image src="/static/iconImg/icon-gps.svg" mode="scaleToFill" /></view>
        </view>
      </JInput>
    </JMainCard>
    <JMainCard pd="0" wrapPd="30rpx" v-if="createInfo.trmType">
      <JInput name="省市区" :isBorder="true">
        <uni-data-picker
          :localdata="address"
          @change="dataPickerChange($event, 'areaCode')"
          v-slot:default="{ data, error, options }"
        >
          <view class="place-text" v-if="createInfo.areaCode?.length == 0"
            >请选择省市区
            <image src="/static/iconImg/icon-right-jiantou.svg" mode="scaleToFill" />
          </view>
          <view v-else style="font-size: 33rpx">{{ createInfo.addressInfo }}</view>
        </uni-data-picker>
      </JInput>
      <JInput name="经纬度" v-if="createInfo.trmType">
        <view class="place-text" v-if="!createInfo.lng">选择位置后自动生成</view>
        <view style="font-size: 33rpx" v-else>{{ createInfo.lng }},{{ createInfo.lat }}</view>
      </JInput>
    </JMainCard>
    <JButton
      pdTop="0"
      pd="0 30rpx 50rpx 30rpx"
      bottom="55rpx"
      v-if="createInfo.trmType"
      @HandleTouch="confirmCreated"
      >{{ createInfo.trmId ? "确认修改" : "确认创建" }}</JButton
    >
  </view>
  <SelectedType ref="sType" @selected="selected" />
</template>

<script setup>
import { ref } from "vue"
import { onShow, onLoad } from "@dcloudio/uni-app"
import useStore from "@/hooks/useStore.js"
import { $addTerminal, $updateTerminal, $terminalInfo } from "@/http/apiManager.js"
import { validateArray } from "@/hooks/rules"
import tool from "@/util/tool.js" // 工具类函数
import address from "@/components/applyJson/address.json" // 地址
import JHeaderTitle from "@/components/newComponents/JHeaderTitle/JHeaderTitle.vue"
import JMainCard from "@/components/newComponents/JMainCard/JMainCard.vue"
import JButton from "@/components/newComponents/JButton/JButton.vue"
import JInput from "@/components/newComponents/JInput/JInput.vue"
import SelectedType from "./components/SelectedType.vue"
import { getMapKey } from "@/hooks/mapInfo.js"
const { getStore } = useStore()
onLoad((options) => {
  if (options.trmId) return getList(options.trmId)
})
onShow(() => {
  if (getStore("createINfo")) {
    information.value = getStore("createINfo")
    Object.assign(createInfo.value, information.value)
  }
  if (getStore("POS")?.appId) {
    posInfo.value = getStore("POS")
    createInfo.value.trmName = posInfo.value.deviceName
    createInfo.value.trmNo = posInfo.value.deviceNo
  }
})
const createInfo = ref({
  areaCode: [],
  areacodeNames: [],
  defaultFlag: 0,
  state: 1,
  addressInfo: "",
  detailAddress: undefined,
})
const sType = ref(null)
const typeInfo = ref({})
const posInfo = ref({})
const information = ref({})
const change = (e, val) => {
  createInfo.value[val] = e.detail.value ? 1 : 0
}
const selected = (val) => {
  typeInfo.value = val
  createInfo.value.trmType = val.i + 1
}
const confirmCreated = () => {
  if (createInfo.value.trmType == 2 && !createInfo.value.trmNo) {
    return uni.showToast({
      title: "请选择扫码POS",
      icon: "none",
    })
  }
  if (!createInfo.value.addressInfo && createInfo.value.location) {
    return uni.showToast({
      title: "请选择省市区和布放位置",
      icon: "none",
    })
  } else {
    if (validateArray(createInfo.value)) {
      if (createInfo.value.trmId) {
        $updateTerminal(createInfo.value.trmId, createInfo.value).then(() => {
          uni.showToast({
            title: "修改成功",
            icon: "success",
            mask: true,
          })
        })
        uni.navigateBack()
      } else {
        $addTerminal(createInfo.value).then(() => {
          uni.showToast({
            title: "创建成功",
            icon: "success",
            mask: true,
          })
        })
        uni.navigateBack({
          delta: 2,
        })
      }
    }
  }
}
const getList = (val) => {
  $terminalInfo(val).then(({ bizData }) => {
    typeInfo.value.name = bizData.trmType == 1 ? "终端" : "扫码POS"
    createInfo.value = bizData
    createInfo.value.addressInfo = tool.addressBack(JSON.parse(bizData.areacode), address)
  })
}
function getAddress() {
  uni.chooseLocation({
    latitude: createInfo.value.lat || undefined,
    longitude: createInfo.value.lng || undefined,
    success: (res) => {
      createInfo.value.lng = res.longitude.toFixed(6)
      createInfo.value.lat = res.latitude.toFixed(6)
      createInfo.value.location = res.longitude + "/" + res.latitude
      createInfo.value.detailAddress = res.address
      getMapKey(res.address, 0).then((res) => {
        createInfo.value.addressInfo = res.text
        createInfo.value.areaCode = res.code
      })
    },
    fail: (err) => {
      console.log(err, "error")
    },
  })
}

const dataPickerChange = async (e, name) => {
  createInfo.value.addressInfo = ""
  createInfo.value.areaCode = []
  e.detail.value.forEach((v, i) => {
    createInfo.value.areaCode.push(v.value)
    createInfo.value.addressInfo += i == e.detail.value.length - 1 ? v.text : v.text + "/"
  })
  const address = createInfo.value.addressInfo.split("/").join("")
  getMapKey(address, 1).then((res) => {
    createInfo.value.lng = parseFloat(res.lon).toFixed(6)
    createInfo.value.lat = parseFloat(res.lat).toFixed(6)
    createInfo.value.detailAddress = address
  })
}
// 跳转到通用选择页面
const jumpPage = (val, selected, search) => {
  if (search) search = JSON.stringify(search)
  uni.navigateTo({
    url: `/pageWork/SelectedList/SelectedList?title=${val}&selected=${selected}&&search=${search}`,
  })
}
</script>

<style lang="scss" scoped>
.page-wrapper {
  image {
    width: 40rpx;
    height: 40rpx;
    vertical-align: bottom;
  }
  .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;
        }
      }
    }

    .img-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      width: 93rpx;
      height: 93rpx;
      margin-right: 20rpx;
      image {
        width: 60rpx;
        height: 66rpx;
      }
    }
  }
}
.tips {
  font-size: 33rpx;
  color: #a6a6a6;
}
.selected {
  color: #000;
}
.place-text {
  font-size: 33rpx;
  color: #a6a6a6;
  image {
    width: 40rpx;
    height: 40rpx;
    margin-left: 10rpx;
    vertical-align: middle;
  }
}
.state-text {
  font-size: 33rpx;
  color: #666;
}
.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>
