<script lang="ts" setup>
import { ref } from 'vue';
import Taro from '@tarojs/taro';
import Pay from '@/components/Pay.vue';
import { getActiveOrderList, deleteActiveOrder } from '@/api/goods';
import { getOrderStatistics } from '@/api/order';
import UQRCode from 'uqrcodejs';

const tabValue = ref(0);

const isShowPay = ref(false);
const isShowCode = ref(false);
const url = ref('');

const tabsList = ref([
  {
    title: '全部',
    value: 0,
    num: 0,
  },
  {
    title: '待付款',
    value: 1,
    num: 0,
  },
  {
    title: '待使用',
    value: 2,
    num: 0,
  },
  {
    title: '已使用',
    value: 3,
    num: 0,
  },
  {
    title: '已失效',
    value: 4,
    num: 0,
  },
]);

const jfInfo = ref({});

interface OrderList {
  oid: string;
  add_time: string;
  status: number;
  Store: {
    bid: string;
  };
  OrderGoods: GoodsItem[];
  count: number;
  number: number;
  pay_type: number;
  exchange: number;
  price: number;
  joint_oid: string;
  bid: string;
  discount_price: number;
  discount_integral: number;
}

interface GoodsItem {
  Goods: {
    name: string;
    cover: string;
    discount_price: number;
    exchange: number;
  };
  ID: number;
  gid: string;
  number: number;
  oid: string;
  pay_integral: number;
  pay_price: number;
}

const orderList = ref<OrderList[]>([]);

Taro.useLoad(options => {
  tabValue.value = Number(options.type);
});

Taro.useDidShow(() => {
  getList();
});

// Taro.startPullDownRefresh({
//   success: () => {
//     getList();
//   },
// });

const getList = async () => {
  try {
    const res = await getActiveOrderList({
      status: tabValue.value,
    });
    orderList.value = res.data.data;
  } catch (error) {
    Taro.showToast({
      title: error.msg,
      icon: 'none',
    });
  }
  // await getTj();
  // Taro.stopPullDownRefresh();
};

const tabChange = (index: number) => {
  tabValue.value = index;
  getList();
};

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

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

const successPay = () => {
  isShowPay.value = false;
  jfInfo.value = {};
  getList();
};

const toDetail = (item: any) => {
  Taro.navigateTo({
    url: `/pages/users/order_list_detail/index?orderId=${item.oid}&OrderType=2`,
  });
};

const delOrder = async (oid: string) => {
  try {
    await deleteActiveOrder({ oid });
  } catch (error) {
    Taro.showToast({
      title: error.msg,
      icon: 'none',
    });
  }
  await getList();
};

const t_id = ref();

const openCode = item => {
  if (item.status === 2) return;
  // url.value = `https://api.pwmqr.com/qrcode/create?url=${item.oid}`;
  // 获取uQRCode实例
  const qr = new UQRCode();
  // 设置二维码内容
  qr.data = item.oid;
  // 设置二维码大小，必须与canvas设置的宽高一致
  qr.size = 200;
  // 调用制作二维码方法
  qr.make();
  // 获取canvas元素
  const ctx = Taro.createCanvasContext('qrcode');
  // 设置uQRCode实例的canvas上下文
  qr.canvasContext = ctx;
  // 调用绘制方法将二维码图案绘制到canvas上
  qr.drawCanvas();
  isShowCode.value = true;
  t_id.value = setInterval(() => {
    checkStatus(item);
  }, 1000);
};

const checkStatus = async itm => {
  await getList();
  orderList.value.forEach(item => {
    if (item.oid === itm.oid) {
      console.log(item);
      if (item.status === 2) {
        clearInterval(t_id.value);
        isShowCode.value = false;
        url.value = '';
        Taro.showToast({
          title: '核销成功',
          icon: 'none',
        });
      }
    }
  });
};

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

