<template>
  <el-dialog v-model="dialogVisible" title="添加收货地址" width="650px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="收货人" prop="consignee">
        <el-input v-model="form.consignee" placeholder="请输入收货人姓名" />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="form.deptName" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="邮政编码" prop="postal">
        <el-input v-model="form.postal" placeholder="请输入邮政编码" />
      </el-form-item>
      <el-form-item label="详细地址" prop="provincialCityCountry">
        <el-cascader v-model="codeArr" :options="regionData" placeholder="请选择" @change="handleRegionChange" style="width: 100%" />
      </el-form-item>
      <el-form-item prop="address">
        <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="submitLoading" type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, getCurrentInstance } from 'vue';
import { addShippingAddress } from '@/api/customer/customerFile/shippingAddress';
import { ShippingAddressForm } from '@/api/customer/customerFile/shippingAddress/types';
import { regionData } from 'element-china-area-data';
import type { FormInstance, FormRules } from 'element-plus';

interface Props {
  modelValue: boolean;
  customerId?: string | number;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const codeArr = ref<string[]>([]);

const initForm: ShippingAddressForm = {
  customerId: undefined,
  consignee: undefined,
  deptName: undefined,
  phone: undefined,
  address: undefined,
  postal: undefined,
  provincialNo: undefined,
  cityNo: undefined,
  countryNo: undefined,
  provincialCityCountry: undefined
};

const form = ref<ShippingAddressForm>({ ...initForm });

const rules: FormRules = {
  consignee: [{ required: true, message: '收货人姓名不能为空', trigger: 'blur' }],
  provincialCityCountry: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }]
};

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
    if (val) {
      form.value.customerId = props.customerId;
    }
  },
  { immediate: true }
);

// 监听 dialogVisible 变化，同步到父组件
watch(dialogVisible, (val) => {
  emit('update:modelValue', val);
});

// 处理区域选择变化
const handleRegionChange = (val: string[]) => {
  if (!val || val.length === 0) {
    form.value.provincialNo = undefined;
    form.value.cityNo = undefined;
    form.value.countryNo = undefined;
    form.value.provincialCityCountry = undefined;
    return;
  }

  // 保存编码
  form.value.provincialNo = val[0];
  form.value.cityNo = val[1];
  form.value.countryNo = val[2];

  // 根据编码获取名称
  const names: string[] = [];
  if (val[0]) {
    const province = regionData.find((item: any) => item.value === val[0]);
    if (province) {
      names.push(province.label);

      if (val[1] && province.children) {
        const city = province.children.find((item: any) => item.value === val[1]);
        if (city) {
          names.push(city.label);

          if (val[2] && city.children) {
            const county = city.children.find((item: any) => item.value === val[2]);
            if (county) {
              names.push(county.label);
            }
          }
        }
      }
    }
  }

  // 将省市区名称用斜杠连接
  form.value.provincialCityCountry = names.join('/');
};

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false);
  resetForm();
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  form.value = { ...initForm };
  codeArr.value = [];
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    submitLoading.value = true;
    await addShippingAddress(form.value);
    emit('success');
    handleClose();
  } catch (error) {
    console.error('添加收货地址失败:', error);
  } finally {
    submitLoading.value = false;
  }
};
</script>
