<template>
  <view class="sell-postend">
    <view class="sell-postend-banner"></view>
    <view class="sell-postend-content">
      <view class="withdraw-express">
        <view class="header">
          <view class="header-left">
            <view class="line"></view>
            <view class="title">自主邮寄</view>
          </view>
          <view class="header-right">
            <uni-countdown
              :minute="countdown"
              color="#f8c007"
              @timeup="timeupHandle"
            ></uni-countdown>
          </view>
        </view>
        <view class="item">
          <view class="targe">收</view>
          <view class="address">
            <view
              >{{ appStore.$wxConfig.mailerName }} ：{{
                appStore.$wxConfig.mailerPhone
              }}</view
            >
            <view class="address-detail" style="margin-top: 4px">
              <text class="receive-address">地址:</text>
              {{ appStore.$wxConfig.mailingAddress }}
            </view>
          </view>
          <view class="end">
            <view class="copy" @click="copy">复制</view>
          </view>
        </view>
      </view>
      <view class="upload-box">
        <view class="header">
          <view class="header-left">
            <view class="line"></view>
            <view class="title">上传实物图</view>
          </view>
        </view>
        <view class="upload-tips"
          >上传实物图、包裹图，如有购买凭证（发票、单据） 可以一起上传</view
        >
        <view class="upload-img">
          <view class="upload-box-contanier">
            <up-upload
              :fileList="imageList"
              uploadIcon="plus"
              @afterRead="afterRead"
              @delete="deletePic"
              name="1"
              multiple
              :maxCount="4"
            >
              <template #trigger>
                <view class="upload-block">
                  <uni-icons
                    size="38"
                    color="#ccc"
                    type="plusempty"
                  ></uni-icons>
                </view>
              </template>
            </up-upload>
          </view>
        </view>
        <view class="pz-tips">示例图（产品实物，凭证图片）</view>
        <view class="pz-img">
          <image
            v-for="(item, index) in filelist"
            :key="index"
            :src="item"
          ></image>
        </view>
      </view>
      <view class="postend-info-box">
        <view class="header">
          <view class="header-left">
            <view class="line"></view>
            <view class="title">您的信息</view>
          </view>
        </view>
        <view class="postend-info">
          <view class="info-item">
            <view class="info-item-left">快递单号</view>
            <view class="info-item-right">
              <input
                type="text"
                v-model="expressNum"
                placeholder="请输入快递单号"
              />
              <text class="iconfont icon-iconfontscan" @click="scanCode"></text>
            </view>
          </view>
          <view class="info-agree" @click="showAggre">
            <up-checkbox-group @change="checkboxChange" v-model="isCheck">
              <up-checkbox activeColor="#e9c279" label="确认协议"></up-checkbox>
            </up-checkbox-group>

            <span style="color: #b5aa90; font-size: 16px">《回收协议》</span>
          </view>
        </view>
      </view>
      <view class="recyle-price">
        <view class="recyle-desc">预估回收价</view>
        <view class="recyle-price-num">¥{{ orderInfo.totalMoney }}</view>
      </view>
      <view class="btn-box">
        <!-- <view class="postend-cbtn" @click="cancelOrder">取消订单</view> -->
        <view class="postend-btn" @click="submitOrder">
          <image class="btn" src="/static/images/btn-button.png"></image>
          <text class="btn-text">立即回收</text>
        </view>
      </view>
      <view class="white"></view>
    </view>
    <uni-popup
      ref="singPopup"
      type="bottom"
      borderRadius="10px 10px 0 0"
      maskBackgroundColor="rgba(0,0,0,0)"
    >
      <view class="signContent">
        <scroll-view scrollY class="scroll">
          <up-parse :content="content"></up-parse>
        </scroll-view>
        <view
          class="comfireBtn footer"
          @click="
            isCheck = true;
            $refs.singPopup.close();
          "
        >
          我已详细知悉
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from "vue";
import { useImageUpload } from "@/hooks/useImageUpload";
import { recycleCancelAPI, recyclUpdateAPI } from "@/api/functions";
import { onLoad } from "@dcloudio/uni-app";
import { agreementGetoneApi } from "@/api/user";
import { useAppStore } from "@/stores/app";
const appStore = useAppStore();

// 1. 初始化图片上传钩子
const { imageList, afterRead, deletePic, uploadLoading } = useImageUpload({
  pid: 14,
  model: "recyle",
});
console.log(imageList.value);

