<template>
  <view class="p-4">
    <!--    步骤条    -->
    <!-- <view class="step-bar">
      <view
        class="item"
        v-for="item in statusList"
        :key="item.id"
        :class="{activation: item.id === goodInfo.status}">
        <view class="text">{{ item.text }}</view>
        <view class="dot"></view>
      </view>
    </view> -->
    <!-- <view v-if="goodInfo.status === 1" class="timeBox">
      订单剩余{{ timeStr }}过期,请尽快核销！
    </view> -->
    <view class="mb-3">
      <view v-if="goodInfo.status === 0">
        <view class="flex text-[#333333] items-center mb-1">
          <view class="font-bold">订单待付款</view>
          <IconFont name="rect-right" size="15" color="#333333"></IconFont>
        </view>
        <view class="text-[#9C9C9C] text-[20px]">订单未支付，请付款</view>
      </view>
      <view v-if="goodInfo.status === 1">
        <view class="flex text-[#333333] items-center mb-1">
          <view class="font-bold">订单待使用</view>
          <IconFont name="rect-right" size="15" color="#333333"></IconFont>
        </view>
        <view class="text-[#9C9C9C] text-[20px]"
          >订单剩余<text class="text-[#FF0000]">{{ timeStr }}</text
          >过期，请尽快核销！</view
        >
      </view>
      <view v-if="goodInfo.status === 2">
        <view class="flex text-[#333333] items-center mb-1">
          <view class="font-bold">订单已使用</view>
          <IconFont name="rect-right" size="15" color="#333333"></IconFont>
        </view>
        <view class="text-[#9C9C9C] text-[20px]">订单已核销，欢迎下次光临</view>
      </view>
      <view v-if="goodInfo.status === 3">
        <view class="flex text-[#333333] items-center mb-1">
          <view class="font-bold">订单失效</view>
          <IconFont name="rect-right" size="15" color="#333333"></IconFont>
        </view>
        <view class="text-[#9C9C9C] text-[20px]">未核销，已失效</view>
      </view>
    </view>
    <!--    商家信息    -->
    <view class="mer-info">
      <image
        class="w-[150px] h-[150px] rounded-lg mr-2"
        :src="goodInfo.Store?.head_photo" />
      <view class="right">
        <view class="text-[#333333]">{{ goodInfo.Store?.name }}</view>
        <view
          class="flex mt-2 items-center text-[#999999] text-[23px] text-ellipsis line-clamp-3">
          <view
            style="font-size: 15px"
            class="iconfont icon-dizhi text-[#C4C4C4]"></view>
          <view>{{ goodInfo.Store?.address }}</view>
        </view>
        <view class="w-full flex items-center justify-between mt-1">
          <view class="ml-3 text-[23px] text-[#999999]"
            >距离您{{
              calculateDistance(
                userLocalNum.t,
                userLocalNum.l,
                Number(goodInfo.Store?.lat),
                Number(goodInfo.Store?.lon),
              )
            }}
          </view>
          <view class="flex items-center">
            <image
              @tap="toPhone()"
              class="w-[50px] h-[50px]"
              src="http://p0.meituan.net/csc/ab0493b124a6bb858bf82a2340767c0d919.png" />
            <image
              @tap="toAdder()"
              class="w-[50px] h-[50px] ml-2"
              src="http://p1.meituan.net/csc/92ee8512c90527169b44e07fd11d250d924.png" />
          </view>
        </view>
      </view>
    </view>

    <!--    订单信息    -->
    <nut-cell-group>
      <nut-cell>
        <template #default>
          <view class="center-box">
            <view
              class="top"
              v-for="(item, index) in goodInfo.OrderGoods"
              :key="index">
              <image :src="item.Goods?.cover" />
              <view class="flex flex-col justify-between flex-1">
                <view class="title">{{ item.Goods?.name }}</view>
                <view class="text-[#F83D3D] mt-5">
                  <view>{{ item.pay_price }}元</view>
                  <view>{{ item.pay_integral }}积分</view>
                </view>
              </view>
              <view class="right">
                <view>x{{ item.number }}</view>
              </view>
            </view>
            <view
              class="flex justify-between items-center mt-2 mb-2 text-[25px]">
              <view class="text-[#9C9C9C]">{{
                `共${goodInfo.count}件商品`
              }}</view>
              <text
                >{{ goodInfo.status !== 0 ? '实' : '应' }}付款{{
                  goodInfo.pay_type === 1 ? '(元): ' : '(积分): '
                }}{{
                  goodInfo.pay_type === 1 ? goodInfo.price : goodInfo.exchange
                }}</text
              >
            </view>
          </view>
        </template>
      </nut-cell>
    </nut-cell-group>
    <nut-cell-group>
      <nut-cell title="订单号:" :desc="goodInfo.oid"></nut-cell>
      <nut-cell
        title="下单时间:"
        :desc="goodInfo.add_time?.slice(0, 19)"></nut-cell>
      <!-- <nut-cell
        v-if="goodInfo.expires !== 0"
        title="订单过期时间:"
        :desc="
          dayjs.unix(goodInfo.expires).format('YYYY-MM-DD HH:mm:ss')
        "></nut-cell> -->
      <nut-cell
        title="订单状态:"
        :desc="
          goodInfo.status === 0
            ? '待付款'
            : goodInfo.status === 1
            ? '待使用'
            : goodInfo.status === 2
            ? '已使用'
            : '已失效'
        "></nut-cell>
    </nut-cell-group>

    <view class="mt-[30px] m-auto">
      <nut-button
        v-if="goodInfo.status === 0"
        shape="square"
        type="primary"
        block
        @click="openPay()"
        >继续付款</nut-button
      >
      <nut-button
        v-if="goodInfo.status === 1"
        shape="square"
        type="primary"
        block
        @click="openCode()"
        >出示核销码</nut-button
      >
    </view>

    <!-- <view class="btn">
      <nut-button
                plain
                v-if="goodInfo.status === 0"
                size="small"
                type="primary"
                >取消订单
            </nut-button>
      <nut-button
        v-if="goodInfo.status === 0"
        style="margin-left: 5px"
        size="small"
        type="primary"
        @click="openPay()"
        >立即付款
      </nut-button>
      <nut-button
        v-if="goodInfo.status === 1"
        style="margin-left: 5px"
        size="small"
        type="primary"
        @click="openCode()"
        >出示核销码
      </nut-button>
    </view> -->

    <!-- 核销码弹窗 -->
    <nut-popup
      v-model:visible="isShowCode"
      position="center"
      style="padding: 20px; border-radius: 15px"
      :maskClosable="true"
      safe-area-inset-bottom
      @click-overlay="closed"
      @closed="closed">
      <view class="code-box">
        <view>核销码</view>
        <image class="qrcode" :src="url"></image>
      </view>
    </nut-popup>
    <pay
      :isShowPay="isShowPay"
      :interval="false"
      :jfInfo="jfInfo"
      :OrderType="2"
      @errPay="errPay"
      @successPay="successPay"
      @closePay="closePay" />
  </view>