<template>
  <view>
    <!-- <view class="topTips">
      <view>
        <view style="font-weight: bold">订单信息</view>
        <view style="font-size: 15px"
          >总消费积分：{{ countInfo.ExchangeTotal || 0 }}
        </view>
        <view style="font-size: 15px"
          >总消费金额：{{ countInfo.PriceTotal || 0 }}
        </view>
      </view>
      <image src="../static/user/order_list_top.png" />
    </view> -->
    <view class="tabs-box">
      <view v-for="item in tabsList" :key="item.value" @click="tabChange(item.value)">
        <view class="text" :style="{
          color: tabValue === item.value ? '#000' : '#9C9C9C',
        }">{{ item.title }}
        </view>
        <!-- <view>{{ item.num }}</view> -->
        <view class="line" :class="{ lineColor: item.value === tabValue }"></view>
      </view>
    </view>
    <view v-if="orderList.length > 0">
      <view class="order-card" v-for="(item, index) in orderList" :key="index" @click="toDetail(item)">
        <view class="top">
          <view class="text-[#9C9C9C] text-[28px]">订单号：{{ item.oid }}</view>
          <view :style="{
            color:
              item.status === 0
                ? '#FF850A'
                : item.status === 1
                  ? '#F83D3D'
                  : item.status === 2
                    ? '#333333'
                    : '#9C9C9C',
          }">{{
            item.status === 0
              ? '待付款'
              : item.status === 1
                ? '待使用'
                : item.status === 2
                  ? '已使用'
                  : '已失效'
          }}
          </view>
        </view>
        <view class="line"></view>
        <view class="center" v-for="(itm, idx) in item.OrderGoods" :key="idx">
          <view class="top">
            <image :src="itm.Goods.cover" />
            <view class="flex flex-col justify-between flex-1">
              <view class="title">{{ itm.Goods?.name }}</view>
              <view class="text-[#F83D3D] mt-5">
                <view>{{ itm.Goods.discount_price }}元
                  <text v-if="itm.Goods.exchange > 0">+{{ itm.Goods.exchange }}积分</text>
                </view>
              </view>
            </view>
            <view class="right">
              <view>x{{ itm.number }}</view>
            </view>
          </view>
        </view>
        <!-- <view class="line"></view> -->
        <view class="flex justify-between items-center mt-2 mb-2 text-[25px]" v-if="item.status !== 0"
          style="text-align: right">
          <text class="text-[#9C9C9C] text-[28px]">共{{ item.count }}件商品
          </text>
          <text class="text-[26px]">{{ item.status !== 0 ? '实' : '应' }}付款:
            {{ item.discount_price }} (元)
            <text v-if="item.exchange > 0">积分抵扣: {{ item.exchange }}</text>
          </text>
          <!-- <view class="line"></view> -->
        </view>
        <view class="btn">
          <nut-button v-if="item.status === 0" plain size="mini" type="primary" @click.stop="delOrder(item.oid)">取消订单
          </nut-button>
          <!-- <nut-button
            style="margin-left: 5px"
            size="mini"
            type="primary"
            @click="toDetail(item)"
            >查看详情
          </nut-button> -->
          <nut-button style="margin-left: 5px" size="mini" type="primary" v-if="item.status === 0"
            @click.stop="openPay(item)">立即付款
          </nut-button>
          <nut-button style="margin-left: 5px" size="mini" type="primary" v-if="item.status === 1"
            @click.stop="openCode(item)">出示核销码
          </nut-button>
        </view>
      </view>
    </view>
    <nut-empty v-else description="暂无订单"></nut-empty>
    <!-- 核销码弹窗 -->
    <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 class="qrcode"> -->
        <canvas ref="qrcode" id="qrcode" style="width: 200px; height: 200px" canvas-id="qrcode"></canvas>
        <!-- </view> -->
      </view>
    </nut-popup>
    <pay :isShowPay="isShowPay" :interval="false" :jfInfo="jfInfo" :OrderType="2" @errPay="errPay"
      @successPay="successPay" @closePay="closePay" />
  </view>
</template>

<style lang="scss">
page {
  // IOS安全区域
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.topTips {
  box-sizing: border-box;
  width: 100%;
  background-color: #ff0000;
  color: #ffffff;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  image {
    width: 200px;
    height: 200px;
  }
}

.tabs-box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 20px 20px 0 20px;
  text-align: center;

  .text {
    align-items: center;
    font-size: 30px;
  }

  .line {
    margin: 10px auto;
    width: 50px;
    height: 10px;
    border-radius: 30px;
    transition: all 0.3s ease-in-out;
  }

  .lineColor {
    background-color: #ff0000;
  }
}

.order-card {
  width: 95%;
  box-sizing: border-box;
  margin: 20px auto;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;

  .line {
    width: 100%;
    height: 1px;
    background-color: #f5f5f5;
    margin: 20px auto;
  }

  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .btn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .center {
    .top {
      display: flex;
      align-items: flex-start;

      image {
        width: 150px;
        height: 150px;
        border-radius: 15px;
        margin-right: 20px;
      }

      .title {
        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;
        color: #9c9c9c;
      }
    }
  }
}

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

.qrcode {
  width: 370px;
  height: 370px;
  padding: 10px;
}
</style>
