<template>
  <div class="wrap" >
    <div class="headerWrap">
      <div v-if="isWebFunc()" style="opacity: 0;" class="back"></div>
      <img v-else class="back" @click="h5GoBack" src="@/assets/secondHandCar/back.png" />
      <span>{{detailInfo?.status?.code !== 6 ? '在售' : '已售出'}}</span>
      <div style="opacity: 0;" class="back"></div>
    </div>
    <van-loading v-show="!detailInfo"  class="loadingWrap"  type="spinner" color="#1989fa" />
    <div class="contentWrap" v-show="detailInfo">
      <el-carousel v-if="isWebFunc()" trigger="click" height="215px" :autoplay="true">
        <el-carousel-item v-for="(item,i) in imgSrcList" :key="i">
          <el-image
            :src="item"
            v-if="item"
            :preview-src-list="[item]"
            class="swipeImg"
          />
        </el-carousel-item>
      </el-carousel>
      <van-swipe v-else  @change="onChange" :autoplay="3000">
        <van-swipe-item v-for="(item,i) in imgSrcList" :key="i" @click="showImagePreview(i)">
          <img v-if="item" class="swipeImg" :src="item" />
        </van-swipe-item>
        <template #indicator>
          <div class="custom-indicator">{{ current + 1 }}/{{imgSrcList.length}}</div>
        </template>
      </van-swipe>
      <div class="infoWrap">
        <div class="titleWrap wrapCommon">
          <div class="info">
            <span>{{ detailInfo.vehicleType }}</span>
            <span>{{ detailInfo.boardType?.label }}</span>
            <span>{{ detailInfo.licenseType?.label }}</span>
            <span>{{detailInfo.brandModel?.match(/^[\u4e00-\u9fa5]+/)?.[0]?.replace(/牌$/, '')}}</span>
            <span>{{ detailInfo.emissionStandard?.label }}</span>
            <span>{{ detailInfo.underpanBrand }}</span>
            <span>{{  formatToWan(detailInfo.mileage) }}公里</span>
          </div>
          <div class="time">
            <span>{{ detailInfo.createTime?.substring(0,10) }}</span><span>{{ detailInfo.areaName }}</span><span>发布</span>
          </div>
          <div class="priceWrap">
            <div class="price">
              售价（含税）：
              <span>{{ formatNumber(detailInfo.minPrice) }}</span>
              <span>万</span>
            </div>
            <div class="viewNum">{{detailInfo.attentionCount}}人想要<span>{{detailInfo.browseCount}}人浏览</span></div>
          </div>
          <div class="price commonColor">
            车源ID: &nbsp;&nbsp;&nbsp;&nbsp;{{ detailInfo.code }}
            <img class="copyIcon" @click="copyHandler(detailInfo.code)" src="@/assets/copy.png" />
          </div>
        </div>
        <div class="detailInfoWrap wrapCommon">
          <div>
            <img class="descImg firstDescImg" src="@/assets/secondHandCar/details.png" />
          </div>
          <div class="descItem descCommon">
            <div class="itemInfo">
              <span>{{ detailInfo.licenseType?.label }}</span>
              <span>牌照类型</span>
            </div>
            <div class="suGang"></div>
            <div class="itemInfo">
              <span>{{ detailInfo.vehicleType }}</span>
              <span>车辆类型</span>
            </div>
            <div class="suGang"></div>
            <div class="itemInfo">
              <span>{{ detailInfo.boardType?.label }}&nbsp;&nbsp;</span>
              <span>落板方式</span>
            </div>
          </div>
          <div class="descItem descCommon">
            <div class="itemInfo">
              <span>{{detailInfo.brandModel?.match(/^[\u4e00-\u9fa5]+/)?.[0]?.replace(/牌$/, '')}}</span>
              <span>上装品牌</span>
            </div>
            <div class="suGang"></div>
            <div class="itemInfo">
              <span>{{ detailInfo.emissionStandard?.label }}</span>
              <span>排放标准</span>
            </div>
            <div class="suGang"></div>
            <div class="itemInfo">
              <span>{{ detailInfo.brakeSystem == 2 ? '油刹' : '汽刹' }}</span>
              <span>刹车系统</span>
            </div>
          </div>
          <div class="descItem descCommon">
            <div class="itemInfo">
              <span>{{ detailInfo.underpanBrand }}</span>
              <span>底盘品牌</span>
            </div>
            <div class="suGang"></div>
            <div class="itemInfo">
              <el-tooltip  class="item" effect="dark" :content="formatToWan(detailInfo.mileage)+'公里'" placement="top">
                <span style="display: inline-block;width:100%;cursor: pointer; white-space: nowrap; overflow: hidden;  text-overflow: ellipsis;">{{ formatToWan(detailInfo.mileage)}}公里</span>
              </el-tooltip>
              <span>行驶公里</span>
            </div>
            <div class="suGang"></div>
            <div class="itemInfo dateItemInfo">
              <span>{{ detailInfo.registerDate?.substring(0,10) }}</span>
              <span>注册日期</span>
            </div>
          </div>
          <div>
            <img class="descImg"  src="@/assets/secondHandCar/description1.png" />
          </div>
          <div class="descCommon desc">{{detailInfo.desc}}</div>
        </div>
        <div class="btnWrap" >
          <div v-if="isList && !detailInfo.selfSupplierPublish && detailInfo.status.code !== 6" class="btn commonBtn"  @click="noMultipleClicks(handle)">我想要</div>
        </div>
      </div>
    </div>
 </div>