</template>

<script setup lang="ts">
import Taro from '@tarojs/taro';
import {onUnmounted, ref} from 'vue';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import Pay from '@/components/Pay.vue';
import {getUserPoint} from '@/api/admin';
import {calculateDistance} from '@/utils';
import {IconFont} from '@nutui/icons-vue-taro';
import {getActiveOrderDetail} from '@/api/goods';

dayjs.extend(duration);

const goodInfo = ref<any>({});

const userLocalNum = ref({
  l: 0,
  t: 0,
});

const isShowCode = ref(false);
const isShowPay = ref(false);
const jfInfo = ref<any>({});

const type = ref('');

const url = ref('');

const oid = ref('');

const tId = ref();

Taro.useLoad(options => {
  type.value = options.type;
  oid.value = options.orderId;
  tId.value = Number(options.OrderType);
  Taro.getLocation({
    type: 'wgs84',
    success: res => {
      userLocalNum.value.l = res.longitude;
      userLocalNum.value.t = res.latitude;
    },
  });
  // goodInfo.value = Taro.getStorageSync('item');
  getOrderDetail();
});

const getOrderDetail = async () => {
  const res = await getActiveOrderDetail({
    oid: oid.value,
    OrderType: tId.value,
  });
  goodInfo.value = res.data.data[0];
  if (goodInfo.value.status === 1) {
    startTime();
  }

  if (goodInfo.value.status === 2 && isShowCode.value) {
    Taro.showToast({
      title: '订单核销完成',
      icon: 'none',
    });
  }
};

const toPhone = () => {
  Taro.makePhoneCall({
    phoneNumber: goodInfo.value.Store.mobile,
  });
};

const toAdder = () => {
  Taro.openLocation({
    latitude: Number(goodInfo.value.Store.lat),
    longitude: Number(goodInfo.value.Store.lon),
    scale: 18,
  });
};

