<template>
  <view>
    <up-form labelPosition="left" :model="modelForm" :rules="rulesForm" ref="formRef">
      <up-form-item label="姓名" prop="name" borderBottom labelWidth="70">
        <up-input v-model="modelForm.name" border="none" placeholder="请输入姓名"></up-input>
      </up-form-item>
      <up-form-item label="性别" prop="sex" borderBottom @click="() => (sexFlag = true)" labelWidth="70">
        <up-input v-model="displaySex" disabled disabledColor="#ffffff" placeholder="请选择性别" border="none"></up-input>
        <template #right>
          <up-icon name="arrow-right"></up-icon>
        </template>
      </up-form-item>
      <!-- <up-form-item label="关系" prop="label" borderBottom @click="() => (labelFlag = true)" labelWidth="70">
        <up-input v-model="modelForm.label" disabled disabledColor="#ffffff" placeholder="请选择关系"
          border="none"></up-input>
        <template #right>
          <up-icon name="arrow-right"></up-icon>
        </template>
      </up-form-item> -->
      <up-form-item label="年龄" prop="age" borderBottom labelWidth="70">
        <up-input v-model="modelForm.age" border="none" placeholder="请输入年龄"></up-input>
      </up-form-item>
      <up-form-item label="手机号" prop="telephone" borderBottom labelWidth="70">
        <up-input v-model="modelForm.telephone" border="none" placeholder="请输入手机号"></up-input>
      </up-form-item>
      <up-form-item label="地区" prop="area" borderBottom @click="() => (addressShow = true)" labelWidth="70">
        <pickerAddress @change="addressChange" :selectValue="[
            modelForm.provinceInd,
            modelForm.cityInd,
            modelForm.districtInd,
          ]">
          <view class="inp" :class="
              modelForm.provinceName &&
              modelForm.cityName &&
              modelForm.districtName
                ? ''
                : 'address-inp'
            ">
            {{ modelForm.provinceName ? modelForm.provinceName : '省' }} /
            {{ modelForm.cityName ? modelForm.cityName : '市' }} /
            {{ modelForm.districtName ? modelForm.districtName : '区' }}
          </view>
        </pickerAddress>
        <template #right>
          <up-icon name="map" size="22" @click="onCityWx"></up-icon>
        </template>
      </up-form-item>
      <up-form-item label="地址" prop="address" borderBottom labelWidth="70">
        <up-input v-model="modelForm.address" border="none" placeholder="请输入地址"></up-input>
      </up-form-item>
      <up-form-item label="门牌号" prop="detailAddress" borderBottom labelWidth="70">
        <up-input v-model="modelForm.detailAddress" border="none" placeholder="请输入地址"></up-input>
      </up-form-item>
    </up-form>
    <up-action-sheet :show="sexFlag" :actions="sexOptions" @select="sexSelect"
      @close="sexFlag = false"></up-action-sheet>
    <up-action-sheet :show="labelFlag" :actions="relaTionsHip" @select="sexSelectsHip"
      @close="labelFlag = false"></up-action-sheet>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import pickerAddress from '@/pages_home/components/pickerAddress/pickerAddress.vue' // 地区选择器组件
import { splitAddress } from '@/utils/adress'
import config from '@/config'
const mapKey = config.mapKey // 从配置文件中直接获取腾讯地图key
const formRef = ref(null)
const modelForm = ref({
  name: '',
  sex: '',
  // label: '',
  age: '',
  telephone: '',
  detailAddress: '',
  address: '',


  provinceName: '', // 省
  provinceCode: '',
  provinceInd: 0,

  cityName: '', // 市
  cityCode: '',
  cityInd: 0,

  districtName: '',
  districtCode: '',
  districtInd: 0,

})

const rulesForm = ref({
  name: {
    type: 'string',
    required: true,
    message: '请填写姓名',
    trigger: ['blur', 'change'],
  },
  // sex: {
  //   type: 'string',
  //   required: true,
  //   message: '请选择性别',
  //   trigger: ['change'],
  // },
  // userInfo: {
  //   type: 'string',
  //   required: true,
  //   message: '请填写年龄',
  //   trigger: ['blur', 'change'],
  // },
  telephone: {
    type: 'string',
    required: true,
    message: '请填写手机号',
    trigger: ['blur', 'change'],
  },
  address: {
    type: 'string',
    required: true,
    message: '请填写地址',
    trigger: ['blur', 'change'],
  },
  detailAddress: {
    type: 'string',
    required: true,
    message: '请填写门牌号',
    trigger: ['blur', 'change'],
  }
})

