<route lang="json5" type="page">
{
  style: { navigationBarTitleText: '购牛录入' },
}
</route>

<template>
  <view class="container px-2">
    <wd-form ref="form" :model="model" class="px-2">
      <wd-cell-group custom-class="group" title="牛只信息" border>
        <wd-input
          prop="value2"
          clearable
          label="电子耳标号"
          label-width="100px"
          :disabled="model.earTag"
          suffix-icon="scan"
          @clicksuffixicon="scanQRCode"
          v-model="model.earTag"
          placeholder="请输入电子耳标号"
          required
        />

        <wd-input
          label="牛号"
          label-width="100px"
          prop="value2"
          clearable
          v-model="model.earTag"
          placeholder="请输入牛号"
        />

        <wd-cell title="体重" title-width="100px" prop="value1" right>
          <view style="text-align: left">
            <wd-input-number
              v-model="model.weight"
              @change="handleChange"
              :precision="2"
              :step="0.1"
            />
            <text class="pl-2 mt-2">KG</text>
          </view>
        </wd-cell>

        <!-- <wd-picker
          label="品种"
          label-width="100px"
          :columns="columns"
          v-model="model.value1"
          @confirm="handleConfirm"
        /> -->
        <wd-cell title="图片上传" title-width="100px" prop="value1">
          <wd-upload
            :file-list="fileList"
            image-mode="aspectFill"
            :action="action"
            :limit="6"
            @change="handleUpload"
            accept="all"
            multiple
          ></wd-upload>
        </wd-cell>
        <wd-textarea
          label="备注"
          label-width="100px"
          v-model="model.remark"
          :maxlength="200"
          clearable
          show-word-limit
          placeholder="请输入备注"
          auto-height
        />
        <wd-input label="操作人" label-width="100px" prop="value2" disabled v-model="model.user" />
        <wd-calendar
          label="购买时间"
          label-width="100px"
          type="datetime"
          v-model="model.date"
          disabled
        />
        <wd-input
          label="当前位置"
          label-width="100px"
          prop="location"
          disabled
          v-model="location"
        />
      </wd-cell-group>
      <view class="footer mx-4 mt-10">
        <wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
// 获取当前地理位置
var QQMapWX = require('../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk')

defineOptions({
  name: 'neckRing',
})

// const { success: showSuccess } = useToast()
// form信息
const model = reactive<{
  value1: string
  value2: string
  date: number
  earTag: string | null
  user: string
  weight: string
  remark: string
}>({
  value1: '',
  value2: '',
  date: Date.now(),
  earTag: '',
  user: 'hss',
  weight: '321.2',
  remark: '',
})

// 品种下来选择
const columns = ref(['选项1', '选项2', '选项3', '选项4', '选项5', '选项6', '选项7'])
const value = ref('选项1')
function handleConfirm({ value }) {
  value.value = value
}

const fileList = ref<any[]>([
  {
    url: 'https://img12.360buyimg.com//n0/jfs/t1/29118/6/4823/55969/5c35c16bE7c262192/c9fdecec4b419355.jpg',
  },
])

const action: string =
  'https://mockapi.eolink.com/zhTuw2P8c29bc981a741931bdd86eb04dc1e8fd64865cb5/upload'

function handleUpload({ fileList: files }) {
  fileList.value = files
}

async function scanQRCode() {
  try {
    const res = await uni.scanCode()
    model.earTag = res.result // 假设二维码中的数据是耳标编号
    console.log(model.earTag, '耳标编号')
    // this.earTag = res.result // 假设二维码中的数据是耳标编号
  } catch (e) {
    console.error('扫描失败:', e)
  }
}
const form = ref()

function handleChange({ value }) {
  // console.log(value)
}

function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        // showSuccess({
        //   msg: '校验通过',
        // })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
// const location = ref<string>('定位中...')
// // 获取当前地理位置
// function fetchLocation() {
//   uni.getFuzzyLocation({
//     type: 'wgs84', //默认为 wgs84 返回 gps 坐标
//     success: (res) => {
//       const latitude = res.latitude
//       const longitude = res.longitude

//       // console.log(res, '经纬度')
//       // // 使用腾讯地图API获取具体到县城的地址
//       // const key = 'GNDBZ-VYLCG-PJYQA-I44CW-RUT7Q-YUFG5'
//       // uni.request({
//       //   url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&get_poi=0`,
//       //   success: (result) => {
//       //     console.log(result, 'hss-permission')
//       //     const addressComponent = result.data.result.address_component
//       //     location.value = `${addressComponent.province} ${addressComponent.city} ${addressComponent.district}`
//       //   },
//       //   fail: () => {
//       //     location.value = '无法获取地理位置'
//       //   },
//       // })
//     },
//     fail: () => {
//       location.value = '无法获取地理位置'
//     },
//   })
// }

// onMounted(() => {
//   // fetchLocation()
// })
const location = ref<string>('定位中...')

function getUserAdreess() {
  uni.authorize({
    scope: 'scope.userFuzzyLocation',
    success(res) {
      if (res.errMsg == 'authorize:ok') {
        uni.getFuzzyLocation({
          type: 'wgs84',
          success(res) {
            let qqmapsdk = new QQMapWX({
              key: 'GNDBZ-VYLCG-PJYQA-I44CW-RUT7Q-YUFG5',
            })
            qqmapsdk.reverseGeocoder({
              location: {
                latitude: res.latitude,
                longitude: res.longitude,
              },
              success(addressRes) {
                console.log(addressRes, '======hss')
                // @ts-ignore
                location.value = addressRes?.result?.address || ''
              },
              fail(res) {
                uni.showToast({
                  title: '获取定位失败,请先开启手机定位！',
                  icon: 'none',
                  duration: 2000,
                })
              },
            })
          },
        })
      }
    },
    fail(err) {
      console.log(err, '获取定位失败')
    },
  })
}
onLoad(() => {
  getUserAdreess()
})
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 10rem;
  background: #fff;
}
</style>
