<template>
  <div class="wrap">
    <div class="baseInfo common">
      <div class="title">基本信息:</div>
      <div class="line"></div>
      <div class="infoWrap fontColor">
        <div class="infoRow">
          <span class="leftItem">工单编号:</span>
          <span class="rightItem" style="display: flex;align-items: center;">
            <span id="copyText">{{orderDetailInfo.orderCode}}</span>
            <img @click="copyText" src="@/assets/copy.png" style="width: 35px;height: 15px;margin-left: 10px"/>
          </span>
        </div>
        <div class="infoRow" v-if="!([7,9,11,12].includes(Number(queryType)))">
          <span class="leftItem">合同:</span>
          <span class="rightItem">{{ orderDetailInfo.contractName }}</span>
        </div>
        <template v-if="orderDetailInfo.contractParentId == 110">
          <div class="infoRow">
            <span class="leftItem">机构名称:</span>
            <span class="rightItem">{{ orderDetailInfo.organizeName }}</span>
          </div>
          <div class="infoRow">
            <span class="leftItem">销售人员:</span>
            <span class="rightItem">{{ orderDetailInfo.saleName }}</span>
          </div>
          <div class="infoRow">
            <span class="leftItem">司机号码:</span>
            <span class="rightItem">{{ orderDetailInfo.driverPhone ? orderDetailInfo.driverPhone : '  '}}</span>
          </div>
        </template>
        <div class="infoRow">
          <span class="leftItem">结算方式:</span>
          <span class="rightItem">{{ orderDetailInfo.contractSettleType?.label }}</span>
        </div>
        <div class="infoRow">
          <span class="leftItem">客户姓名:</span>
          <span class="rightItem">{{ [7,9,11,12].includes(Number(queryType)) ? maskName(orderDetailInfo.userName) : orderDetailInfo.userName }}</span>
        </div>
        <div class="infoRow">
          <span class="leftItem">客户电话:</span>
          <span class="rightItem">{{ maskPhone(orderDetailInfo.userPhone) }}</span>
        </div>
        <div class="infoRow">
          <span class="leftItem">车牌号:</span>
          <span class="rightItem">{{ [7,9,11,12].includes(Number(queryType)) ? maskPlate(orderDetailInfo.plateNumber) : orderDetailInfo.plateNumber }}</span>
        </div>
        <div class="infoRow">
          <span class="leftItem">车型品牌:</span>
          <span class="rightItem">{{orderDetailInfo.model}}{{ orderDetailInfo.brand }}</span>
        </div>
        <div class="infoRow" v-if="!([7,9,11,12].includes(Number(queryType)))">
          <span class="leftItem">车架号:</span>
          <span class="rightItem">{{orderDetailInfo.vinNo}}</span>
        </div>
      </div>
    </div>
    <div class="serviceInfo common">
      <div class="title">服务信息:</div>
      <div class="line"></div>
      <div class="infoContent">
        <div class="item">
          <span class="leftTitle fontColor">服务类型:</span><span class="rightContent">{{ orderDetailInfo.taskServiceName }}</span>
        </div>
        <div class="item" v-if="orderDetailInfo?.userVehicleTypeString">
          <span class="leftTitle fontColor">车辆类型:</span><span class="rightContent">{{ orderDetailInfo.userVehicleTypeString }}<van-icon class="icon" name="question" @click="showCarTypeShow = true" /></span>
        </div>
        <div class="item">
          <span class="leftTitle fontColor">车辆位于:</span><span class="rightContent">{{ orderDetailInfo.positionEnvironment?.label }}</span>
        </div>
        <div class="item"  style="align-items: baseline">
          <span class="leftTitle fontColor">事发地:</span><span class="rightContent" style="flex: 1">{{ orderDetailInfo.vehiclePointAddress }}</span>
        </div>
        <div class="item" style="align-items: baseline">
          <span class="leftTitle fontColor">事发地补充:</span><span class="rightContent vehicleRemark" >{{orderDetailInfo.vehiclePointRemark}}
      </span>
        </div>
        <div v-show="orderDetailInfo.taskFlowId === 2" class="item"  style="align-items: baseline" >
          <span class="leftTitle fontColor">目的地:</span><span class="rightContent" style="flex: 1">{{ orderDetailInfo.destinationAddress }}</span>
        </div>
        <div v-show="orderDetailInfo.taskFlowId === 2" class="item"  style="align-items: baseline">
          <span class="leftTitle fontColor">目的地补充:</span><span class="rightContent vehicleRemark">{{orderDetailInfo.destinationRemark}}</span>
        </div>
        <div class="item">
          <span class="leftTitle fontColor">工单状态:</span><span class="rightContent orderStatus">{{ orderDetailInfo.taskOrderStatusString }}</span>
        </div>
        <div class="item">
          <span class="leftTitle fontColor">服务车辆:</span><span class="rightContent">{{ orderDetailInfo.taskVehicleName }}</span>
        </div>
        <div class="item">
          <span class="leftTitle fontColor">服务师傅:</span><span class="rightContent">{{ orderDetailInfo.driverName }} {{orderDetailInfo.drivePhone ? '/' : ''}} {{orderDetailInfo.drivePhone }}
           <span v-if="queryType == 5" class="driverPoiBtn" @click="noMultipleClicks(showMap)">查看司机位置</span>
           <span v-if="orderDetailInfo.driverName && orderDetailInfo.proprietary?.code==1" class="driverPoiBtn" @click="noMultipleClicks(createDriverInfo)">生成司机信息</span>
          </span>
        </div>
        <div class="item" v-if="queryType == 9 || queryType ==11  || queryType ==12 || queryType ==5">
          <span class="leftTitle fontColor">工单照片:</span><span class="rightContent">
           <span  class="driverPoiBtn" @click="checkPhoto">查看照片</span>
           <span  class="driverPoiBtn" v-if="orderDetailInfo.beforeDispatchImages && orderDetailInfo.beforeDispatchImages.length > 0" @click="environmentPhoto">环境照片</span>
          </span>
        </div>
        <div v-if="orderDetailInfo.firstAggregateFailInfo" class="aggregate-fail-card">
          <div class="aggregate-fail-card__title">⚠ 首次聚合未接单</div>
          <div class="aggregate-fail-card__row">
            <span class="aggregate-fail-card__label">师傅姓名：</span>
            <span class="aggregate-fail-card__value">{{ orderDetailInfo.firstAggregateFailInfo.driverName || '—' }}</span>
          </div>
          <div class="aggregate-fail-card__row">
            <span class="aggregate-fail-card__label">师傅手机号：</span>
            <span class="aggregate-fail-card__value">{{ orderDetailInfo.firstAggregateFailInfo.driverPhone || '—' }}</span>
          </div>
          <div class="aggregate-fail-card__row">
            <span class="aggregate-fail-card__label">车辆：</span>
            <span class="aggregate-fail-card__value">{{ aggregateFailVehicle }}</span>
          </div>
          <div class="aggregate-fail-card__row">
            <span class="aggregate-fail-card__label">失败原因：</span>
            <span class="aggregate-fail-card__value aggregate-fail-card__value--warning">{{ orderDetailInfo.firstAggregateFailInfo.failReason || '—' }}</span>
          </div>
          <div class="aggregate-fail-card__row">
            <span class="aggregate-fail-card__label">聚合时间：</span>
            <span class="aggregate-fail-card__value">{{ orderDetailInfo.firstAggregateFailInfo.dispatchTime || '—' }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="serviceInfo common" v-if="orderDetailInfo.batteryNo">
      <div class="title">电瓶信息:</div>
      <div class="line"></div>
      <div class="infoContent">
        <div class="item">
          <span class="leftTitle fontColor">设备号:</span><span class="rightContent">{{orderDetailInfo?.batteryNo}}</span>
        </div>
        <div class="item">
          <span class="leftTitle fontColor">品牌:</span><span class="rightContent">{{orderDetailInfo?.batteryBrand}}</span>
        </div>
        <div class="item">
          <span class="leftTitle fontColor">型号:</span><span class="rightContent">{{orderDetailInfo?.batteryModel}}</span>
        </div>
      </div>
    </div>
    <van-popup v-model="showCarTypeShow" round position="center" class="popupCenter">
      <table v-for="(item, index) in carTypeList" :key="index">
        <tr>
          <td width="50">{{item.type}}:</td>
          <td>{{item.abbr}}</td>
        </tr>
      </table>
<!--      <div v-for="(item, index) in carTypeList" :key="index"><span style="margin-right: 5px">{{item.type}}:</span><span>{{item.abbr}}</span></div>-->
    </van-popup>
    <div class="map" v-show="showPopup"   id="container">
      <img @click="showPopup = false"  src="@/assets/delKey.png" class="mapImg">
    </div>
  </div>
</template>
<script>
import {myMixins} from '@/utils/myMixins'
import {getOrderDetail,showVehiclePositionInfo, getConfigByCode,getDriverInfo} from "@/api/order"
import minePosition from '@/assets/minePosition.png';
import vehiclePosition from '@/assets/vehiclePosition.png';
import  desitationPosition from '@/assets/desitationPosition.png'
export default {
  name: "workOrderDetail",
  mixins:[myMixins],
  data(){
    return{
      userOrderId:'',
      queryType:'',
      orderCode:'',
      taskOrderId:'',
      orderDetailInfo:{},
      showPopup: false,
      map: '',
      driverPoiInfo:{},
      noClick:true,
      showCarTypeShow: false,
      carTypeList: []
    }
  },
  computed:{
    aggregateFailVehicle(){
      const info = this.orderDetailInfo.firstAggregateFailInfo
      if(!info) return '—'
      const plate = info.licensePlate || ''
      const type = info.vehicleTypeName || ''
      if(plate && type) return `${plate}（${type}）`
      return plate || type || '—'
    }
  },
  async mounted() {
    // 获取当前 URL
    const urlParams = new URLSearchParams(window.location.search);
    // 获取指定参数的值
    this.queryType=urlParams.get('queryType');
    this.userOrderId = urlParams.get('userOrderId');
    this.orderCode=urlParams.get('orderCode');
    this.taskOrderId=urlParams.get('taskOrderId') ? urlParams.get('taskOrderId') : '';
    await this.getConfigByCodeHandler();
    await this.getDetail();
    if(this.queryType == 5){
      await this.getDriverPoi();
    }
    this.$nextTick(() => {
      this.initMap();
    });
    console.log('queryType', this.queryType)
  },
  methods:{
    async getConfigByCodeHandler() {
      let res = await getConfigByCode({
        code: 'userVehicleTypeConfig'
      });
      this.carTypeList = res?.data?.userVehicleType
    },
    async getDriverInfo(){
      let result=await getDriverInfo({
        driverId:this.orderDetailInfo.driverId
      })
      if(result.data){
        // console.log('--result--',result.data)
        let params=`姓名：${this.orderDetailInfo.driverName}\n身份证：${result.data.identityCardNumber}\n车牌：${this.orderDetailInfo.vehiclePlateNumber}\n手机：${this.orderDetailInfo.driverPhone}`
        // console.log('params',params)
        let data = {"action":"copyToClipboard","params":params}
        var u = navigator.userAgent;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if(isiOS){
          window.webkit.messageHandlers.nativeObject.postMessage(data);
        }else {
          window.android.copyToClipboard(params);
        }
      }else {
        this.$toast('未获取到司机信息')
      }
    },
    async getDetail(){
      let result=await getOrderDetail({
        queryType:this.queryType,
        userOrderId:this.userOrderId,
        orderCode:this.orderCode,
        taskOrderId:this.taskOrderId ? this.taskOrderId : ''
      })
      // if(result.code === 200){
        this.orderDetailInfo=result.data;
      // }
    },
    showMap() {
      this.showPopup = true;
      this.mapMarkers();
    },
    async createDriverInfo(){//生成司机信息
      await this.getDriverInfo()
    },
    checkPhoto(){
      let isAllowImage = this.queryType == 9 ? 0 : 1
      let data = {
        "action": "orderPhoto",
        "params": {
          "userOrderId": this.userOrderId,
          "orderCode": this.orderCode,
          "taskOrderId": this.taskOrderId,
          "isAllowImage":isAllowImage,
        }
      }
      var u = navigator.userAgent;
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if(isiOS){
        window.webkit.messageHandlers.nativeObject.postMessage(data);
      }else {
        window.android.sendMessage("orderPhoto,"+this.userOrderId+","+this.orderCode+","+this.taskOrderId+","+isAllowImage);
      }
    },
    environmentPhoto() {
      this.$router.push({
        path: '/environmentPhotos',
        query: { userOrderId: this.userOrderId }
      })
    },
    initMap() {
      this.map = new AMap.Map('container',{
        zoom:14,//级别(缩放比例 3-20 )
        center: [this.driverPoiInfo.vehiclePositionLongtitude,this.driverPoiInfo.vehiclePositionLatitude],//中心点坐标
        viewMode:'2D',//使用3D视图
      })
      this.map.on('complete', () => {
        console.log("地图加载完成")
        this.mapMarkers();
      });
    },
    mapMarkers(){
      // 车辆位置，a点
      let marker = new AMap.Marker({
        position: [this.driverPoiInfo?.vehiclePositionLongtitude,this.driverPoiInfo?.vehiclePositionLatitude],
        icon: new AMap.Icon({
          image: minePosition, // 图片的相对路径
          size: new AMap.Size(22, 32),  // 图标的尺寸
          imageSize: new AMap.Size(22, 32)  // 图片的实际尺寸
        }),
      });
      this.map.add(marker);
      // 事发地，b点
      let marker1 = new AMap.Marker({
        position: [this.driverPoiInfo?.vehiclePointLongitude,this.driverPoiInfo?.vehiclePointLatitude],
        icon: new AMap.Icon({
          image: vehiclePosition, // 图片的相对路径
          size: new AMap.Size(26, 28),  // 图标的尺寸
          imageSize: new AMap.Size(26, 28)  // 图片的实际尺寸
        })
      });
      this.map.add(marker1);
      let marker2 = new AMap.Marker({
        position: [this.driverPoiInfo?.destinationLongitude,this.driverPoiInfo?.destinationLatitude],
        icon: new AMap.Icon({
          image: desitationPosition, // 图片的相对路径
          size: new AMap.Size(28, 28),  // 图标的尺寸
          imageSize: new AMap.Size(28, 28)  // 图片的实际尺寸
        })
      });
      this.map.add(marker2);
      this.map.setFitView([marker,marker1,marker2])
    },
    maskName(name) {
      if (!name) return '';
      return name.slice(0, 1) + '*'.repeat(name.length - 1);
    },
    maskPhone(phone) {
      if (!phone) return '';
      const str = String(phone);
      if (str.length <= 7) return str;
      return str.slice(0, 3) + '*'.repeat(str.length - 7) + str.slice(-4);
    },
    maskPlate(plate) {
      if (!plate) return '';
      if (plate.length <= 2) return plate;
      return plate.slice(0, 1) + '*'.repeat(plate.length - 2) + plate.slice(-1);
    },
    async getDriverPoi(){
      let res=await showVehiclePositionInfo({
        userOrderId:this.userOrderId,
        taskOrderId:this.taskOrderId
      })
      // 2704382，24145
      this.driverPoiInfo = res.data
      console.log("driverPoiInfo",this.driverPoiInfo)
    }
  }
}
</script>

<style scoped lang="scss">
@import "@/styles/mixin.scss";
.wrap{
  @include wh(100%,100%);
  background-color: #F4F5F7;
  overflow-y: auto;
}
::v-deep .amap-copyright{
  display: none !important;
}
::v-deep .amap-logo{
  display: none !important;
}
.map{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  @include wh(95%,350px);
  .mapImg{
    background-color: #FFFFFF;
    position: absolute;
    right: 0;
    top: 0;
    @include wh(25px,25px);
    z-index: 1111111;
  }
}

.common{
  background: #FFFFFF;
  @include radiusSizing(6px);
  padding: 11px 17px 15px 24px;
}
.fontColor{
  @include fontWeightSize(400,12px);
  color: #000000;
  line-height: 24px;
}
.baseInfo{
  width: 100%;
  margin-bottom: 12px;
  .infoWrap{
    .infoRow{
      display: flex;
      align-items: center;
      min-height: 24px;
      .leftItem{
        width: 60px;
        flex-shrink: 0;
        margin-left: 5px;
        margin-right: 6px;
        opacity: .5;
      }
      .rightItem{
        flex: 1;
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
.serviceInfo{
  //@include wh(100%,356px);
  width: 100%;
  margin-bottom: 30px;
  .item{
    @include flexCenter;
  }
  .infoContent{
    .leftTitle{
      display: block;
      width: 72px;
      opacity: .5;
    }
    .rightContent{
      width: calc(100% - 90px);
      @include fontWeightSize(bold,12px);
      .driverPoiBtn{
        display: inline-block;
        padding: 3px 8px;
        @include bgFontColor(#FFFFFF,#354D93);
        opacity: .7;
        border-radius: 3px;
        text-align: center;
        margin-left: 6px;
        cursor: pointer;
      }
    }

    .vehicleRemark{
      @include fontWeightSize(400,11px);
      @include colorOpa(#121212,0.55);
      line-height: 14px;
      flex: 1;
    }
    .orderStatus{
      color: #E69B0B;
    }
  }
}
.aggregate-fail-card{
  margin-top: 12px;
  padding: 12px;
  background: #FFF7F0;
  border: 1px solid #FFBB96;
  border-radius: 6px;
  &__title{
    @include fontWeightSize(bold,13px);
    color: #FA541C;
    margin-bottom: 8px;
  }
  &__row{
    display: flex;
    align-items: baseline;
    line-height: 22px;
  }
  &__label{
    width: 78px;
    flex-shrink: 0;
    @include fontWeightSize(400,12px);
    color: #000000;
    opacity: .65;
  }
  &__value{
    flex: 1;
    @include fontWeightSize(bold,12px);
    color: #000000;
    &--warning{
      color: #FA541C;
    }
  }
}
.title{
  @include fontWeightSize(bold,14px);
  @include colorOpa(#323643,0.6);
  line-height: 20px;
}
.line{
  @include wh(100%,2px);
  opacity: 0.16;
  border-bottom: 1px solid;
  margin: 7px 0;
  border-image: linear-gradient(270deg, rgba(217, 217, 217, 0.6), rgba(178, 178, 178, 1), rgba(178, 178, 178, 1), rgba(217, 217, 217, 0.6)) 1 1;
}
  .popupCenter {
    padding: 20px 10px;
    width: 80%;
  }
</style>
