<template>
  <view class="deposit-page">
    <view class="top-tabs-container">
      <view
        class="tab-item"
        :class="{ active: activeTab === 'mail' }"
        @click="activeTab = 'mail'"
      >
        邮寄存金
      </view>
      <!-- <view
        class="tab-item"
        :class="{ active: activeTab === 'warehouse' }"
        @click="activeTab = 'warehouse'"
      >
        无物流存金
      </view> -->
    </view>

    <view class="content-body" v-if="activeTab === 'mail'">
      <view class="card-section">
        <view class="section-title">自主邮寄</view>
        <view class="address-box">
          <view class="icon-location">收</view>
          <view class="address-info">
            <view class="info-line"
              >{{ appStore.$wxConfig.mailerName || "回收部" }} |
              {{ contact.phone }}</view
            >
            <view class="info-line">地址 | {{ contact.address }}</view>
          </view>
          <view class="copy-btn" @click="copyAddress">复制</view>
        </view>
      </view>

      <view class="card-section">
        <view class="section-title">快递单号</view>
        <view class="input-row">
          <up-input
            type="text"
            v-model="formData.trackingNumber"
            placeholder="请输入正确的快递单号"
            placeholder-class="placeholder"
            border="none"
          />
          <image class="icon-scan" src="/static/images/scan-icon.png" />
        </view>
      </view>

      <view class="card-section">
        <view class="section-title">快递图片</view>
        <view class="upload-box">
          <up-upload
            :fileList="imageList"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
            multiple
            :maxCount="1"
          >
            <template #trigger>
              <view class="upload-block">
                <uni-icons size="38" color="#ccc" type="plusempty"></uni-icons>
              </view>
            </template>
          </up-upload>
        </view>
      </view>

      <view class="card-section">
        <!-- <template  v-for="metal in metalInputs" > -->
        <view class="input-row with-arrow">
          <text class="input-label">{{ metalTypeText }}克重</text>
          <up-input
            type="digit"
            v-model="formData.weight"
            placeholder="请输入"
            placeholder-class="placeholder"
            class="text-right"
            border="none"
          />
          <text class="arrow">g</text>
        </view>
        <!-- </template> -->
      </view>

      <view class="submit-section">
        <button class="submit-btn" @click="handleSubmit">立即提交</button>
        <!-- 协议选择 -->
        <view
          class="agreement-section"
          style="display: flex; align-items: center"
        >
          <up-checkbox
            v-model:checked="agreedToTerms"
            shape="square"
            activeColor="#e9c279"
            usedAlone
            :customStyle="{ marginRight: '12rpx' }"
          >
            <template #label>
              <text class="agreement-text"> 阅读并同意 </text>
            </template>
          </up-checkbox>
          <view class="agreement-link" @click="showAgreement"
            >《存金协议》</view
          >
        </view>
      </view>
      <!-- 协议弹窗 -->
      <up-popup
        :show="showAgreementPopup"
        mode="center"
        border-radius="20"
        width="80%"
        height="60%"
      >
        <view class="popup-content">
          <view class="popup-header"></view>
          <scroll-view scroll-y scroll-left="50" class="popup-body">
            <view class="agreement-content">
              <Aggrement />
            </view>
          </scroll-view>
          <view class="popup-footer">
            <!-- <button class="popup-btn" @click="closeAgreement">
              我已详细知悉
            </button> -->
            <up-button
              class="popup-btn"
              text="我已详细知悉"
              @click="closeAgreement"
            ></up-button>
          </view>
        </view>
      </up-popup>

      <view class="info-image-section">
        <view class="item-image">
          <!-- <image
            style="width: 100%"
            mode="widthFix"
            src="/static//images/formula.png"
          /> -->
        </view>
        <view class="tip-box">
          <view class="title">温馨提示</view>
          <view class="tip-content"
            >※寄出快递前，客户留底打包视频及快递单号，以便工作人员签收快递核验※</view
          >
        </view>
        <view class="item-image">
          <!-- <image
            style="width: 100%"
            mode="widthFix"
            src="/static/images/gold_table.png"
          /> -->
        </view>
        <view class="text-section">
          <view class="paragraph"
            >1、下午三点前收到寄回包裹当天处理，三点之后统一隔天处理（48小时内打款）</view
          >
          <view class="paragraph"
            >2、如有塑料膜，珐琅、烤漆，镶嵌等辅料，熔烧会产生损耗，按实际熔烧后成色、克重回收；</view
          >
          <view class="paragraph"
            >3、任意时间可提交订单，客服在线时间为早10点~晚8点；</view
          >
          <view class="paragraph"
            >4、如用户担心货品运输风险，建议您保价邮寄。(更多咨询请联系在线客服)；</view
          >
        </view>
        <view class="item-image qr_code">
          <!-- <image
            style="width: 100%"
            mode="widthFix"
            src="/static/images/tpy_qr_code.jpg"
          /> -->
        </view>
        <view class="text-section">
          <view class="paragraph"
            >5、黄金到账时间：通常情况下，在线上平台确认金重后，黄金会实时存入用户贵金属账户中；</view
          >
          <view class="paragraph">6、线上存金，需选择自主邮寄；</view>
          <view class="paragraph"
            >7、足金，K金一定要分开装袋，如熔完后出现因足金K金未分开而造成的成色不足，则需客户自己承担。</view
          >
        </view>
        <view class="alert-text">
          <view class="paragraph">注：周日休息，请错开时间！</view>
          <view class="paragraph"
            >客服热线：19925434991 客服微信：19925434991</view
          >
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useAppStore } from "@/stores/app";
import { useImageUpload } from "@/hooks/useImageUpload";
import Aggrement from "./aggrement.vue";
import { liveExchange } from "@/api/vault";
import { useToast } from "@/hooks/useToast";