let sexFlag = ref(false)
let labelFlag = ref(false)
let addressShow = ref(false)
let index = ref(0)
// 新增一个响应式变量，控制传染病内容的显示
const showContagionContent = ref(false)

const sexOptions = ref([
  {
    name: '男',
    value: 0,
  },
  {
    name: '女',
    value: 1,
  },
])

const relaTionsHip = ref([
  {
    name: '父母',
  },
  {
    name: '子女',
  },
  {
    name: '兄弟',
  },
  {
    name: '朋友',
  },
  {
    name: '同学',
  },
  {
    name: '同事',
  },
  {
    name: '配偶',
  },
])

const displaySex = computed({
  get() {
    const option = sexOptions.value.find(
      (item) => item.value === modelForm.value.sex
    )
    return option ? option.name : ''
  },
  set(newValue) {
    const option = sexOptions.value.find((item) => item.name === newValue)
    if (option) {
      modelForm.value.sex = option.value
    }
  },
})
// 性别选择处理
function sexSelect(e) {
  modelForm.value.sex = e.value
  sexFlag.value = false
}

function sexSelectsHip(e) {
  modelForm.value.label = e.name
  labelFlag.value = false
}

function addressChange(info) {
  console.log(info, '>>>>data')

  const { data, code, index } = info

  modelForm.value.provinceName = data[0]
  modelForm.value.provinceCode = code[0]
  modelForm.value.provinceInd = index[0]

  modelForm.value.cityName = data[1]
  modelForm.value.cityCode = code[1]
  modelForm.value.cityInd = index[1]

  modelForm.value.districtName = data[2]
  modelForm.value.districtCode = code[2]
  modelForm.value.districtInd = index[2]
}

// 使用腾讯地图 API 的函数
function getAdcodeByCoordinates(latitude, longitude) {
  if (!mapKey) {
    console.error('腾讯地图key为空，请检查配置！');
    uni.showToast({
      title: '腾讯地图key为空',
      icon: 'error'
    });
    return Promise.reject('地图获取失败');
  }

  const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${mapKey}`;
  console.log('请求URL:', url);

  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      success: (res) => {
        if (res.data.status === 0) {
          const adInfo = res.data.result.ad_info;
          resolve({
            provinceName: adInfo.province,
            cityName: adInfo.city,
            districtName: adInfo.district,
            provinceCode: adInfo.adcode.slice(0, 2) + '0000', // 提取省编码
            cityCode: adInfo.adcode.slice(0, 4) + '00', // 提取市编码
            districtCode: adInfo.adcode // 提取区编码
          });
        } else {
          console.error('腾讯地图API错误:', res.data.message);
          reject('Error fetching adcode: ' + res.data.message);
        }
      },
      fail: (err) => {
        console.error('请求腾讯地图API失败:', err);
        reject(err);
      }
    });
  });
}

// 点击地图图标选择地址
// 点击地址图标，选择位置并获取省市区编码
async function onCityWx() {
  wx.chooseLocation({
    success: async function (res) {
      try {
        console.log('选择的地址:', res);

        // 调用腾讯地图 API 获取省市区编码
        const adcodeData = await getAdcodeByCoordinates(res.latitude, res.longitude);

        // 更新表单数据
        modelForm.value.provinceName = adcodeData.provinceName;
        modelForm.value.cityName = adcodeData.cityName;
        modelForm.value.districtName = adcodeData.districtName;
        modelForm.value.provinceCode = adcodeData.provinceCode;
        modelForm.value.cityCode = adcodeData.cityCode;
        modelForm.value.districtCode = adcodeData.districtCode;
        modelForm.value.address = res.address; // 完整地址
        modelForm.value.longitude = res.longitude;
        modelForm.value.latitude = res.latitude;

        console.log('获取到的省市区信息:', adcodeData);
      } catch (err) {
        console.error('获取省市区编码失败:', err);
        // uni.showToast({
        //   title: '获取地址编码失败',
        //   icon: 'error'
        // });
      }
    },
    fail: function (err) {
      console.error('选择位置失败:', err);
      uni.showToast({
        title: '获取地址失败',
        icon: 'error'
      });
    }
  });
}
defineExpose({
  modelForm: modelForm.value,
})
</script>

<style></style>
