<template>
  <div>
    <img class="imgs" :src="`https://h5.whjhft.com/static/${imgArr[0]}`" v-show="imgArr[0]">
    <div class="content">
      <van-cell-group>
        <van-field :rules="[{ required: true, message: '请填写用户名' }]" v-model="formData.cert_name" label="收货人姓名" placeholder="请输入收货人姓名" />
      </van-cell-group>

      <van-cell-group>
        <van-field v-model="formData.contact_num" label="收货人电话" placeholder="请输入收货人电话" />
      </van-cell-group>

      <van-cell-group>
        <van-field v-model="formData.cert_no" label="身份证号" placeholder="请输入身份证号"  v-show="need_identity===1"/>
      </van-cell-group>

      <van-cell-group>
        <van-field readonly v-model="formData.post_province_name+formData.post_city_name+formData.post_district_name" label="地区" placeholder="请选择地区" @click="showPopup"/>
      </van-cell-group>

  <div class="popup">
    <van-popup v-model="show" position="bottom" :style="{ height: '30%' }" >
      <van-area title="选择地区" :area-list="areaList" @confirm="handleConfirm" @cancel="handleCancel"/>
    </van-popup>
  </div>
      <van-cell-group>
        <van-field v-model="formData.post_addr" label="详细地址" placeholder="请输入详细地址" />
      </van-cell-group>
      <button class="vbuttons" @click="submit">立即领取，包邮到家</button>
    </div>


    <img class="imgs" :src="`https://h5.whjhft.com/static/${imgArr[1]}`" v-show="imgArr[1]" >


    <img class="imgs" :src="`https://h5.whjhft.com/static/${imgArr[2]}`" v-show="imgArr[2]">
  </div>
</template>

<script>
import areaData from 'china-area-data';
import { Base64 } from "js-base64";
import axios from "axios";
import { Toast } from 'vant';
import CryptoJS from 'crypto-js'; // 引入 CryptoJS