// 当前激活的Tab
const activeTab = ref("mail");
const { Toast } = useToast();

const appStore = useAppStore();

const { imageList, afterRead, deletePic, uploadLoading } = useImageUpload({
  pid: 9,
  model: "gold",
});

// 联系人信息 - 从 appStore 获取
const contact = computed(() => ({
  phone: appStore.$wxConfig.mailerPhone,
  address: appStore.$wxConfig.mailingAddress,
}));

// 表单数据
const formData = reactive({
  trackingNumber: "", // 订单号
  imageUrl: "", // 上传的图片URL
  weight: "",
  weights: {
    gold: "",
    kGold: "",
    platinum: "",
    silver: "",
  },
  agreeToTerms: false,
});

// 金属输入项配置
const metalInputs = ref([
  { label: "黄金金重", key: "gold", metalType: 1 },
  { label: "铂金金重", key: "kGold", metalType: 2 },
  { label: "白银金重", key: "platinum", metalType: 3 },
  // { label: "白银金重", key: "silver", metalType: 4 },
]);

//metalType  金属类型（1黄金、2铂金、3白银···）
const metalType = ref(1);
const metalTypeText = computed(() => {
  return metalType.value == 1
    ? "黄金"
    : metalType.value == 2
    ? "铂金"
    : metalType.value == 3
    ? "白银"
    : "";
});

// 复制地址方法
const copyAddress = () => {
  const fullText = `${appStore.$wxConfig.mailerName || "回收部"}：${
    contact.phone
  } 地址: ${contact.address}`;
  uni.setClipboardData({
    data: fullText,
    success: () => {
      Toast({
        title: "地址已复制",
        icon: "none",
      });
    },
  });
};

// 协议弹窗相关逻辑
const showAgreementPopup = ref(false);
const showAgreement = () => {
  showAgreementPopup.value = true;
};
const closeAgreement = () => {
  showAgreementPopup.value = false;
};

// 协议勾选状态
const agreedToTerms = ref(false);

