import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import tickleBehavior, {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";
import {
  getOrderDetailMethod,
  orderPayMethod,
  orderCancelMethod,
  orderConfirmMethod,
} from "../../request";
// module/article/pages/order-detail/order-detail.ts
Page({
  behaviors: [PageContainerBehavior, tickleBehavior],
  onLoad(options: any) {
    console.log(options, "options");
    if (options.id) {
      this.setData({ id: options.id });
    }
  },
  properties: {},
  data: {
    showDetail: false,
    id: "",
    showConfirm: false,
    url: "https://pic.nximg.cn/file/20190718/28170468_214109363000_2.jpg",
    dialogKey: "",
    totalPrice: 0,
    orderStatus: "", // 'pending' | 'received' | 'completed' | ''
    orderDetail: {},
    address: "",
    name: "",
    phone: "",
    // selectedAddress: null,
    // 节流控制
    isPaymentLoading: false,
    isConfirmLoading: false,
  },
  // 切换收货地址
  changeAddress(event: any) {
    const orderStatus = event.currentTarget.dataset.status;
    // 根据订单状态判断是否可以切换地址. 待支付状态下可以切换地址
    if (orderStatus === "0") {
      wx.navigateTo({
        url:
          "/module/article/pages/manage-address/manage-address?type=orderDetail&orderId=" +
          this.data.id,
      });
    }
  },
  // 订单支付
  async payment() {
    if (this.data.isPaymentLoading) {
      return;
    }

    this.setData({ isPaymentLoading: true });

    try {
      await orderPayMethod(this.data.id);
      wx.redirectTo({
        url: "/module/article/pages/success-page/success-page?title=订单支付成功",
      });
    } catch (error: any) {
      wx.showToast({
        title: error.errMsg,
        icon: "none",
      });
    } finally {
      this.setData({ isPaymentLoading: false });
    }
  },
  statusType(status: any) {
    const code = status == null ? "" : String(status);
    switch (code) {
      case "0":
        this.setData({ orderStatus: "pending" });
        break;
      case "6":
        this.setData({ orderStatus: "received" });
        break;
      case "2":
        this.setData({ orderStatus: "closed" });
        break;
      case "345":
        this.setData({ orderStatus: "completed" });
        break;
      default:
        this.setData({ orderStatus: "" });
        break;
    }
  },
  // 订单详情
  async load(id: string) {
    wx.showLoading({ title: "加载中" });
    try {
      const res = await getOrderDetailMethod(id);
      if (res && res.data) {
        this.setData({ orderDetail: res.data });
        if (
          !res.data.liaison ||
          !res.data.phone ||
          !res.data.provinceName ||
          !res.data.cityName ||
          !res.data.areaName ||
          !res.data.detailAddress
        ) {
          this.setData({
            showDetail: true,
          });
        } else {
          this.setData({
            showDetail: false,
          });
          this.setData({
            name: res.data.liaison ? `${res.data.liaison}` : "",
            phone: res.data.phone ? `${res.data.phone}` : "",
            address: `${res.data.provinceName}${
              res.data.cityName ? `${res.data.cityName}` : ""
            }${res.data.areaName ? `${res.data.areaName}` : ""}${
              res.data.detailAddress ? `${res.data.detailAddress}` : ""
            }`,
          });
        }
        // 0：待付款
        // 2 交易关闭
        // 6 待收货
        // 345  交易成功
        this.statusType(res.data.orderStatus);
        const totalPrice = res.data.items.reduce(
          (acc: number, item: any) => acc + item.totalPrice,
          0
        );
        this.setData({ totalPrice });
      }
    } catch (error: any) {
      wx.showToast({
        title: error.errMsg,
        icon: "none",
      });
    }
    wx.hideLoading();
  },
  closeDialog() {
    this.setData({ showConfirm: false });
  },
  async confirmDialog() {
    const that = this;
    wx.showModal({
      title: "提示",
      content: "确认取消该订单吗？",
      success: (res) => {
        if (res.confirm) {
          that.cancelOrdering();
        }
      },
    });
  },
  // 取消订单
  async cancelOrdering() {
    try {
      await orderCancelMethod(this.data.id);
      this.setData({ showConfirm: false });
      wx.navigateTo({
        url: "/module/article/pages/success-page/success-page?title=订单取消成功",
      });
    } catch (error: any) {
      wx.showToast({
        title: error.errMsg,
        icon: "none",
      });
    }
  },
  // 取消订单
  async cancelOrder() {
    this.setData({ showConfirm: true });
  },
  // 查看物流
  viewLogistics() {
    wx.showToast({
      title: "暂未开通",
      icon: "none",
    });
    // 物流接口现在没有 先空着
    // wx.navigateTo({ url: "/module/article/pages/see-logistics/see-logistics" });
  },
  // 确认收货
  async confirmReceipt() {
    if (this.data.isConfirmLoading) {
      return;
    }

    this.setData({ isConfirmLoading: true });

    const orderId = this.data.id;
    wx.navigateTo({
      url: `/module/article/pages/confirm-receiving/confirm-receiving?orderId=${orderId}`,
    });

    // 延迟重置loading状态，给页面跳转一些时间
    setTimeout(() => {
      this.setData({ isConfirmLoading: false });
    }, 2000);

    // let that = this;
    // wx.showModal({
    //   title: "提示",
    //   content: "确认收货后，订单将无法修改，请确认无误后再进行操作",
    //   success: (res) => {
    //     if (res.confirm) {
    //       that.confirmReceiving();
    //     }
    //   },
    // });
  },
  async confirmReceiving() {
    try {
      await orderConfirmMethod(this.data.id);
      wx.navigateTo({
        url: "/module/article/pages/success-page/success-page?title=确认收货成功",
      });
      // 物流接口现在没有 先空着
      // wx.navigateTo({
      //   url: "/module/article/pages/confirm-receiving/confirm-receiving",
      // });
    } catch (error: any) {
      wx.showToast({
        title: error.errMsg,
        icon: "none",
      });
    }
  },
  onShow() {
    if(this.data.id){ 
      this.load(this.data.id);
    }
  },
});
