<template>
  <view class="withdraw">
    <view class="content">
      <view class="withdraw-express">
        <view class="header">
          <span class="title">自主邮寄</span>
        </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="copyAddress">复制</view>
          </view>
        </view>
      </view>
      <view>
        <view style="padding: 0rpx 10px">
          <view class="gold-item">
            <view class="header">
              <span class="title">快递单号</span>
            </view>
            <view class="input-box">
              <input
                type="text"
                class="inpu-box-ds"
                placeholder="请输入快递单号"
                v-model="expressNum"
                placeholder-style="color: #999999; font-size: 28rpx;"
              />
              <text class="iconfont icon-iconfontscan" @click="scanCode"></text>
            </view>
          </view>

          <view class="gold-item">
            <view class="header">
              <span class="title">快递图片</span>
            </view>
            <view style="margin-top: 10px">
              <view class="upload-box">
                <up-upload
                  :fileList="imageList"
                  uploadIcon="plus"
                  @afterRead="afterRead"
                  @delete="deletePic"
                  name="1"
                  multiple
                  :maxCount="3"
                >
                  <template #trigger>
                    <view class="upload-block">
                      <uni-icons
                        size="38"
                        color="#ccc"
                        type="plusempty"
                      ></uni-icons>
                    </view>
                  </template>
                </up-upload>
              </view>
            </view>
          </view>

          <view class="gold-item">
            <view class="form-body">
              <view class="weight-input">
                <view class="input-label">黄金金重</view>
                <view class="form-body-box">
                  <input
                    v-model="auExtract"
                    type="digit"
                    class="weight-value"
                  />
                  <text>g</text>
                </view>
              </view>
              <view class="weight-input">
                <view class="input-label">K金金重</view>
                <view class="form-body-box">
                  <input
                    v-model="kauExtract"
                    type="digit"
                    class="weight-value"
                  />
                  <text>g</text>
                </view>
              </view>
              <view class="weight-input">
                <view class="input-label">铂金金重</view>
                <view class="form-body-box">
                  <input
                    v-model="ptExtract"
                    type="digit"
                    class="weight-value"
                  />
                  <text>g</text>
                </view>
              </view>
              <view class="weight-input">
                <view class="input-label">白银金重</view>
                <view class="form-body-box">
                  <input
                    v-model="agExtract"
                    type="digit"
                    class="weight-value"
                  />
                  <text>g</text>
                </view>
              </view>

              <view class="tips">* 若无相关产品，可不用填写</view>
            </view>
          </view>
        </view>
        <view class="withdraw-body">
          <view class="tx-active" style="margin-top: 10px">
            <button @click="submitGoldOrder">点击提交</button>
          </view>
          <view class="aggregate" @click="aggregate = !aggregate">
            <image
              class="choose"
              :src="
                aggregate
                  ? '/static/recycle/choose.png'
                  : '/static/recycle/nochoose.png'
              "
              mode="scaleToFill"
            ></image>
            <view class="aggre">
              阅读并同意
              <span class="aggre-text" @click="showAggre">《存金协议》</span>
            </view>
          </view>
          <view style="margin-top: 20px">
            <up-parse :content="content"></up-parse>
          </view>
        </view>
      </view>
    </view>
    <uni-popup
      background-color="#fff"
      ref="singPopup"
      type="bottom"
      :safeArea="false"
      borderRadius="10px 10px 0 0"
      maskBackgroundColor="rgba(0, 0, 0,0)"
    >
      <view class="signContent">
        <scroll-view scrollY class="scroll">
          <up-parse :content="agreement"></up-parse>
        </scroll-view>
        <view
          class="comfireBtn footer"
          @click="
            aggregate = true;
            $refs.singPopup.close();
          "
        >
          我已详细知悉
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
// 1. 导入依赖（保持不变）
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { depositCreateAPI } from "@/api/functions";
import { useImageUpload } from "@/hooks/useImageUpload";
import { useAppStore } from "@/stores/app";
const appStore = useAppStore();

