<!-- 搜索表单 -->
<template>
  <simple-form-modal
    title="修改地址"
    :items="formItems"
    ref="editRef"
    :baseUrl="baseUrl"
    @success="(data) => emit('success', data)"
    :formatData="formatData"
  >
    <template #areaSelect>
      <area-select v-model="formData.proCodes" />
    </template>
  </simple-form-modal>
</template>

<script setup>
  import { reactive, ref, defineEmits, getCurrentInstance } from 'vue';
  import SimpleFormModal from '@/components/CommonPage/SimpleFormModal.vue';
  import AreaSelect from '@/components/CommonPage/AreaSelect.vue';
  import request from '@/utils/request';
  const { proxy } = getCurrentInstance();

  const emit = defineEmits(['success']);

  const formItems = computed(() => {
    return [
      {
        type: 'input',
        label: '发件人',
        prop: 'sendName',
        required: true
      },
      {
        type: 'input',
        label: '手机号',
        prop: 'sendMobile',
        itemProps: {
          rules: [
            { required: true, message: '请输入手机号', trigger: ['blur'] },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入正确的手机号',
              trigger: ['change']
            }
          ]
        }
      },
      {
        type: 'regions',
        label: '省市区',
        prop: 'proCodes',
        required: true,
        props: {
          cascaderProps: {
            lazy: true,
            lazyLoad: loadAreaData,
            value: 'id',
            label: 'district',
            checkStrictly: false
          }
        }
      },
      {
        type: 'textarea',
        label: '详细地址',
        prop: 'detailAddress',
        required: true
      }
    ];
  });

  //默认值
  const baseUrl = reactive({
    add: '/order/orderInfo/modifyAddress'
  });
  const formData = ref({
    orderId: '',
    sendName: '',
    sendMobile: '',
    provinceId: 0,
    cityId: 0,
    districtId: 0,
    detailAddress: '',
    proCodes: []
  });

  const editRef = ref(null);

  const formatData = (data) => {
    if (data.proCodes.length > 0) {
      data.provinceId = data.proCodes[0];
      data.cityId = data.proCodes[1];
      data.districtId = data.proCodes[2];
    }
    return {
      ...data,
      orderId: formData.value.orderId
    };
  };

  function handleOpen(data) {
    if (data && data.orderId) {
      formData.value.orderId = data.orderId;
      formData.value.sendName = data.sendName;
      formData.value.sendMobile = data.sendMobile;
      formData.value.detailAddress = data.sendAddress;
      formData.value.proCodes = data.sendSsqId ? data.sendSsqId.split('/').map(Number) : [];
      console.log(formData.value, 'formData.value');
      editRef.value?.handleOpen(formData.value);
    }
  }

  // 加载区域数据
  async function loadAreaData(node, resolve) {
    const { level, value } = node;
    try {
      let data = [];
      if (level === 0) {
        // 加载省份数据
        data = await getProvinceList();
        console.log(data, 'data');
      } else if (level === 1) {
        // 加载城市数据
        data = await getProvinceList(value);
      } else if (level === 2) {
        // 加载区县数据
        data = await getProvinceList(value);
        data.forEach((item) => {
          item.leaf = true;
        });
      }
      resolve(data);
    } catch (error) {
      console.error('加载地区数据失败:', error);
      resolve([]);
    }
  }

  function getProvinceList(id = 1) {
    return new Promise((resolve, reject) => {
      request
        .get(`/baseinfo/districtInfo/findInfo/${id}`)
        .then((res) => {
          resolve(res.data.data);
        })
        .catch((err) => {
          resolve([]);
          reject(err);
        });
    });
  }

  defineExpose({ handleOpen });
</script>
