<template>
  <div class="table-box button-table friend-coupon-container">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      :key="activeName"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <div class="table-header-content">
          <!-- <div class="header-button">
            <el-button type="primary" @click="openGiftDialog"> 赠送好友优惠券 </el-button>
          </div> -->
          <el-tabs v-model="activeName" class="header-tabs" @tab-click="handleTabClick">
            <el-tab-pane label="好友赠我" name="friendMessage" />
            <el-tab-pane label="我赠好友" name="myGift" />
          </el-tabs>
        </div>
      </template>

      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button link type="primary" @click="viewDetail(scope.row)"> 查看详情 </el-button>
        <!-- <el-button v-if="activeName === 'myGift'" link type="primary" @click="deleteRow(scope.row)"> 删除 </el-button> -->
      </template>
    </ProTable>

    <!-- 赠送好友优惠券对话框 -->
    <el-dialog v-model="giftDialogVisible" title="赠送好友优惠券" width="600px" @close="closeGiftDialog">
      <el-form ref="giftFormRef" :model="giftFormData" :rules="giftRules" label-width="120px">
        <el-form-item label="选择好友" prop="friendId">
          <el-select v-model="giftFormData.friendId" placeholder="请选择好友" style="width: 100%" :loading="friendListLoading">
            <el-option v-for="friend in friendList" :key="friend.id" :label="friend.name" :value="friend.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择优惠券" prop="couponId">
          <el-select
            v-model="giftFormData.couponId"
            placeholder="请选择优惠券"
            style="width: 100%"
            :loading="couponListLoading"
            @focus="loadCouponList"
            @change="handleCouponChange"
          >
            <el-option v-for="coupon in couponList" :key="coupon.id" :label="coupon.name" :value="coupon.id" />
          </el-select>
          <div v-if="giftFormData.couponId" class="coupon-info">
            <span>请输入赠送数量</span>
          </div>
        </el-form-item>

        <el-form-item v-if="giftFormData.couponId" label="赠送数量" prop="quantity">
          <el-input-number v-model="giftFormData.quantity" :min="1" :max="100" placeholder="请输入数量" style="width: 100%" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeGiftDialog"> 取消 </el-button>
          <el-button type="primary" @click="handleGiftSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="friendCoupon">
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { localGet } from "@/utils";
import { getFriendCouponList, getMutualAttention, getCouponList, setFriendCoupon } from "@/api/modules/newLoginApi";

const router = useRouter();

// 当前激活的标签页
const activeName = ref("friendMessage");

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 赠送对话框
const giftDialogVisible = ref(false);
const giftFormRef = ref<FormInstance>();

// 好友列表
const friendList = ref<any[]>([]);
const friendListLoading = ref(false);
const friendListLoaded = ref(false); // 标记是否已加载

// 优惠券列表
const couponList = ref<any[]>([]);
const couponListLoading = ref(false);
const couponListLoaded = ref(false); // 标记是否已加载

// 加载好友列表
const loadFriendList = async () => {
  // 如果已经加载过，则不重复加载
  if (friendListLoaded.value || friendListLoading.value) {
    return;
  }

  friendListLoading.value = true;

  try {
    const res: any = await getMutualAttention({
      page: 1,
      size: 999, // 获取所有好友
      fansId: "store_" + localGet("geeker-user")?.userInfo?.phone
    });

    if (res.code === 200) {
      friendList.value = res.data.records.map((item: any) => ({
        id: item.id,
        name: item.username
      }));
      friendListLoaded.value = true;
    } else {
      // 如果接口失败，使用模拟数据
      friendList.value = [];
      friendListLoaded.value = true;
    }
  } catch (error) {
    console.error("加载好友列表失败:", error);
    // 使用模拟数据作为备用
    friendList.value = [];
    friendListLoaded.value = true;
  } finally {
    friendListLoading.value = false;
  }
};

// 加载优惠券列表
const loadCouponList = async () => {
  // 如果已经加载过，则不重复加载
  if (couponListLoaded.value || couponListLoading.value) {
    return;
  }

  couponListLoading.value = true;

  try {
    const res: any = await getCouponList({
      storeId: localGet("createdId"),
      status: 0
    });

    if (res.code === 200) {
      couponList.value = res.data.map((item: any) => ({
        id: item.id,
        name: item.name
      }));
      couponListLoaded.value = true;
    } else {
      // 如果接口失败，使用模拟数据
      couponList.value = [];
      couponListLoaded.value = true;
    }
  } catch (error) {
    console.error("加载优惠券列表失败:", error);
    // 使用模拟数据作为备用
    couponList.value = [];
    couponListLoaded.value = true;
  } finally {
    couponListLoading.value = false;
  }
};

