import {
  status,
  nurseOrderStatusMap,
  operationsEnum,
} from "../../../utils/enumMap";
import {
  fhGetNurseOrder,
  fhPayNurseOrders,
  fhCancelNurseOrders,
} from "../../../api/hospital/index";
const baseUrl = require("../../../api/index.js").config;
const order = require("../../../api/order.js");
const share = require("../../../api/share.js");
const map = require("../../../utils/enumMap.js");
import { Tips, ToShare } from "../../../utils/util";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderid: "",
    orderInfo: [],
    foodlist: [],
    statusToCNMap: {},
    riderlist: [],
    typeToCNMap: {},
    delieryToCNMap: {},
    show: false,
    ordertype: "",
    mentionlist: [],
    // 分享有礼
    active: "",
    activeflag: false,
    // 菜单
    funs: [],
    orderStatus: status,
    loading: true,
    // 待支付
    totalMicroSecond: "",
    clock: "",
    // 订单类型
    orderType: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { orderId, type } = options;

    this.tempNavInfo = options;

    this.setData({
      orderid: orderId,
      orderType: type,
      statusToCNMap: map.orderStatus(),
      typeToCNMap: map.orderType(),
      delieryToCNMap: map.deliveyType(),
      orderStatus: type === "shitang" || type === "patient" ? status : nurseOrderStatusMap,
    });
    // 当前订单类型
    this.tempType = type;
    type === "nurse" ? this.getNurseOrder() : this.refreshCurrent();
  },
  // 页面加载完成
  onReady() {
    this.orderStepModal = this.selectComponent("#order-step-modal");
  },
  // 分享活动
  takeActive: function () {
    var that = this;
    var memberId = wx.getStorageSync("memberId");
    order.takeActivity(
      baseUrl.waimaiUrl + "/client/" + memberId + "/share/activity",
      {},
      {},
      "加载中",

      function (res) {
        var result = res.results;
        if (!result && typeof result != "undefined" && result != 0) {
          that.setData({
            activeflag: false,
          });
        } else {
          that.setData({
            activeflag: true,
            active: result,
          });
        }
        that.setData({
          active: result,
        });
      },
      function (err) {
        wx.showToast({
          title: "失败",
        });
      }
    );
  },
  // 新分享功能
  takeActiveimg: function () {
    var that = this;
    share.getShareactiveimg(
      baseUrl.baseUrl + "/mini/share-activity/image",
      {},
      {},
      "加载中",

      function (res) {
        var result = res.results;
        if (!result && typeof result != "undefined" && result != 0) {
          that.setData({
            activeflag: false,
          });
        } else {
          that.setData({
            activeflag: true,
            active: result,
          });
        }
        that.setData({
          active: result,
        });
      },
      function (err) {
        wx.showToast({
          title: "失败",
        });
      }
    );
  },
  // 申请退款
  applyMoney: function (e) {
    var that = this;
    const item = that.data.orderInfo;
    wx.setStorageSync("refundData", item);
    wx.$routerTo({
      url: "/package/good/refund/refund",
      query: { ...item, type: this.data.orderType },
    });
  },
  ringUp: function (e) {
    var that = this;
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
    });
  },
  // 催单
  takeReminder: function (e) {
    var that = this;
    var memberId = wx.getStorageSync("memberId");
    order.getReminder(
      baseUrl.waimaiUrl +
        "/client/" +
        memberId +
        "/order/" +
        that.data.orderid +
        "/reminder",
      {},
      {},
      "加载中",
      function (res) {
        if (res.code == 200) {
          wx.showToast({
            title: "催单成功",
            icon: "none",
          });
        }
      },
      function (err) {
        wx.showToast({
          title: "失败",
        });
      }
    );
  },
  // 跳转商家门店
  jumpSaleroom: function (e) {
    var that = this;
    var storeid = e.currentTarget.dataset.storeid;
    wx.setStorageSync("storeid", storeid);
    wx.navigateTo({
      url: "/store/pages/lunch/index",
    });
  },
  takeProcess: function () {
    var that = this;
    that.setData({
      show: true,
    });
  },
  // 当前数据刷新
  refreshCurrent: function () {
    var that = this;
    var memberId = wx.getStorageSync("memberId");
    this.setData({
      loading: true,
    });
    const api = this.tempType === 'shitang' ? 'shitang' : 'waimai'
    order.takeCurrentdetail(
      baseUrl.waimaiUrl +
        "/client/" +
        memberId +
        `/order/${api}/` +
        that.data.orderid,
      {},
      {},
      "加载中",
      function (res) {
        var result = res.results;
        that.compoutedOperations(result);
        const orderStatusText = that.compoutedStatusText(result);
        const { createTime, orderStatus, refundStatus, expectedTime } = result;
        orderStatus === 1 && that.evokePayCountDown(createTime);

        const orderTipText =
          refundStatus === 601
            ? "请耐心等待商家处理"
            : [7, 302].includes(orderStatus)
            ? "感谢您的信任，期待再次光临！"
            : expectedTime
            ? `计划${expectedTime}送达`
            : "";

        if (result.orderProgress.length > 0) {
          for (var i = 0; i < result.orderProgress.length; i++) {
            result.orderProgress[i].operationTime =
              result.orderProgress[i].operationTime.slice(5);
            result.orderProgress[i].orderStatus =
              map.orderJournal()[result.orderProgress[i].orderStatus];
          }
        }

        that.setData({
          orderInfo: { ...result, orderTipText, orderStatusText },
          mentionlist: result.cabOrderInfo,
          foodlist: result.foodItemVoList,
          statusToCNMap: map.orderStatus(),
          riderlist: result.riderInfoDto,
          typeToCNMap: map.orderType(),
          delieryToCNMap: map.deliveyType(),
          ordertype: result.orderType,
          loading: false,
        });
        wx.stopPullDownRefresh();
      },
      function (err) {
        this.setData({
          loading: false,
        });
        wx.stopPullDownRefresh();
      }
    );
  },
  // 下拉刷新
  onPullDownRefresh: function () {
    // this.refreshCurrent();
    this.tempType === "nurse" ? this.getNurseOrder() : this.refreshCurrent();
  },
  ToShare,
  clickFun({ currentTarget: { dataset } }) {
    const { type } = dataset;
    switch (type) {
      case "refund":
        this.applyMoney();
        break;
      case "payment":
        this.goPaid();
        break;
      case "cancel":
        this.takeCancel();
        break;
      case "callMerchant":
        const { storePhone } = this.data.orderInfo;
        if (storePhone && storePhone !== "暂无电话") {
          this.phoneCall(storePhone);
        } else {
          Tips("获取商家电话失败，请联系平台管理员");
        }
        break;
      case "callRider":
        const { riderInfoDto } = this.data.orderInfo;
        const { riderPhone } = riderInfoDto;
        if (riderPhone && riderPhone !== "暂无电话") {
          this.phoneCall(riderPhone);
        } else {
          Tips("获取骑手电话失败，请联系商家");
        }
        break;
      case "callDeliveryNurse":
      case "callNurse":
        const { nursePhone } = this.data.orderInfo;
        if (nursePhone && nursePhone !== "暂无电话") {
          this.phoneCall(nursePhone);
        } else {
          Tips("获取取货护工电话失败，请联系商家");
        }
        break;
      case "againOrder":
        this.againOrder();
        break;

      default:
        break;
    }
  },
  // 唤起电话
  phoneCall(phone) {
    wx.makePhoneCall({
      phoneNumber: phone,
    });
  },
  /* 毫秒级倒计时 */
  countDown: function () {
    // 渲染倒计时时钟
    var that = this;
    that.setData({
      clock: that.dateFormat(that.data.totalMicroSecond),
    });

    if (that.data.totalMicroSecond <= 0) {
      Tips("超过15分钟未支付，订单将自动取消");
      that.setData(
        {
          clock: "已经截止",
        },
        () => {
          setTimeout(() => {
            wx.$routerTo({
              url: "/pages/order/list/index",
              type: "reLaunch",
              query: {
                ...this.tempNavInfo,
              },
            });
          }, 1000 * 1.5);
        }
      );

      return;
    }

    setTimeout(function () {
      // 放在最后--
      that.setData({
        totalMicroSecond: that.data.totalMicroSecond - 1000,
      });
      that.countDown();
    }, 1000);
  },

  // 时间格式化输出，如03:25:19 86。每10ms都会调用一次
  dateFormat: function (micro_second) {
    // 分钟位
    var min = this.fillZeroPrefix(Math.floor(micro_second / 60000));
    // 秒位
    var sec = this.fillZeroPrefix(
      Math.floor((micro_second - min * 60000) / 1000)
    ); // equal to => var sec = second % 60;
    return min + ":" + sec + " ";
  },

  // 位数不足补零
  fillZeroPrefix: function (num) {
    return num < 10 ? "0" + num : num;
  },

  // 去支付
  goPaid: function (e) {
    this.data.orderType === "nurse"
      ? this.payNurseOrders()
      : this.payWechat(this.data.orderInfo.orderId);
  },

  // 微信支付
  payWechat: function (id) {
    var that = this;
    var memberId = wx.getStorageSync("memberId");
    order.takePayment(
      baseUrl.waimaiUrl + `/client/${memberId}/order/${id}/pay`,
      {},
      {
        payType: 1,
      },
      "加载中",
      function (res) {
        var result = res.results;
        that.evokeWechatPay(result);
      },
      function (err) {
        wx.showToast({
          title: "支付失败，请重试",
        });
        that.setData({
          payflag: false,
        });
      }
    );
  },

  // 唤起微信支付
  evokeWechatPay(info) {
    const { prepayId } = info;
    wx.requestPayment({
      ...info,
      package: prepayId,
      success: (res) => {
        wx.showToast({
          title: "支付成功",
          duration: 1000,
          mask: true,
          success: () => {
            setTimeout(() => {
              wx.$routerTo({
                url: "/package/good/successpage/successpage",
                type: "reLaunch",
                query: {
                  type: this.data.orderType,
                  orderid: this.data.orderid,
                  price: this.data.price,
                },
              });
            }, 1000); //延迟时间
          },
        });
      },
      fail: (res) => {
        this.setData({
          payflag: false,
        });
        wx.showToast({
          title: "取消支付",
          icon: "error",
          duration: 800,
          success: function () {},
        });
      },
    });
  },

  // 取消订单
  // TODO 添加二次确认弹窗
  takeCancel: function (e) {
    const { orderType } = this.data;
    var that = this;
    var memberId = wx.getStorageSync("memberId");
    orderType === "nurse"
      ? this.fhCancelNurseOrders()
      : order.takeCancel(
          baseUrl.waimaiUrl +
            "/client/" +
            memberId +
            "/order/" +
            that.data.orderInfo.orderId +
            "/cancel",
          {},
          {},
          "加载中",
          function (res) {
            Tips("取消订单成功");
            setTimeout(() => {
              wx.$routerTo({
                url: "/pages/order/list/index",
                type: "reLaunch",
                query: {
                  ...this.tempNavInfo,
                },
              });
            }, 1000 * 1.5);
          },
          function (err) {
            wx.showToast({
              title: "失败",
            });
          }
        );
  },

  // 未支付倒计时
  evokePayCountDown(createTime) {
    const diff =
      15 * 60 * 1000 -
      (new Date().valueOf() -
        new Date(createTime.replace(/-/g, "/")).valueOf());
    if (diff > 0) {
      this.setData(
        {
          totalMicroSecond: diff,
        },
        () => {
          this.countDown();
        }
      );
    }
  },

  // 获取护工订单的详情
  async getNurseOrder() {
    try {
      const { results } = await fhGetNurseOrder(this.data.orderid);
      this.compoutedOperations(results);
      const orderStatusText = this.compoutedStatusText(results);
      const { createTime, orderStatus } = results;
      orderStatus === 1 && this.evokePayCountDown(createTime);
      this.setData({
        orderInfo: { ...results, orderStatusText },
        loading: false,
      });
    } catch (e) {
      console.log("debug axios", e);
    }
    wx.stopPullDownRefresh();
  },

  // 计算订单当前状态
  compoutedStatusText(info) {
    const { orderStatus, refundStatus } = info;
    const key = (refundStatus !== 603 && refundStatus) || orderStatus;
    return this.data.orderStatus[key];
  },

  // 支付护工订单
  async payNurseOrders() {
    try {
      const { results } = await fhPayNurseOrders(this.data.orderid, {
        payType: 1,
      });
      this.evokeWechatPay(results);
    } catch (e) {
      console.log("debug axios", e);
    }
  },

  // 取消护工订单
  async fhCancelNurseOrders() {
    try {
      await fhCancelNurseOrders(this.data.orderid);
      Tips("取消订单成功");
      setTimeout(() => {
        wx.$routerTo({
          url: "/pages/order/list/index",
          type: "reLaunch",
          query: {
            ...this.tempNavInfo,
          },
        });
      }, 1000 * 1.2);
    } catch (e) {
      console.log("debug axios", e);
    }
  },

  // 计算该订单拥有的操作列表
  compoutedOperations(detail) {
    const { orderType } = this.data;
    const { orderStatus, refundStatus, nurseDeliveryStatus, nurseName } = detail;
    const res = operationsEnum.filter((i) => {
      const { show, all, unshow, orderType: orderTypes, type } = i;
      const typeFlag = orderTypes.includes(orderType);
      const unshowFlag = unshow && Array.isArray(unshow) && unshow.includes(refundStatus);
      const showFlag = all || (Array.isArray(show) && show.includes(orderStatus));

      if (
        type === "callDeliveryNurse" &&
        (!nurseDeliveryStatus || nurseName === "暂未分配护工")
      ) {
        return false;
      }

      if (typeFlag && !unshowFlag && showFlag) {
        return i;
      }
    });
    console.log(res)
    this.setData({
      funs: res,
    });
  },

  // 展示订单进度
  showOrderStepModal() {
    const { orderProgress, orederProgress } = this.data.orderInfo;
    if (!orderProgress && !orederProgress) return;
    this.orderStepModal.showModal();
  },

  // 再来一单
  againOrder() {
    const { storeId, storeLat, storeLon, foodItemVoList } = this.data.orderInfo;
    wx.setStorageSync("groupFood", foodItemVoList);
    wx.setStorageSync("latitude", storeLat);
    wx.setStorageSync("longitude", storeLon);
    wx.setStorageSync("storeid", storeId);
    wx.nextTick(() => {
      wx.$routerTo({
        url: "/package/good/affirm/affirm",
        query: {
          storeid: storeId,
          currentflag: 1,
          addressflag: 1,
        },
      });
    });
  },

  // 查看详情大图
  previewImage(images) {
    wx.previewImage({
      current: images[0], // 当前显示图片的http链接
      urls: images, // 需要预览的图片http链接列表
    });
  },

  // 查看取货点
  checkPickImg({ currentTarget: { dataset } }) {
    let { images } = dataset;
    if (images && !Array.isArray(images)) {
      images = [images];
    }
    this.previewImage(images);
  },
});