// 2. 响应式变量（保持不变，明确金属类型对应关系）
const { imageList, afterRead, deletePic, uploadLoading } = useImageUpload({
  pid: 9,
  model: "gold",
});
const extract = ref([]);
const auExtract = ref(null); // 黄金重量 → type:1
const ptExtract = ref(null); // 铂金重量 → type:2
const agExtract = ref(null); // 白银重量 → type:3
const kauExtract = ref(null); // K金重量 → type:4
const aggregate = ref(false);
const expressNum = ref("");
const cust_img = ref([]);
const singPopup = ref(null);
const props = defineProps(["agreement", "content"]);
onLoad(() => {});
const showAggre = () => {
  singPopup.value?.open();
};
// 3. 扫码方法（保持不变）
const scanCode = () => {
  uni.scanCode({
    success: (res) => {
      expressNum.value = res.result;
      console.log("赋值后:", expressNum.value);
    },
    fail: (err) => {
      console.error("扫码失败:", err);
      uni.showToast({ title: "扫码失败，请重试", icon: "none" });
    },
  });
};
const copy = (item) => {
  uni.setClipboardData({
    data: item,
    success: () => {
      uni.showToast({
        title: "复制成功",
        icon: "success",
      });
    },
    fail: (err) => {
      uni.showToast({
        title: "复制失败",
        icon: "none",
      });
      console.error("复制失败：", err);
    },
  });
};

// 复制地址方法
const copyAddress = () => {
  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);
    },
  });
};

/**
 * 转换金属重量为目标格式：[{type:1,weight:1}, ...]
 * 改用直接引用ref变量的映射表，避免eval
 */
const buildMetalWeightList = () => {
  // 优化：金属映射表直接包含ref变量，无需通过字符串动态获取
  const metalConfigList = [
    { metalVar: auExtract, type: 1, label: "黄金" }, // 直接传auExtract（ref变量）
    { metalVar: ptExtract, type: 2, label: "铂金" },
    { metalVar: agExtract, type: 3, label: "白银" },
    { metalVar: kauExtract, type: 4, label: "K金" },
  ];

  // 循环收集有效重量（逻辑与之前一致，仅获取重量的方式变化）
  const metalList = [];
  metalConfigList.forEach(({ metalVar, type }) => {
    // 直接访问ref变量的.value获取重量值
    const weightValue = metalVar.value;
    // 处理重量：去空格、排除空值、转为数字
    const trimmedWeight = weightValue ? String(weightValue).trim() : "";
    const validWeight = Number(trimmedWeight);

    // 仅保留「非空、非NaN、正数」的重量
    if (trimmedWeight !== "" && !isNaN(validWeight) && validWeight > 0) {
      metalList.push({
        type: type,
        weight: validWeight, // 转为数字格式，符合接口要求
      });
    }
  });

  return metalList;
};

// 5. 提交方法（逻辑不变，依赖优化后的buildMetalWeightList）
const submitGoldOrder = async () => {
  // 步骤1：基础校验（图片+重量+快递单号）
  const isCheckPass = checkHandle();
  if (!isCheckPass) return;

  // 步骤2：构建目标格式的金属重量数组
  const metalWeightList = buildMetalWeightList();
  if (metalWeightList.length === 0) {
    uni.showToast({ title: "请至少填写一个有效金属重量!", icon: "none" });
    return;
  }

  // 步骤3：整合提交数据
  const submitData = {
    metalInfos: metalWeightList, // 核心目标数组
    expressNo: expressNum.value.trim(),
    expressImages: imageList.value.map((v) => v.info.url),
  };

  // 步骤4：执行提交（示例接口调用）
  try {
    const res = await depositCreateAPI(submitData);

    uni.showToast({ title: "提交成功!" });
    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/users/vault/storeMetal/order",
      });
    }, 1000);
  } catch (error) {
    console.error("提交失败：", error);
    uni.showToast({ title: "提交失败，请重试", icon: "none" });
  }
};

// 6. 校验方法（逻辑不变，依赖优化后的buildMetalWeightList）
const checkHandle = () => {
  // 校验1：快递图片
  if (imageList.value.length === 0) {
    uni.showToast({ title: "请上传快递图片!", icon: "none" });
    return false;
  }

  // 校验2：至少一个有效金属重量
  const metalWeightList = buildMetalWeightList();
  if (metalWeightList.length === 0) {
    uni.showToast({
      title: "请至少填写一个金属重量（黄金/铂金/白银/K金）!",
      icon: "none",
    });
    return false;
  }

  // 校验3：快递单号（可选，根据需求保留）
  if (!expressNum.value.trim()) {
    uni.showToast({ title: "请填写或扫码获取快递单号!", icon: "none" });
    return false;
  }

  return true;
};
</script>

<style lang="scss" scoped>
page {
  height: 100%;
}
.icon-iconfontscan {
  font-size: 20px;
}
.upload-box {
  .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;
  }
}
.tips {
  text-align: center;
  color: #bdbdbd;
  font-size: 24rpx;
  margin: 20rpx auto;
}

