<template>
  <div class="page-container">
    <div class="page-header">
      <PageTitle title="收货地址" />
      <el-button type="danger" link @click="handleAdd">
        <el-icon><Plus /></el-icon>新增收货地址
      </el-button>
    </div>

    <!-- 地址列表 -->
    <div class="address-list">
      <div v-for="(item, index) in addressList" :key="index" class="address-item">
        <div class="address-info">
          <div class="address-name">
            <span>{{ item.consignee }}</span>
            <el-tag v-if="item.defaultAddress === '0'" type="danger" size="small">默认地址</el-tag>
          </div>
          <div class="address-detail">{{ item.provincialCityCountry }} {{ item.address }}</div>
          <div class="address-phone">{{ item.phone }}</div>
        </div>
        <div class="address-actions">
          <el-button type="primary" link @click="handleEdit(item)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(item)">删除</el-button>
          <el-button v-if="item.defaultAddress !== '0'" type="danger" link @click="handleSetDefault(item)">设为默认</el-button>
        </div>
      </div>
      <el-empty v-if="addressList.length === 0" description="暂无收货地址" />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="550px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="form.name" 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="region">
          <el-cascader
            v-model="form.regionCodes"
            :options="regionData as any"
            placeholder="请选择省/市/区"
            style="width: 100%"
            @change="handleRegionChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" type="textarea" :rows="2" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="设为默认"><el-switch v-model="form.isDefault" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PageTitle } from '@/components';
import { getAddressList, addAddress, updateAddress, deleteAddress, setDefaultAddress } from '@/api/pc/enterprise';
import { regionData } from 'element-china-area-data';

const dialogVisible = ref(false);
const dialogTitle = ref('新增收货地址');
const formRef = ref();
const editingId = ref<number | null>(null);

const form = reactive({ name: '', phone: '', regionCodes: [], region: '', address: '', isDefault: false });

const rules = {
  name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
};

const addressList = ref([]);

// 加载地址列表
const loadAddressList = async () => {
  try {
    const res = await getAddressList();
    if (res.code === 200) {
      addressList.value = res.rows || [];
    }
  } catch (error) {
    console.error('加载地址列表失败:', error);
    ElMessage.error('加载地址列表失败');
  }
};

onMounted(() => {
  loadAddressList();
});

const resetForm = () => {
  form.name = '';
  form.phone = '';
  form.regionCodes = [];
  form.region = '';
  form.address = '';
  form.isDefault = false;
  editingId.value = null;
};

// 处理地区选择变化
const handleRegionChange = (value: string[]) => {
  if (value && value.length === 3) {
    // 根据选中的代码查找对应的名称

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

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

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

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

const handleAdd = () => {
  resetForm();
  dialogTitle.value = '新增收货地址';
  dialogVisible.value = true;
};
const handleEdit = (item: any) => {
  editingId.value = item.id;
  form.name = item.consignee;
  form.phone = item.phone;
  form.region = item.provincialCityCountry || '';
  form.address = item.address || '';
  form.isDefault = item.defaultAddress;

  // 尝试根据省市区代码设置级联选择器的值
  if (item.provincialNo && item.cityNo && item.countryNo) {
    form.regionCodes = [item.provincialNo, item.cityNo, item.countryNo];
  } else {
    form.regionCodes = [];
  }

  dialogTitle.value = '编辑收货地址';
  dialogVisible.value = true;
};
const handleSave = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;
  try {
    const data: any = {
      consignee: form.name,
      phone: form.phone,
      address: form.address,
      isDefault: form.isDefault
    };

    // 如果选择了省市区，发送代码
    if (form.regionCodes && form.regionCodes.length === 3) {
      data.provincialNo = form.regionCodes[0];
      data.cityNo = form.regionCodes[1];
      data.countryNo = form.regionCodes[2];
      data.provincialCityCountry = form.region;
    }

    if (editingId.value) {
      data.id = editingId.value;
      await updateAddress(data);
    } else {
      await addAddress(data);
    }
    ElMessage.success(editingId.value ? '修改成功' : '新增成功');
    dialogVisible.value = false;
    loadAddressList();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};
const handleDelete = (item: any) => {
  ElMessageBox.confirm('确定要删除该收货地址吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(
    async () => {
      try {
        await deleteAddress([item.id]);
        ElMessage.success('删除成功');
        loadAddressList();
      } catch (error) {
        ElMessage.error('删除失败');
      }
    }
  );
};
const handleSetDefault = async (item: any) => {
  try {
    await setDefaultAddress({ id: item.id });
    ElMessage.success('设置成功');
    loadAddressList();
  } catch (error) {
    ElMessage.error('设置失败');
  }
};
</script>

<style scoped lang="scss">
.page-container{
  flex: 1;
  background-color: #ffffff;
  padding: 15px;
  margin-bottom: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  :deep(.page-title) {
    margin-bottom: 0;
  }
}
.address-list {
  .address-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-bottom: 15px;
    &:last-child {
      margin-bottom: 0;
    }
    .address-info {
      .address-name {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 15px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
      }
      .address-detail {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }
      .address-phone {
        font-size: 14px;
        color: #666;
      }
    }
    .address-actions {
      display: flex;
      gap: 10px;
    }
  }
}
</style>
