import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import tickleBehavior, {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";
import { getAddressListMethod, orderPayAddressMethod } from "../../request";
// module/diet/pages/delivery-address/delivery-address.ts
Page({
  behaviors: [PageContainerBehavior, tickleBehavior],

  properties: {},
  data: {
    addressList: [], // 当前展示的列表
    allAddressList: [], // 原始完整列表
    selectedIndex: -1,
    searchValue: "",
    noResult: false, // 新增
    type: "",
    orderId: "",
  },
  onLoad(options: any) {
    if (options.type) {
      this.setData({ type: options.type });
      wx.setStorageSync("type", options.type);
    }
    if (options.orderId) {
      this.setData({ orderId: options.orderId });
      wx.setStorageSync("orderId", options.orderId);
    }
  },
  // 更新订单地址
  async updataOrderAddress(id: string, address: any) {
    const data = {
      provinceName: address.provinceName,
      provinceCode: address.provinceCode,
      cityName: address.cityName,
      cityCode: address.cityCode,
      areaName: address.areaName,
      areaCode: address.areaCode,
      detailAddress: address.detailAddress,
      liaison: address.liaison,
      phone: address.phone,
    };
    await orderPayAddressMethod(id, data);
  },
  // 选择地址
  async selectAddress(e: any) {
    const item = e.currentTarget.dataset.item;
    const type = wx.getStorageSync("type");
    const orderId = wx.getStorageSync("orderId");
    const pages = getCurrentPages();


    const findTargetPageIndex = (targetRoute: string) => {
      for (let i = pages.length - 1; i >= 0; i--) {
        if (pages[i].route === targetRoute) {
          return pages.length - 1 - i; // 需要返回的层级数
        }
      }
      return -1;
    };

    if (type === "orderDetail") {
      // 订单详情 切换地址
      try {
        await this.updataOrderAddress(orderId, item);
        const targetRoute = "module/order/pages/order-detail/order-detail";
        const delta = findTargetPageIndex(targetRoute);
        if (delta > 0) {
          // 返回到目标页面
          wx.navigateBack({ delta });
        } else {
          // 如果找不到目标页面，返回到上一页
          wx.navigateBack();
        }
      } catch (error: any) {
        getTickleContext.call(this).showWarnMessage(error.errMsg);
      }
    } else if (type === "orderList") {
      // 订单列表 切换地址
      try {
        await this.updataOrderAddress(orderId, item);
        const targetRoute = "module/article/pages/order-list/order-list";
        const delta = findTargetPageIndex(targetRoute);
        if (delta > 0) {
          wx.navigateBack({ delta });
        } else {
          wx.navigateBack();
        }
      } catch (error: any) {
        getTickleContext.call(this).showWarnMessage(error.errMsg);
      }
    } else if (type === "confirmeOrder") {
      wx.setStorageSync('selectedAddress', item);
      // 确认订单页面 切换地址
      const confirmeOrderPage = pages.find(
        (page: any) =>
          page.route === "module/order/pages/confirme-order/confirme-order"
      );
      if (confirmeOrderPage) {
        wx.redirectTo({
          url: "/" + confirmeOrderPage.route + "?isDefault=1",
        });
      }
    } else {
      // 其他页面 切换地址
    }
  },
  // 搜索
  onSearchChange(e: any) {
    const keyword = (e.detail.value || "").trim().toLowerCase();
    const allList = this.data.allAddressList || [];
    if (!keyword) {
      this.setData({ addressList: allList, noResult: false });
      return;
    }
    const filtered = allList.filter(
      (item: any) =>
        (item.liaison || "").toLowerCase().includes(keyword) ||
        (item.phone || "").toLowerCase().includes(keyword) ||
        (item.fullAddress || "").toLowerCase().includes(keyword)
    );
    this.setData({
      addressList: filtered,
      noResult: filtered.length === 0,
    });
  },
  // 编辑地址
  onEdit(e: any) {
    const id = e.currentTarget.dataset.id;
    // 跳转编辑
    wx.navigateTo({
      url: `/module/article/pages/add-address/add-address?id=${id}&type=${this.data.type} `,
    });
  },
  // 新增地址
  onAddress() {
    // 新增地址逻辑
    wx.navigateTo({
      url:
        "/module/article/pages/add-address/add-address?type=" + this.data.type,
    });
  },
  async load() {
    wx.showLoading({ title: "加载中" });
    try {
      // 获取所有的地址列表
      const res = await getAddressListMethod("", "");
      if (res && res.length > 0) {
        res.forEach((item: any) => {
          item.fullAddress = `${item.provinceName} ${item.cityName} ${item.areaName} ${item.detailAddress}`;
          item.tag = item.tagList[0] || "";
        });
        this.setData({
          noResult: false,
          addressList: res, // 当前展示
          allAddressList: res, // 原始
        });
      } else {
        this.setData({
          noResult: true,
          addressList: [],
          allAddressList: [],
        });
      }
    } catch (error: any) {
      getTickleContext.call(this).showWarnMessage(error.errMsg);
    }
    wx.hideLoading();
  },
  // 导入微信地址
  onImportWechatAddress() {
    wx.chooseAddress({
      success: (res) => {
        // 拼接参数
        const params = encodeURIComponent(
          JSON.stringify({
            liaison: res.userName,
            phone: res.telNumber,
            region:
              res.provinceName + " " + res.cityName + " " + res.countyName,
            provinceName: res.provinceName,
            cityName: res.cityName,
            areaName: res.countyName,
            detailAddress: res.detailInfoNew,
          })
        );
        wx.navigateTo({
          url: `/module/article/pages/add-address/add-address?imported=${params}`,
        });
      },
      fail: () => {
        wx.showToast({ title: "导入失败或用户取消", icon: "none" });
      },
    });
  },
  onShow() {
    // 加载地址列表
    this.load();
  },
});