.form-body {
  // background-color: #fff;
  // padding: 20px 30px;
  font-size: 14px;
  margin-top: 90rpx;

  .weight-input {
    display: flex;
    align-items: center;
    // justify-content: space-around;
    margin: 30rpx 0;

    .form-body-box {
      display: flex;
      align-items: center;
      background-color: #ededed;
      margin-left: 30rpx;
      height: 72rpx;
      border-radius: 10rpx;
      font-size: 30rpx;

      text {
        color: #cc9933;
        padding-right: 20rpx;
        font-size: 25rpx;
      }

      input {
        // font-size: 18rpx;
        padding-left: 10rpx;
      }
    }

    .input-label {
      font-size: 32rpx;
      font-weight: 500;

      width: 135rpx;
    }

    .weight-value {
      height: 1.9em;
      font-size: 1.5em;
      border: none;
      outline: none;
    }
  }

  .submit-btn-area {
    button {
      color: #fff;
      background: #c4bba6;
    }
  }

  .agreement-section {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx;
    margin-top: 30rpx;

    .agreement-checkbox {
      width: 32rpx;
      height: 16px;
    }

    .agreement-text {
      font-size: 14px;
      margin-left: 10px;

      .agreement-link {
        color: #3ab0ff;
      }
    }
  }
}

.input-box {
  display: flex;
  background-color: #ededed;
  border-radius: 5px;
  height: 90rpx;
  align-items: center;
  justify-content: space-around;
  font-size: 28rpx;
  // paddingft: ;
  padding-left: 20rpx;

  // color:#c7c7c7 ;
  input {
    // background-color: ;
    width: 80%;
    // color: #c7c7c7;
  }
}

.inpu-box-zl {
  justify-content: space-between;
  padding-left: 47rpx;
}

.gold-item {
  margin: 50rpx 0;
}

// .gold-input{
//    background-color: red !important;
// }
.address-detail {
  line-height: 2.2;
}

.header {
  padding-left: 5px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 10px;
  border-radius: 5px;
  // background-color: #fff;
  font-weight: bold;
  font-size: 18px;

  &::before {
    position: absolute;
    /*绝对定位*/
    top: 50%;
    /*Y轴方向偏移自身高度的50%*/
    transform: translatey(-50%);
    /*Y轴方向偏移微调*/
    left: 0;
    /*紧靠容器左边缘*/
    content: "";
    /*伪元素需要有内容才能显示*/
    width: 2px;
    /*伪元素宽度*/
    height: 15px;
    /*伪元素高度*/
    background-color: #daa520;
    /*伪元素颜色*/
  }

  .title {
    font-weight: 500;
    font-size: 32rpx;
    font-family: "黑体";
  }
}

.withdraw {
  height: 100%;
  background-color: #f7f7f7;
  border-radius: 10px 10px 0 0;
  position: relative;
  // top: -20rpx;
  padding: 0 25rpx;
  top: -67rpx;

  .withdraw-express {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;

    padding: 28rpx;
    margin-bottom: 30rpx;
    border-radius: 30rpx;
    padding-right: 0;

    .head {
      font-size: 14px;
    }

    .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: #cc9933;
      }

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

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

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

        .copy {
          color: #888888;
          border-radius: 3px;
          border: 1px solid #888888;
          font-size: 24rpx;
          padding: 6rpx 23rpx;
        }
      }
    }
  }

  .withdraw-body {
    // background-color: #fff;
    padding: 20px 30px;
    font-size: 14px;

    .input-money {
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 600;
      border-bottom: 1px solid #eaeef1;

      .rmb {
        font-size: 16px;
      }

      .t-input {
        height: 1.9em;
        font-size: 1.5em;
        border: none;
        outline: none;
      }
    }

    .aggregate {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px;
      color: #ababab;
      font-size: 12px;

      .aggre {
        font-size: 30rpx;
        margin-left: 10px;

        .aggre-text {
          color: #cc9933;
        }
      }
    }

    .choose {
      width: 28rpx;
      height: 28rpx;
    }
  }
}

.tx {
  button {
    color: #b2b2b2;
  }
}

.tx-active {
  margin: 0 auto;
  display: flex;
  justify-content: center;

  button {
    width: 420rpx;
    height: 84rpx;
    background-color: #cc9933;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
    border-radius: 30px;
  }
}

.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);
  }
}

.express-input {
  &:nth-child(1) {
    padding: 0;
  }
}
</style>