const openPay = async () => {
  // isShowPay.value = true;
  // const mer_info = Taro.getStorageSync('mer_info');
  // const user_info = Taro.getStorageSync('userInfo');
  // const data = await getUserPoint({
  //   phone: user_info.data.phone,
  //   bid: mer_info.bid,
  // });
  // jfInfo.value = {
  //   jh_info: data.data,
  //   oid: Taro.getStorageSync('item').oid,
  // };
  // console.log(goodInfo.value.bid, goodInfo.value.joint_oid);
  Taro.navigateTo({
    url: `/pages/goods/pay/index?oid=${goodInfo.value.joint_oid}&bid=${goodInfo.value.bid}`,
  });
};

const successPay = (val: boolean) => {
  isShowPay.value = val;
  Taro.showToast({
    title: '支付成功',
    icon: 'none',
  });
  Taro.navigateBack({
    delta: 1,
  });
};

const errPay = () => {
  isShowPay.value = false;
  Taro.showToast({
    title: '支付失败',
    icon: 'none',
  });
  jfInfo.value = {};
};
const closePay = () => {
  isShowPay.value = false;
  Taro.showToast({
    title: '支付取消',
    icon: 'none',
  });
  jfInfo.value = {};
};

const t_id = ref();

const openCode = () => {
  if (goodInfo.value.status === 2) return;
  url.value = `https://api.pwmqr.com/qrcode/create?url=${goodInfo.value.oid}`;
  isShowCode.value = true;
  t_id.value = setInterval(() => {
    getOrderDetail();
  }, 1000);
};

const closed = () => {
  isShowCode.value = false;
  url.value = '';
  clearInterval(t_id.value);
};

let timeId: any;

const timeStr = ref('????');

const startTime = () => {
  const nowTime = dayjs();
  const endTime = dayjs(goodInfo.value.expires * 1000);

  // 计算剩余时间的持续时间对象
  const duration = dayjs.duration(endTime.diff(nowTime));

  // 格式化剩余时间
  timeStr.value = duration.format('D天H小时m分钟s秒');

  if (goodInfo.value.expires - dayjs().unix() > 0) {
    clearTimeout(timeId);
    timeId = setTimeout(() => {
      startTime();
    }, 1000);
  }
};

Taro.useUnload(() => {
  clearTimeout(timeId);
  clearInterval(t_id.value);
});

Taro.useDidHide(() => {
  clearTimeout(timeId);
  clearInterval(t_id.value);
});

onUnmounted(() => {
  clearTimeout(timeId);
  clearInterval(t_id.value);
});
</script>

<style lang="scss">
page {
  --nut-cell-desc-color: #999;
  height: 100vh;
  box-sizing: border-box;
  padding-bottom: 100px;
  position: relative;
}

.timeBox {
  text-align: center;
  font-weight: bold;
  font-size: 30px;
  padding: 30px;
}

.step-bar {
  width: 100%;
  height: 100px;
  background: #fff;
  display: flex;

  .item {
    width: 200px;
    height: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: small;

    .dot {
      width: 25px;
      height: 25px;
      border-radius: 50%;
      background: #cecece;
      margin-top: 5px;
    }
  }

  .activation {
    .text {
      color: #ff0000;
    }

    .dot {
      background: #ff0000;
      position: relative;

      &::before {
        content: '';
        width: 15px;
        height: 15px;
        border-radius: 50%;
        background: #fff;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
}

.mer-info {
  background-color: white;
  padding: 15px;
  margin-top: 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-betweenhh;
  align-items: center;
  border-radius: 15px;

  .right {
    color: #858585;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 70%;
  }
}

.btn {
  box-sizing: border-box;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;

  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
}

.center-box {
  display: flex;
  flex-direction: column;
  width: 100%;

  .top {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;

    image {
      width: 150px;
      height: 150px;
      border-radius: 10rpx;
      margin-right: 10px;
    }

    .title {
      margin-left: 10px;
      display: -webkit-box;
      overflow: hidden;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      text-overflow: ellipsis;
      width: 350px;
    }

    .right {
      margin-left: 10px;
      font-size: 28px;
      text-align: right;
    }
  }
}

.code-box {
  padding: 20px;
  box-sizing: border-box;
  text-align: center;
  font-size: large;
}

.qrcode {
  width: 300px;
  height: 300px;
}

.nut-button {
  border-radius: 20px;
}
</style>