onLoad((p) => {
  metalType.value = p.type;
});
// 提交表单方法
const handleSubmit = async () => {
  if (!agreedToTerms.value) {
    Toast({
      title: "请先阅读并同意存金协议",
      icon: "none",
    });
    return;
  }
  if (!formData.trackingNumber) {
    Toast({
      title: "请填写快递单号",
      icon: "none",
    });
    return;
  }
  if (!formData.weight || Number(formData.weight) <= 0) {
    Toast({
      title: `请填写${metalTypeText.value}金重`,
      icon: "none",
    });
    return;
  }
  if (!imageList.value || imageList.value.length === 0) {
    Toast({
      title: "请上传快递图片",
      icon: "none",
    });
    return;
  }
  if (uploadLoading.value) {
    Toast({
      title: "正在上传图片",
      icon: "none",
    });
    return;
  }
  try {
    uni.showLoading({
      title: "提交中...",
    });
    const params = {
      userId: appStore.uid,
      operationType: 1, // 1 - 存金
      orderNo: formData.trackingNumber,
      weight: formData.weight,
      metalType: metalType.value,
      price: 0,
      type: 1,
      imageUrl: imageList.value[0].info.url,
    };
    await liveExchange(params);
    setTimeout(() => {
      uni.navigateBack();
    }, 500);
    Toast({ title: "提交成功" });
  } catch (error) {
    console.error("liveExchange", error);
    const title = typeof error === "string" ? error : "提交失败";
    Toast({ title });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style lang="scss">
// 页面和主题变量
$page-bg-color: #f7f7f7;
$theme-color: #e9c279;
$text-primary: #333;
$text-secondary: #999;
$white: #ffffff;
$border-color: #f0f0f0;

page {
  background-color: $page-bg-color;
  color: $text-primary;
}

.deposit-page {
  padding-bottom: 40rpx;
}

// 顶部 Tabs
.top-tabs-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  background-color: $white;
  gap: 80rpx;
  border-bottom: 1px solid $border-color;

  .tab-item {
    font-size: 30rpx;
    color: $text-secondary;
    padding-bottom: 10rpx;
    border-bottom: 2px solid transparent;
    transition: all 0.3s ease;

    &.active {
      font-weight: bold;
      color: $theme-color;
      border-bottom-color: $theme-color;
    }
  }
}

.content-body {
  padding: 30rpx;
}

// 卡片样式
.card-section {
  background-color: $white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 24rpx;

  .section-title {
    font-size: 30rpx;
    line-height: 30rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    position: relative;
    padding-left: 20rpx;
    &::before {
      content: "";
      width: 4rpx;
      height: 100%;
      background: #daa520;
      position: absolute;
      left: 0;
      top: 0;
    }
  }
}

.upload-box {
  border-top: 1rpx solid #ccc;
  padding: 50rpx 0 0;
  ::v-deep .u-upload__wrap__preview__image {
    width: 143rpx !important;
    height: 143rpx !important;
  }
  .upload-block {
    width: 150rpx;
    height: 150rpx;
    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;
  }
}

// 地址框
.address-box {
  display: flex;
  align-items: center;
  background-color: #fcf9f3;
  padding: 20rpx;
  border-radius: 12rpx;

  .icon-location {
    width: 70rpx;
    height: 70rpx;
    line-height: 70rpx;
    color: #fff;
    text-align: center;
    background-color: #cc9933;
    border-radius: 50rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
  }

  .address-info {
    flex-grow: 1;
    font-size: 26rpx;
    line-height: 1.6;
  }

  .copy-btn {
    flex-shrink: 0;
    margin-left: 20rpx;
    padding: 10rpx 24rpx;
    border: 1px solid $theme-color;
    color: $theme-color;
    border-radius: 30rpx;
    font-size: 24rpx;
  }
}

// 输入行
.input-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid $border-color;
  padding: 20rpx 0;

  .placeholder {
    color: #cccccc;
  }

  input {
    flex-grow: 1;
    font-size: 28rpx;
  }

  .icon-scan {
    width: 40rpx;
    height: 40rpx;
    margin-left: 20rpx;
  }

  .input-label {
    font-size: 28rpx;
    color: $text-primary;
    margin-right: 15rpx;
  }

  .text-right {
    text-align: right;
  }

  &.with-arrow {
    .arrow {
      font-size: 28rpx;
      color: $header-color;
      margin-left: 10rpx;
    }
  }

  // &:last-child {
  //   border-bottom: none;
  // }
}

// 图片上传
.image-uploader {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed $text-secondary;
  border-radius: 12rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: $text-secondary;
  font-size: 60rpx;
  overflow: hidden;

  .preview-image {
    width: 100%;
    height: 100%;
  }
}

// 提交区域
.submit-section {
  margin-top: 40rpx;

  .submit-btn {
    background-color: $theme-color;
    color: $white;
    border-radius: 50rpx;
    font-size: 32rpx;
    height: 90rpx;
    line-height: 90rpx;
    &:after {
      border: none;
    }
  }

  .agreement-box {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 30rpx;
    font-size: 24rpx;
    color: $text-secondary;
  }
}

.agreement-section {
  margin: 30rpx 0 40rpx;
  display: flex;
  align-items: center;
}

.agreement-text {
  font-size: 28rpx;
  color: #666;
}

.agreement-link {
  color: #e9c279;
  text-decoration: underline;
  margin-left: 4rpx;
}

// 弹窗样式
.popup-content {
  width: 80vw;
  padding: 40rpx 40rpx 0;
  height: 80vh;
  // display: flex;
  // flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;

  .popup-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .popup-close {
    font-size: 48rpx;
    color: #666;
    cursor: pointer;
  }
}

.popup-footer {
  margin-top: 30rpx;

  .popup-btn {
    width: 100%;
    background: #e9c279;
    color: white;
    border: none;
    border-radius: 12rpx;
    padding: 30rpx 30rpx;
    font-size: 32rpx;
  }
}

.popup-body {
  height: 85%;
  // flex: 1;
  // min-height: 0; // 关键，防止flex塌陷

  .agreement-content {
    font-size: 28rpx;
    line-height: 1.6;
    color: #666;
  }
}

// 说明图片区域
.info-image-section {
  margin-top: 40rpx;
  .tip-box {
    .title {
      color: #cc9933;
    }
  }
  .paragraph {
    color: #cc9933;
  }
  .qr_code {
    width: 200rpx;
  }
  .alert-text {
    margin: 20rpx 0 0;
    .paragraph {
      color: red;
    }
  }
}
</style>