// 2. 响应式数据
const pic = ref([]);
const expressNum = ref("");
const singPopup = ref(null);
const isCheck = ref(false);
const content = ref("");
const filelist = ref([
  "https://my-go-easy-im.oss-cn-shenzhen.aliyuncs.com/goeasy-im-%E6%B0%B4%E8%B4%9D%E5%95%86%E5%9F%8E/example/example1.png",
  "https://my-go-easy-im.oss-cn-shenzhen.aliyuncs.com/goeasy-im-%E6%B0%B4%E8%B4%9D%E5%95%86%E5%9F%8E/example/example2.png",
  "https://my-go-easy-im.oss-cn-shenzhen.aliyuncs.com/goeasy-im-%E6%B0%B4%E8%B4%9D%E5%95%86%E5%9F%8E/example/example3.png",
  "https://my-go-easy-im.oss-cn-shenzhen.aliyuncs.com/goeasy-im-%E6%B0%B4%E8%B4%9D%E5%95%86%E5%9F%8E/example/example4.png",
]);
const reqData = ref({}); // 假设从路由参数或其他地方获取
const orderInfo = ref({});
const countdown = ref(999);
// 3. 生命周期
onLoad((options) => {
  if (options.order) {
    countdown.value = getTimeDiff(JSON.parse(options.order).expirationTime);
    orderInfo.value = JSON.parse(options.order);
  }
});
function agreementGetoneFn() {
  // 资产说明
  agreementGetoneApi({ name: "recyle" }).then((res) => {
    content.value = res.data?.content;
  });
}
const checkboxChange = (n) => {
  isCheck.value = true;
};

const showAggre = () => {
  singPopup.value?.open();
  agreementGetoneFn();
};
// 4. 方法
// 扫描快递单号
const scanCode = () => {
  uni.scanCode({
    success: (res) => {
      console.log(res);
      expressNum.value = res.result;
    },
    fail: (err) => {
      uni.showToast({ title: "扫码失败，请重试", icon: "none" });
    },
  });
};

// 复制收件人信息
const copy = () => {
  uni.setClipboardData({
    data: `${appStore.$wxConfig.mailerName}：${appStore.$wxConfig.mailerPhone} 地址: ${appStore.$wxConfig.mailingAddress}`,
    success() {
      uni.showToast({ title: "复制成功", icon: "success" });
    },
    fail: (err) => {
      uni.showToast({
        title: "复制失败",
        icon: "none",
      });
      console.error("复制失败：", err);
    },
  });
};

// 处理图片上传成功
const success = (result) => {
  pic.value.push(result.url);
};

// 提交订单
const submitOrder = async () => {
  if (!isCheck.value) {
    uni.showToast({ title: "请阅读并同意回收协议", icon: "none" });
    return;
  }

  if (imageList.value.length === 0) {
    uni.showToast({ title: "请上传实物图", icon: "none" });
    return;
  }

  if (!expressNum.value.trim()) {
    uni.showToast({ title: "请填写快递单号", icon: "none" });
    return;
  }
  try {
    uni.showLoading({
      title: "下单中",
    });
    // `实际项目中调用接口`
    const res = await recyclUpdateAPI({
      expressNo: expressNum.value,
      images: imageList.value.map((v) => v.info.url),
      orderNo: orderInfo.value.orderNo,
    });

    setTimeout(() => {
      uni.redirectTo({
        url: "/pages/users/vault/recycle/recyle_order",
      });
    }, 0);
    uni.hideLoading();
  } catch (err) {
    uni.showToast({
      title: err?.msg || "下单失败，请稍后重试",
      icon: "none",
    });
    setTimeout(() => {
      uni.redirectTo({
        url: "/pages/users/vault/recycle/recyle_order",
      });
    }, 1000);
  }
};

// 取消订单
const cancelOrder = async () => {
  try {
    const res = await recycleCancelAPI({ orderNo: orderInfo.value.orderNo });
  } catch (err) {
    console.error("取消订单失败:", err);
  }
};

// 订单过期处理
const timeupHandle = () => {
  uni.showToast({
    title: "订单已过期",
    duration: 1000,
    icon: "none",
  });

  // 取消订单
  cancelOrder();

  setTimeout(() => {
    uni.reLaunch({
      url: "/pages/users/vault/recycle/recyle_order",
    });
  }, 1000);
};

// 计算时间差（分钟）
const getTimeDiff = (targetTimeStr) => {
  if (!targetTimeStr) return 0;

  const targetTime = new Date(targetTimeStr).getTime();
  const currentTime = Date.now();
  const diffMs = targetTime - currentTime;
  const diffMinutes = diffMs / 60000;

  return diffMinutes > 0 ? diffMinutes : 0;
};
</script>