export default {
  data() {
    return {
      need_identity:null,
      base64:null,
      show: false,
      urlos: null,
      id_goods: null,
      id_agent: null,
      imgArr: [],
      encrypted: 'https://example.com/product?data=DiW0XlB6rznMFVtUopdDj6CyL%2FGYjEubPEyOZRCjmtzZco97wHy9bLPo%2BnZdqureW%2BynJnIR%2Biktz5HNWrvLOg%3D%3D',
      areaList: {},
      value: '',
      formData: {
        cert_name: "",
        contact_num: "",
        address: "",
        addressOption: [],
        post_addr: "",
        goods: [],
        agent_id: "",
        cert_no: "",
        post_province_name: "",
        post_city_name: "",
        post_district_name: "",
        source: 7,
        source_type: 1
      },
      // CryptoJS 解密配置（需与加密端一致）
      cryptoConfig: {
        key: '1234567890123456', // 16位密钥（AES-128）
        iv: '6543210987654321' // 16位初始向量
      }
    };
  },
  async created() {
    console.log(window.location.href);
    // await this.Parse(this.encrypted);
    this.formatAreaData();
    // const result = window.location.href.split('=')[1]
    const result = 'ffMngb0kTzCgTwjPAt7KY0yAtF4784R3VRxzhlVEM5PMZn4xXT4XvuVLXFkQqZyXVS5Cnsd3WRpKaQIQh%2BLn0Q%3D%3D'
    await this.getLink(result)
    const {data} = await axios.get(`https://h5.whjhft.com/api/v1/h5/lot?key=${this.base64}`);
    console.log(data)
    this.imgArr=[
        data.data.good.top_img,
        data.data.good.details_img,
        data.data.good.copyright_img,
        data.data.good.customize_img,
    ]
    this.need_identity=data.data.good.need_identity
  },
  methods: {
    getLink(encrypted){
      console.log(encrypted)
      const key = CryptoJS.enc.Utf8.parse('1234567890123456');
      const iv = CryptoJS.enc.Utf8.parse('6543210987654321');

      const decrypted = CryptoJS.AES.decrypt(decodeURIComponent(encrypted), key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      });

      const result = JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));
      this.formData.goods=[
        result.goods_id
      ]
      this.formData.agent_id=result.agent_id
      // console.log(btoa(result.agent_id+'_'+result.goods_id))
      // console.log(btoa(result.agent_id+'_'+))
      console.log(result.goods_id)
      result.goods_id=53
      this.base64=btoa(result.agent_id+'_'+result.goods_id)
    },
    showPopup() {
      this.show = true;
    },
    async submit() {

      // 提交逻辑保持不变
      const res = await axios({
        url: 'https://h5.whjhft.com/api/v1/h5/lot/save',
        method: 'POST',
        data: this.formData
      });
      if (res.data.status === 1) {
        Toast.success("提交成功");
      } else if (res.data.status === 0) {
        Toast.fail(res.data.msg);
      }
    },
    formatAreaData() {
      // 地区数据格式化逻辑保持不变
      const result = {
        province_list: {},
        city_list: {},
        county_list: {}
      };
      if (areaData['86']) {
        result.province_list = areaData['86'];
      }
      Object.keys(result.province_list).forEach(provinceCode => {
        const cities = areaData[provinceCode] || {};
        Object.keys(cities).forEach(cityCode => {
          if (typeof cities[cityCode] === 'object') {
            result.city_list[cityCode] = cityCode;
          } else {
            result.city_list[cityCode] = cities[cityCode];
          }
        });
      });
      Object.keys(result.city_list).forEach(cityCode => {
        const counties = areaData[cityCode] || {};
        Object.keys(counties).forEach(countyCode => {
          result.county_list[countyCode] = counties[countyCode];
        });
      });
      this.areaList = result;
      console.log('格式化后的地区数据:', this.areaList);
    },
    handleConfirm(values) {
      this.formData.post_province_name=values[0].name
      this.formData.post_city_name=values[1].name
      this.formData.post_district_name=values[2].name
      this.formData.address=values[0].name+values[1].name+values[2].name
      this.formData.addressOption=[
        values[0].name,values[1].name,values[2].name
      ]
      this.show = false;


    },
    handleCancel() {
      this.show = false;
    },
    async Parse(urls) {
      try {
        console.log(urls);
        const url = new URL(urls);
        const dataParam = url.searchParams.get('data'); // 获取加密的data参数
        console.log('原始加密参数:', dataParam);

        // ====================== 核心修改：使用 CryptoJS 解密 ======================
        // 1. Base64解码（如果参数是Base64编码的，需先解码）
        const base64Decoded = Base64.decode(dataParam);
        // 2. AES-CBC解密（需与加密端的密钥、IV、模式一致）
        const decryptedBytes = CryptoJS.AES.decrypt(
            base64Decoded,
            CryptoJS.enc.Utf8.parse(this.cryptoConfig.key), // 密钥
            {
              iv: CryptoJS.enc.Utf8.parse(this.cryptoConfig.iv), // 初始向量
              mode: CryptoJS.mode.CBC, // 加密模式
              padding: CryptoJS.pad.Pkcs7 // 填充方式
            }
        );
        const decodedKey = decryptedBytes.toString(CryptoJS.enc.Utf8); // 转换为明文
        // ====================== 修改结束 ======================

        console.log('解密后数据:', decodedKey);
        // 解析解密后的ID（假设格式为 "agentId_goodsId"）
        const [id_agent, id_goods] = decodedKey.split('_');
        this.id_goods = Number(id_goods);
        this.id_agent = id_agent;
        console.log('商品ID:', this.id_goods, '代理商ID:', this.id_agent);

        // 加载商品图片逻辑保持不变
        const res = await axios.get(url.origin + '/api/v1/h5/lot?key=' + dataParam);
        this.imgArr = [
          res.data.data.good.top_img,
          res.data.data.good.customize_img,
          res.data.data.good.details_img
        ];
      } catch (error) {
        console.error('解码/请求失败:', error);
        Toast.fail('数据解析失败，请检查链接');
      }
    }
  }
};
</script>

<style>
/* 新增自适应基础样式 */
html {
  font-size: 50px; /* 375px宽度下的基准值（1rem=50px） */
  box-sizing: border-box;
}

*, *::before, *::after {
  box-sizing: inherit;
}

/* 输入框相关自适应调整（优化原有样式） */



/* 其他原有样式保持不变 */
.imgs{
  width: 100%;
  height: auto;
}
.imgs{
  width: 100%;
  height: auto;
}

body{
  max-width: 100vw;
  overflow-x: hidden;
  margin: 0 auto;
}
.content{
  padding: 0.1rem;
  margin: 5px;
  border-radius: 15px;
}
.vbuttons {
  border-radius: 11115px;
  background-color: #f46c6c;
  color: white;
  font-size: 15px;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(73, 147, 170, 0.2);
  transition: all 0.3s ease;
  display: block;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 20px;
  animation: heart 1s infinite;
}
.vbuttons:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(73, 147, 170, 0.4);
}
@keyframes heart {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); animation-timing-function: cubic-bezier(0.2, 0.8, 0.2, 1); }
}

@media screen and (min-width: 1280px) {
  /* 限制页面最大宽度并居中 */
  body {
    max-width: 1280px;
    margin: 10px auto;
    overflow-x: hidden; /* 隐藏可能出现的横向滚动条 */
    .van-picker{
      max-width: 1280px !important;
      margin: 0 auto;

    }

    .van-picker__cancel{

    }
    .van-picker__confirm{

    }
    .van-picker__title{

    }
    *{
      font-size: 20px;
    }
    .vbuttons{
      font-size: 22px;
    }
  }

  /* 可选：调整大屏下的根字体大小（保持设计稿比例） */
  html {

  }
}


</style>