</template>

<script>

import {myMixins} from "@/utils/myMixins"
import {carInfoDetail,saveRecord} from "@/api/secondHandCar";
import { ImagePreview, Dialog } from 'vant';
export default {
  name: "forSale",
  mixins:[myMixins],
  data(){
    return{
      current: 0,
      noClick:true,
      id:'',
      queryType:'',
      detailInfo:'',
      imgSrcList:[],
      duration:'',
      startTime: null, // 记录进入时间
      recordType:1,
      isList:false,//是否是首页列表跳转过来的
      recordResponseId:'',//信息记录获取的id，用于关闭界面掉接口所需参数
    }
  },
  async mounted() {
    window.addEventListener('message', (event) => {
      if (event.data === 'dialogClosed') {
        console.log('Dialog 已关闭');
        this.getDuration(1)
        // 执行关闭后的逻辑
      }
    });
    this.startTime = new Date();
    const urlParams = new URLSearchParams(window.location.search);
    this.id=this.$route.query.id ||  urlParams.get('id');
    this.queryType=this.$route.query.queryType || urlParams.get('queryType');
    this.isList=this.$route.query.isList || urlParams.get('isList');
    if( this.id){
      let res = await carInfoDetail({
        id:this.id,
        queryType:this.queryType ,
      })
      this.detailInfo=res?.data
      // console.log("this.detailInfo",this.detailInfo)
      const municipalities = ['北京市', '天津市', '上海市', '重庆市'];
      const isMunicipality = municipalities.some(city => res.data.areaName.includes(city));
      this.detailInfo.areaName= isMunicipality ? res.data.areaName?.substring(0, 3) : res.data.areaName;
      if(res.data.otherPhoto){
        this.imgSrcList=res.data.otherPhoto.split(',') || []
      }
      if( res?.data?.vehicleRearPhoto ) {
        this.imgSrcList.unshift(res?.data?.vehicleRearPhoto)
      }
      this.imgSrcList.unshift(res?.data?.vehicleAnglePhoto)
      let result=await saveRecord({type: 1, carInfoId: this.id, duration:'',id:''});
      // console.log('resultresult',result)
      this.recordResponseId=result?.data?.id
    }
  },
  destroyed() {
    this.getDuration(1)
  },
  methods:{
    copyHandler(copyText){
      let inputNode = document.createElement('input')  // 创建input
      inputNode.value = copyText // 赋值给 input 值
      document.body.appendChild(inputNode) // 插入进去
      inputNode.select() // 选择对象
      document.execCommand('Copy') // 原生调用执行浏览器复制命令
      inputNode.className = 'oInput'
      inputNode.style.display = 'none' // 隐藏
      this.$toast('复制成功')
    },
    showImagePreview(index) {
      ImagePreview({
        images: this.imgSrcList.map(item => item),
        startPosition: index,
        closeable: true
      });
    },
    formatToWan(num) {
      let result = (num / 10000).toString(); // 转换为万单位
      if (result.includes('.')) {
        let decimalPart = result.split('.')[1]; // 获取小数部分
        if (decimalPart.length > 1) {
          result = parseFloat(result).toFixed(1); // 保留一位小数
        }
      }
      return result + '万';
    },
    getDuration(type){
      // 页面卸载时记录离开时间并计算浏览时长
      const endTime = new Date();
      const duration = (endTime - this.startTime) / 1000; // 计算时长（秒）\
      this.saveRecord(duration,type);
    },
    async saveRecord(duration,type){
      await saveRecord({type: type, carInfoId: this.id, duration,id:this.recordResponseId || ''})
    },
    handle(){
      this.getDuration(2)
      Dialog.alert({
        message:this.detailInfo.contactNumber	,
        confirmButtonText:this.isWebFunc() ? '确定' : '拨打电话',
        showCancelButton:true,
      }).then(async() => {
        if(!this.isWebFunc()){
          window.location.href = `tel:${this.detailInfo.contactNumber}`;
        }
      }).catch(() => {
        // on cancel
      });
    },
    onChange(index) {
      this.current = index;
    },
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/mixin.scss';
.wrap {
  @include wh(100%, 100%);
  position: relative;
  background-color: #F6F6F6;
}
.headerWrap{
  width: 100%;
  box-sizing: border-box;
  padding: 15px 16px;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .back{
    @include wh(15px,15px);
  }
  span{
    font-weight: bold;
    font-size: 16px;
    color: #203152;
  }
}
.loadingWrap{
  width: 100%;
  height: calc(100% - 42px);
  text-align: center;
  line-height: 200px;
}
.contentWrap{
  height: calc(100% - 42px);
  overflow-y: auto;
  .infoWrap{
    box-sizing: border-box;
    padding: 0 6px;
    margin-top: -15px;
    position: relative;
    z-index: 111;
  }
  .wrapCommon{
    width: 100%;
    background: #FFFFFF;
    border-radius: 6px;
    backdrop-filter: blur(5.602678571428572px);
    box-sizing: border-box;
    margin-bottom: 12px;
  }
  .titleWrap{
    height: 120px;
    padding: 18px 0 15px 21px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .info{
      font-weight: 600;
      font-size: 15px;
      color: #212020;
      line-height: 21px;
      span{
        margin-right: 10px;
      }
    }
    .time{
      font-weight: 400;
      font-size: 12px;
      color: #999999;
      line-height: 17px;
      span:first-child{
        margin-right: 20px;
      }
      span:last-child{
        margin-left: 10px;
      }
    }
    .priceWrap{
      display: flex;
      justify-content: space-between;
      align-items: center;
      .viewNum{
        //color: #ccc;
        margin-right: 15px;
        span{
          margin-left: 10px;
        }
      }
    }
    .price{
      color: #FF5533;
      line-height: 28px;
      font-weight: 600;
      span:first-child{
        font-size: 20px;
        margin-right: 4px;
      }
      span:last-child{
        font-size: 11px;
      }
    }
  }
  .detailInfoWrap{
    box-sizing: border-box;
    padding: 18px 28px 15px 22px;
    .descImg{
      @include wh(72px, 19px);
    }
    .firstDescImg{
      margin-bottom: 24px;
    }
    .descCommon{
      width: 100%;
      box-sizing: border-box;
      padding-left: 15px;
    }
    .descItem{
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      margin-bottom: 20px;
    }
    .dateItemInfo{
      width: 40% !important;
    }
    .itemInfo{
      display: flex;
      flex-direction: column;
      width: 23%;
      flex: 1;
      span:first-child{
        font-weight: bold;
        font-size: 14px;
        color: #282828;
        line-height: 20px;
        margin-bottom: 2px;
      }
      span:last-child{
        font-weight: 400;
        font-size: 10px;
        color: #999999;
        line-height: 14px;
      }
    }
    .suGang{
      width: 1px;
      height: 8px;
      border-right: 1px solid #999999;
      opacity: 0.5;
      margin-right: 30px;
    }
    .desc{
      font-weight: 400;
      font-size: 12px;
      color: #282828;
      margin-top: 10px;
    }
  }
  .btnWrap{
    padding-bottom: 20px;
  }
  .commonBtn{
    height: 46px;
    line-height: 46px;
    text-align: center;
    font-weight: bold;
    border-radius: 5px;
    color: #FFFFFF;
    cursor: pointer;
  }
  .btn{
    width: 296px;
    background: #4A7FEB;
    margin: 0 auto;
    font-size: 15px;
  }
}
.custom-indicator {
  position: absolute;
  right: 5px;
  bottom: 20px;
  padding: 2px 5px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
  color: wheat;
}
.van-swipe-item{
  height: 215px;
  background-color: pink;
}
.swipeImg{
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持比例填充容器，裁剪多余部分 */
  object-position: center; /* 居中显示 */
}
  ::v-deep .el-carousel__button {
    height: 0.15rem !important;
    width: 0.3rem;
  }
  ::v-deep .el-carousel__indicators--horizontal {
    padding: 0.32rem 0.08rem;
  }
  ::v-deep .el-carousel__arrow {
    background-color: rgba(31, 45, 61, 1);
    font-size: 0.5rem;
  }
  ::v-deep .el-carousel__indicators--horizontal {
    bottom: 10px;
  }
  ::v-deep .el-image__inner {
    object-fit: cover;
    object-position: center;
  }
.copyIcon {
  width: 35px;
  height: 15px;
  margin-left: 10px
}
  .commonColor {
    color: #999999 !important;
    display: flex;
    align-items: center;
  }
</style>
