<script lang="ts" setup>
import { ref, onMounted } from "vue";
import {
  ElCard,
  ElTable,
  ElTableColumn,
  ElButton,
  ElMessage,
  ElPopconfirm,
  ElTag,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSwitch,
} from "element-plus";
import { Plus, Edit, Delete, Star } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/UserStore";
import {
  getAddressList,
  addAddress,
  updateAddress,
  deleteAddress,
  setDefaultAddress,
} from "@/apis/user";
import type { UserAddress, UserAddressForm } from "@/types/address";
import MainLayout from "@/layouts/MainLayout.vue";

const userStore = useUserStore();
const addressList = ref<UserAddress[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const isEdit = ref(false);

// 表单数据
const addressForm = ref<UserAddressForm>({
  id: undefined,
  userId: userStore.userInfo?.id || 0,
  receiverName: "",
  receiverPhone: "",
  province: "",
  city: "",
  district: "",
  detailAddress: "",
  isDefault: 0,
});

// 表单验证规则
const rules = {
  receiverName: [
    { required: true, message: "请输入收货人姓名", trigger: "blur" },
  ],
  receiverPhone: [
    { required: true, message: "请输入收货人手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  province: [{ required: true, message: "请输入省份", trigger: "blur" }],
  city: [{ required: true, message: "请输入城市", trigger: "blur" }],
  district: [{ required: true, message: "请输入区县", trigger: "blur" }],
  detailAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
  ],
};

const formRef = ref();

// 获取地址列表
const fetchAddressList = async () => {
  if (!userStore.userInfo?.id) {
    ElMessage.error("用户未登录");
    return;
  }

  loading.value = true;
  try {
    const response = await getAddressList(userStore.userInfo.id);
    if (response.code === 200) {
      addressList.value = response.data;
    } else {
      ElMessage.error(response.message || "获取地址列表失败");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("获取地址列表失败");
  } finally {
    loading.value = false;
  }
};

// 新增地址
const handleAddAddress = () => {
  dialogTitle.value = "新增地址";
  isEdit.value = false;
  addressForm.value = {
    id: undefined,
    userId: userStore.userInfo?.id || 0,
    receiverName: "",
    receiverPhone: "",
    province: "",
    city: "",
    district: "",
    detailAddress: "",
    isDefault: 0,
  };
  dialogVisible.value = true;
};

// 编辑地址
const handleEditAddress = (row: UserAddress) => {
  dialogTitle.value = "编辑地址";
  isEdit.value = true;
  addressForm.value = { ...row };
  dialogVisible.value = true;
};

// 删除地址
const handleDeleteAddress = async (id: number) => {
  if (!userStore.userInfo?.id) {
    ElMessage.error("用户未登录");
    return;
  }

  try {
    const response = await deleteAddress(id, userStore.userInfo.id);
    if (response.code === 200) {
      ElMessage.success("删除成功");
      fetchAddressList(); // 重新获取地址列表
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("删除失败");
  }
};

// 设置默认地址
const handleSetDefault = async (id: number) => {
  if (!userStore.userInfo?.id) {
    ElMessage.error("用户未登录");
    return;
  }

  try {
    const response = await setDefaultAddress(id, userStore.userInfo.id);
    if (response.code === 200) {
      ElMessage.success("设置默认地址成功");
      fetchAddressList(); // 重新获取地址列表
    } else {
      ElMessage.error(response.message || "设置失败");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("设置失败");
  }
};

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

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    try {
      let response;
      if (isEdit.value) {
        // 编辑地址
        response = await updateAddress(addressForm.value);
      } else {
        // 新增地址
        response = await addAddress(addressForm.value);
      }

      if (response.code === 200) {
        ElMessage.success(isEdit.value ? "更新成功" : "添加成功");
        dialogVisible.value = false;
        fetchAddressList(); // 重新获取地址列表
      } else {
        ElMessage.error(
          response.message || (isEdit.value ? "更新失败" : "添加失败"),
        );
      }
    } catch (err) {
      console.error(err);
      ElMessage.error(isEdit.value ? "更新失败" : "添加失败");
    }
  });
};

// 格式化地址
const formatAddress = (address: UserAddress): string => {
  return `${address.province}${address.city}${address.district}${address.detailAddress}`;
};

onMounted(() => {
  fetchAddressList();
});
</script>

<template>
  <MainLayout>
    <div class="address-page">
      <div class="container mx-auto px-4 py-8">
        <el-card class="address-card">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="text-xl font-bold">地址管理</span>
              <el-button type="primary" @click="handleAddAddress">
                <el-icon><plus /></el-icon>
                新增收货地址
              </el-button>
            </div>
          </template>

          <!-- 地址列表 -->
          <el-table
            :data="addressList"
            v-loading="loading"
            empty-text="暂无地址信息"
            stripe
          >
            <el-table-column prop="receiverName" label="收货人" width="100" />
            <el-table-column prop="receiverPhone" label="手机号" width="120" />
            <el-table-column label="地址">
              <template #default="{ row }">
                {{ formatAddress(row) }}
              </template>
            </el-table-column>
            <el-table-column label="默认地址" width="100">
              <template #default="{ row }">
                <el-tag v-if="row.isDefault === 1" type="success">默认</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <div class="flex space-x-2">
                  <el-button
                    size="small"
                    type="primary"
                    link
                    @click="handleEditAddress(row)"
                  >
                    <el-icon><edit /></el-icon>
                    编辑
                  </el-button>
                  <el-popconfirm
                    title="确定要删除这个地址吗？"
                    @confirm="handleDeleteAddress(row.id)"
                  >
                    <template #reference>
                      <el-button size="small" type="danger" link>
                        <el-icon><delete /></el-icon>
                        删除
                      </el-button>
                    </template>
                  </el-popconfirm>
                  <el-button
                    v-if="row.isDefault !== 1"
                    size="small"
                    type="warning"
                    link
                    @click="handleSetDefault(row.id)"
                  >
                    <el-icon><star /></el-icon>
                    设为默认
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 地址编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        @close="formRef?.resetFields()"
      >
        <el-form
          ref="formRef"
          :model="addressForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="收货人" prop="receiverName">
            <el-input
              v-model="addressForm.receiverName"
              placeholder="请输入收货人姓名"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="receiverPhone">
            <el-input
              v-model="addressForm.receiverPhone"
              placeholder="请输入收货人手机号"
            />
          </el-form-item>
          <el-form-item label="省份" prop="province">
            <el-input v-model="addressForm.province" placeholder="请输入省份" />
          </el-form-item>
          <el-form-item label="城市" prop="city">
            <el-input v-model="addressForm.city" placeholder="请输入城市" />
          </el-form-item>
          <el-form-item label="区县" prop="district">
            <el-input v-model="addressForm.district" placeholder="请输入区县" />
          </el-form-item>
          <el-form-item label="详细地址" prop="detailAddress">
            <el-input
              v-model="addressForm.detailAddress"
              type="textarea"
              placeholder="请输入详细地址"
            />
          </el-form-item>
          <el-form-item label="设为默认">
            <el-switch
              v-model="addressForm.isDefault"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </MainLayout>
</template>

<style scoped>
.address-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.address-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  text-align: right;
}
</style>