<style scoped lang="scss">
.signContent {
  background-color: #f8f8f8;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 20px 20px 0 0;
  .scroll {
    background-color: #fff;
    padding: 4px;
    height: 300px;
    overflow-y: hidden;
    border: 1px solid #dfdfdf;
  }
  .footer {
    margin-top: 10px;
    color: #fff;
    padding: 4px 20px;
    border-radius: 20px;
    background: linear-gradient(to right, #8ed187, #5dd665);
  }
}
.icon-iconfontscan {
  font-size: 20px;
  color: #f8c007;
}
.upload-box-contanier {
  margin-top: 40rpx;
  .upload-block {
    width: 160rpx;
    height: 160rpx;
    border: 1px solid #ccc;
    border-radius: 10rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #ccc;
    font-weight: 700;
    font-size: 26rpx;
  }
}
.sell-postend {
  height: auto;
  padding: 10rpx 30rpx;
  position: relative;

  .sell-postend-banner {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 50vh;
    z-index: -1;
    // background-image: linear-gradient(360deg, #ffffff 0%, #e8c279 100%);
    background: $uni-bg-primary;
  }

  .sell-postend-content {
    display: flex;
    flex-direction: column;
    align-items: center;

    .withdraw-express {
      width: 682rpx;
      height: 306rpx;
      background-color: #ffffff;
      box-shadow: 0rpx 3rpx 13rpx 0rpx rgba(0, 0, 0, 0.13);
      border-radius: 20rpx;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: center;
      box-sizing: border-box;
      padding: 28rpx;
      margin-top: 30rpx;

      .item {
        display: flex;
        align-items: center;
        margin-top: 15px;

        .targe {
          display: flex;
          justify-content: center;
          align-items: center;
          color: #fff;
          width: 35px;
          height: 35px;
          border-radius: 50%;
          background-color: #f8c007;
        }

        .address {
          width: 425rpx;
          margin: 0 10px;
          font-size: 28rpx;

          .receive-address {
            letter-spacing: 9px;
            line-height: 2;
          }
        }

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

          .copy {
            color: #888888;
            border-radius: 3px;
            border: 1px solid #888888;
            font-size: 24rpx;
            padding: 0 23rpx;
          }
        }
      }
    }
    .upload-box {
      width: 682rpx;
      height: auto;
      background-color: #ffffff;
      box-shadow: 0rpx 3rpx 13rpx 0rpx rgba(0, 0, 0, 0.13);
      border-radius: 20rpx;
      box-sizing: border-box;
      margin-top: 25rpx;
      padding: 40rpx 40rpx;
      .upload-tips {
        font-size: 26rpx;
        color: #000000;
        margin: 30rpx 0;
      }
      .upload-img {
        margin: 30rpx 0;
      }
      .pz-tips {
        text-align: center;
        font-size: 24rpx;
        color: #7c7c7c;
        margin: 40rpx 0;
      }
      .pz-img {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        margin: 30rpx 0;
        image {
          width: 138rpx;
          height: 138rpx;
          background-color: #f3f3f3;
          border-radius: 10rpx;
          margin: 15rpx 0;
        }
      }
    }
    .postend-info-box {
      padding: 40rpx 40rpx;
      margin-top: 25rpx;
      width: 682rpx;
      // height: 527rpx;
      background-color: #ffffff;
      box-shadow: 0rpx 3rpx 13rpx 0rpx rgba(0, 0, 0, 0.13);
      border-radius: 20rpx;
      box-sizing: border-box;
      .postend-info {
        margin-top: 30rpx;
        .info-item {
          display: flex;
          align-items: center;
          margin: 25rpx 0;
          .info-item-left {
            font-size: 26rpx;
            color: #000000;
          }

          .info-item-right {
            margin-left: 15rpx;
            width: 470rpx;
            height: 77rpx;
            background-color: #f3f3f3;
            border-radius: 10rpx;
            display: flex;
            // justify-content: space-around;
            align-items: center;
            input {
              width: 86%;
              font-size: 26rpx;
              color: #000;
              padding-left: 15rpx;
            }
          }
        }
        .info-agree {
          display: flex;
          justify-content: center;
          margin-top: 25rpx;
          align-items: center;
        }
      }
    }
    .recyle-price {
      display: flex;
      justify-content: center;
      font-size: 26rpx;
      color: #000000;
      margin: 30rpx 0;
      .recyle-price-num {
        // color: #7c7c7c;
        color: $txt-color;
        margin-left: 15rpx;
      }
    }
    .btn-box {
      display: flex;
      justify-content: center;
      .postend-btn {
        // width: 330rpx;
        width: 267rpx;

        height: 71rpx;
        position: relative;
        margin-top: 30rpx;
        .btn {
          width: 100%;
          height: 100%;
        }
        .btn-text {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          color: #000;
          font-size: 26rpx;
        }
      }
      .postend-cbtn {
        margin-right: 30rpx;
        // width: 330rpx;
        padding: 0rpx 60rpx;
        height: 71rpx;
        background: #cecece;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #636363;
        border-radius: 30rpx;
        margin-top: 30rpx;
      }
    }
    .white {
      height: 100rpx;
    }
    .header {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .header-left {
        display: flex;
        align-items: center;
        .line {
          width: 4rpx;
          height: 28rpx;
          background-color: #cc9933;
        }
        .title {
          margin-left: 5rpx;
          font-weight: bold;
        }
        .tips {
          font-size: 26rpx;
          color: #7c7c7c;
        }
      }
      .header-right {
        font-size: 26rpx;
        color: #7c7c7c;
      }
    }
  }
}
</style>