// 赠送表单数据
const giftFormData = reactive({
  friendId: "",
  couponId: "",
  quantity: 1
});

// 表单验证规则
const giftRules = reactive<FormRules>({
  friendId: [{ required: true, message: "请选择好友", trigger: "change" }],
  couponId: [{ required: true, message: "请选择优惠券", trigger: "change" }],
  quantity: [{ required: true, message: "请输入赠送数量", trigger: "blur" }]
});

// 好友赠我表格列配置
const friendMessageColumns = reactive<ColumnProps<any>[]>([
  {
    prop: "storeName",
    label: "店铺名称",
    search: {
      el: "input",
      props: { placeholder: "请输入" }
    }
  },
  {
    prop: "couponType",
    label: "类型",
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: [
      { label: "满减券", value: "1" },
      { label: "折扣券", value: "2" }
    ],
    render: (scope: any) => {
      const typeMap: Record<string, string> = { "1": "满减券", "2": "折扣券" };
      const val = scope.row.couponType ?? scope.row.type;
      return typeMap[String(val)] ?? scope.row.couponTypeName ?? "--";
    }
  },
  {
    prop: "couponName",
    label: "优惠券名称",
    render: (scope: any) => {
      const r = scope.row;
      return r.couponName ?? r.name ?? r.couponTitle ?? "--";
    }
  },
  {
    prop: "couponNum",
    label: "数量"
  },
  {
    prop: "longTermValid",
    label: "有效期",
    render: (scope: any) => {
      const r = scope.row;
      const lt = r.longTermValid;
      if (lt === 1 || lt === "1" || lt === true) return "长期有效";
      const ed = r.expirationDate;
      if (ed === null || ed === undefined || ed === "") return "--";
      return `${ed}天`;
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);

// 我赠好友表格列配置（与好友赠我保持一致）
const myGiftColumns = reactive<ColumnProps<any>[]>([
  {
    prop: "storeName",
    label: "店铺名称",
    search: {
      el: "input",
      props: { placeholder: "请输入" }
    }
  },
  {
    prop: "couponType",
    label: "类型",
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: [
      { label: "满减券", value: "1" },
      { label: "折扣券", value: "2" }
    ],
    render: (scope: any) => {
      const typeMap: Record<string, string> = { "1": "满减券", "2": "折扣券" };
      const val = scope.row.couponType ?? scope.row.type;
      return typeMap[String(val)] ?? scope.row.couponTypeName ?? "--";
    }
  },
  {
    prop: "couponName",
    label: "优惠券名称",
    render: (scope: any) => {
      const r = scope.row;
      return r.couponName ?? r.name ?? r.couponTitle ?? "--";
    }
  },
  {
    prop: "couponNum",
    label: "数量"
  },
  {
    prop: "longTermValid",
    label: "有效期",
    render: (scope: any) => {
      const r = scope.row;
      const lt = r.longTermValid;
      if (lt === 1 || lt === "1" || lt === true) return "长期有效";
      const ed = r.expirationDate;
      if (ed === null || ed === undefined || ed === "") return "--";
      return `${ed}天`;
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);

// 根据当前选中的tab动态返回列配置
const columns = computed(() => {
  return activeName.value === "friendMessage" ? friendMessageColumns : myGiftColumns;
});
// 初始化请求参数：列表接口格式 storeUserId、storeName、type、queryType（queryType 1=好友赠我 2=我赠好友）
const initParam = reactive<Record<string, any>>({
  storeUserId: localGet("createdId") ?? "",
  queryType: 1
});

// Tab 切换处理：queryType 1=好友赠我，2=我赠好友
const handleTabClick = () => {
  initParam.queryType = activeName.value === "friendMessage" ? 1 : 2;
  proTable.value?.getTableList();
};

// dataCallback：兼容后端返回格式——data 直接为数组 或 { records/list, total }，统一为 { list, total }
const dataCallback = (data: any) => {
  if (!data) return { list: [], total: 0 };
  if (Array.isArray(data)) {
    return { list: data, total: data.length };
  }
  const list = data.records ?? data.list ?? [];
  const total = data.total ?? list.length;
  return { list, total };
};

// 获取表格列表：接口参数 storeUserId、storeName、couponType、queryType（1=好友赠我 2=我赠好友）、分页
const getTableList = (params: any) => {
  let storeUserId = localGet("geeker-user")?.userInfo?.id;
  const newParams: any = {
    storeUserId: storeUserId,
    storeName: params.storeName ?? "",
    type: 1,
    queryType: activeName.value === "friendMessage" ? 1 : 2,
    page: params.pageNum ?? 1,
    size: params.pageSize ?? 10
  };
  // 优惠券类型：1=仅满减券，2=仅折扣券，不传=全部优惠券（搜索框可能传字符串 '1'/'2'）
  const couponType = params.couponType != null && params.couponType !== "" ? Number(params.couponType) : undefined;
  if (couponType === 1 || couponType === 2) {
    newParams.couponType = couponType;
  }
  return getFriendCouponList(newParams);
};

// 打开赠送对话框
const openGiftDialog = () => {
  giftDialogVisible.value = true;
  loadFriendList();
  loadCouponList();
  // 点击下拉框时才会加载数据（通过 @focus 事件触发）
};

// 关闭赠送对话框
const closeGiftDialog = () => {
  giftDialogVisible.value = false;
  giftFormRef.value?.resetFields();
  Object.assign(giftFormData, {
    friendId: "",
    couponId: "",
    quantity: 1
  });
  // 重置加载状态，下次打开时重新加载
  friendListLoaded.value = false;
  couponListLoaded.value = false;
};

// 优惠券改变时
const handleCouponChange = (val: string) => {
  giftFormData.quantity = 1;
};

// 提交赠送
const handleGiftSubmit = async () => {
  if (!giftFormRef.value) return;

  await giftFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 调用赠送接口
        const params = {
          couponIds: [
            {
              couponId: giftFormData.couponId,
              singleQty: giftFormData.quantity
            }
          ],
          friendStoreUserId: String(giftFormData.friendId)
        };

        const res: any = await setFriendCoupon(params);

        if (res && res.code === 200) {
          ElMessage.success("赠送成功");
          closeGiftDialog();
          proTable.value?.getTableList();
        } else {
          ElMessage.error(res?.msg || "赠送失败");
        }
      } catch (error: any) {
        console.error("赠送失败:", error);
        ElMessage.error(error?.message || "赠送失败");
      }
    }
  });
};

// 查看详情：整行写入 sessionStorage，详情页直接展示，不调接口
const FRIEND_COUPON_DETAIL_ROW_KEY = "friendCoupon_detail_row";

const viewDetail = (row: any) => {
  try {
    sessionStorage.setItem(FRIEND_COUPON_DETAIL_ROW_KEY, JSON.stringify(row ?? {}));
  } catch (e) {
    console.error(e);
    ElMessage.warning("无法缓存行数据，请重试");
    return;
  }
  const query: Record<string, string> = { type: String(activeName.value || "") };
  if (row?.voucherId != null && row.voucherId !== "") {
    query.voucherId = String(row.voucherId);
  } else if (row?.couponId != null && row.couponId !== "") {
    query.couponId = String(row.couponId);
  }
  if (row?.storeId != null && row.storeId !== "") query.storeId = String(row.storeId);
  router.push({
    path: "/dynamicManagement/friendCouponDetail",
    query
  });
};

// 删除行数据
const deleteRow = (row: any) => {
  ElMessageBox.confirm("确定要删除这条赠送记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        // TODO: 集成真实接口时，取消下面的注释
        // await deleteFriendCoupon({ id: row.id });

        ElMessage.success("删除成功");
        proTable.value?.getTableList();
      } catch (error) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 页面加载时触发查询
onMounted(() => {
  proTable.value?.getTableList();
});
</script>

<style lang="scss" scoped>
.friend-coupon-container {
  .table-header-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
    .header-tabs {
      :deep(.el-tabs__nav-wrap::after) {
        height: 0;
      }
    }
    .header-button {
      display: flex;
      justify-content: flex-start;
    }
  }
  .coupon-info {
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
  }
  .dialog-footer {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }
}
</style>
