<template>
<div class="wrap"  >
  <div class="navBar">
    <van-nav-bar
        title="车辆管理"
        :left-arrow="!supplierId"
        left-arrow-color="#FFFFFF"
        :border="false"
        :fixed="true"
        :safe-area-inset-top="true"
        @click-left="goBack"
    >
      <template slot="right" v-if="permissonList.includes('vehicleAddBtn') || supplierId">
        <div class="rightWrap" @click="goPage('vehicleAdd', supplierId ? { supplierId, potentialFlag } : {})">
              <img src="@/assets/addImg.png" />
              <span class="addTxt">添加</span>
        </div>
      </template>
    </van-nav-bar>
  </div>
  <van-search
    v-model="searchVal"
    show-action
    placeholder="请输入车辆名称、车牌号、车架号"
    @search="resetHandler"
  >
    <template #action>
      <div @click="resetHandler">搜索</div>
    </template>
  </van-search>
  <div class="filterWrap">
<!--    <div >-->
      <!--<el-input v-model="searchVal" @blur="resetHandler" placeholder="车辆名称/车牌号/车架号" :class="{'customSel':true,'customInput':true , 'has-value': searchVal }" >
        <template #suffix>
          <i
            v-if="searchVal"
            class="el-icon-circle-close el-input__icon"
            @click="searchVal = ''"
          ></i>
        </template>
      </el-input>-->
    <el-select @change="resetHandler" multiple :collapse-tags="true" v-model="authStates" placeholder="认证状态" :class="{'customSel':true , 'has-value': authStates }" clearable>
      <el-option
          v-for="item in authStatesOptions"
          :key="item.value"
          :label="item.name"
          :value="item.value">
      </el-option>
    </el-select>
      <el-select @change="resetHandler" multiple :collapse-tags="true" v-model="inputStatusList" placeholder="录入状态" :class="{'customSel':true , 'has-value': inputStatusList }" clearable>
        <el-option
          v-for="item in inputStatusListOptions"
          :key="item.value"
          :label="item.name"
          :value="item.value">
        </el-option>
      </el-select>
<!--    </div>-->
<!--    <div>-->
      <el-select @change="resetHandler" multiple :collapse-tags="true" v-model="liabilityInsuranceAuditList" placeholder="职业责任险" :class="{'customSel':true , 'has-value': liabilityInsuranceAuditList }" clearable>
        <el-option
          v-for="item in insuresOptions"
          :key="item.value"
          :label="item.name"
          :value="item.value">
        </el-option>
      </el-select>
<!--    </div>-->

  </div>
  <div class="wrap_cls">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-if="initialized"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="carItem" v-for="(item,index) in vehicleList" :key="index" @click.stop="updateVehicle(item)">
          <div class="carCode">
            <div class="codeLeft">{{item.plateNumber}} / {{item.vehicleTypeString}}
              <span class="ml10"  :class="{'insuranceSuccess': item.vehicleStatus == 1, 'insuranceDanger': item.vehicleStatus == 2 ,'insuranceGray': !item.vehicleStatus }">{{ item.vehicleStatus == 1 ? '启用' :( item.vehicleStatus == 2 ? '停用' : ( item.vehicleStatus == 12 ? '否-服务商停用' : '无状态')) }} </span>
            </div>
            <div class="codeRight" v-if="item.vehicleStatus == 1" @click.stop="updateStatus(item)">停用</div>
          </div>
          <div class="juhe flex-between">
            <span class="zdJuhe">核验认证</span>
            <span class="flex-right">
            <span class="common_cls" v-if="item.inputStatusString" :class="getClass(item.inputStatusString)?.className">{{item.inputStatusString}}</span>
            <span class="common_cls" v-if="item.authStateString" :class="getClass(item.authStateString)?.className">{{item.authStateString}}</span>
          </span>
          </div>
          <div class="juhe flex-between">
            <span class="zdJuhe">救援责任险</span>
            <span class="flex-right" v-if="item.rescueInsurance">
            <span class="common_cls" @click.stop="showTip(item.liabilityInsuranceAuditMsg)" :class="getClass(item.rescueInsurance)?.className">{{item.rescueInsurance}}</span>
          </span>
          </div>
<!--          <div class="juhe flex-between">
            <span class="zdJuhe">车辆信息</span>
            <span class="flex-right" v-if="item.auditStatusStr">
            <span class="common_cls" @click.stop="showTip(item.auditMsg)" :class="getClass(item.auditStatusStr)?.className">{{item.auditStatusStr}}</span>
          </span>
          </div>-->
          <div class="juhe flex-between">
            <span class="zdJuhe">最近登录时间</span>
            <span class="flex-right">{{item.lastLoginTime}}</span>
          </div>
          <van-icon class="arrow_position" v-if="permissonList.includes('vehicleModifyBtn')" name="arrow" />
        </div>

      </van-list>
    </van-pull-refresh>
  </div>

  <van-dialog v-model="show" title="确定删除吗" show-cancel-button @confirm="handleConfirm"></van-dialog>
  <div class="btn_wrap" v-if="supplierId">
    <div class="btn" @click="nextToDriver">下一步</div>
  </div>
</div>

</template>

<script>
  import {Dialog} from "vant";
import { myMixins} from "@/utils/myMixins";
  import {supplierVehicleList, deleteVehicle, userOperationPermissions, enableVehicle, supplierSelectById} from "@/api/mine"
export default {
  name: "vehicleManage",
  mixins:[myMixins],
  data(){
    return{
      vehicleList:[],
      show:false,
      id:'',
      supplierId: '',
      routeId: '',
      initialized: false,
      pageNum:1,
      pageSize:10,
      total:'',
      isLoading: false,
      loading: false,
      finished: false,
      showPopover: false,
      permissonList:[],
      inputStatusList: [],
      searchVal: '',
      authStates: [],
      liabilityInsuranceAuditList: [],
      potentialFlag: '',
      inputStatusListOptions: [{
        name: '行驶证未录入',
        value: 0
      },{
        name: '行驶证核验通过',
        value: 1
      },{
        name: '行驶证核验不通过',
        value: 2
      }],
      authStatesOptions: [{
        name: '车头照片未录入',
        value: 1
      },{
        name: '车头照片认证通过',
        value: 2
      },{
        name: '车头照片认证不通过',
        value: 3
      }],
        insuresOptions: [{
          name: '待审核',
          value: 1
        },{
          name: '有责任险',
          value: 2
        },{
          name: '有货物险',
          value: 3
        },{
          name: '未通过',
          value: 4
        },{
          name: '无',
          value: 5
        },{
          name: '空',
          value: 6
        },{
          name: '原责任险过期',
          value: 8
        },{
          name: '原货物险过期',
          value: 9
        }],
    }
  },
  async mounted() {
    const urlParams = new URLSearchParams(window.location.search);
    const rawId = this.$route.query.id || urlParams.get('id');
    this.potentialFlag = this.$route.query.potentialFlag || urlParams.get('potentialFlag') || '';
    if (rawId) {
      this.routeId = rawId;
      await this.getSupplierById(Number(rawId));
    } else {
      this.initialized = true;
    }
    let _token = localStorage.getItem('token')
    if( _token ) {
      this.getPermissions();
    }
  },
  methods:{
    nextToDriver() {
      localStorage.setItem('lastRoute', JSON.stringify({ name: 'driverManage', query: { id: this.supplierId, potentialId: this.routeId, potentialFlag: this.potentialFlag } }));
      this.goPage('driverManage', { id: this.supplierId, potentialId: this.routeId, potentialFlag: this.potentialFlag });
    },
    async getSupplierById(id) {
      let res = await supplierSelectById({ id });
      this.supplierId = res?.data?.supplierId || '';
      this.initialized = true;
    },
    showTip(msg) {
      Dialog.alert({
        title: '未通过原因',
        message: msg,
      }).then(() => {
      });
    },
    getClass(id) {
      const ids = String(id)
      const steps = {
        '待审核': {
          className: 'main_cls'
        },
        '有责任险': {
          className: 'success_cls'
        },
        '有货物险': {
          className: 'info_cls'
        },
        '未通过': {
          className: 'danger_cls'
        },
        '原责任险过期': {
          className: 'danger_cls'
        },
        '原货物险过期': {
          className: 'danger_cls'
        },
        '无': {
          className: 'default_cls'
        },
        '空': {
          className: 'default_cls'
        },
        '行驶证未录入': {
          className: 'default_cls'
        },
        '行驶证核验通过': {
          className: 'success_cls'
        },
        '行驶证核验不通过': {
          className: 'danger_cls'
        },
        '车头照未录入': {
          className: 'default_cls'
        },
        '车头照认证通过': {
          className: 'success_cls'
        },
        '车头照认证不通过': {
          className: 'danger_cls'
        }
      }
      return steps[ids] || { className: 'default_cls' }
    },
    async onLoad(){
      await this.getVehicleList()
      if(this.total>10){
        this.pageNum++;
      }
      // 加载状态结束
      this.loading = false;
      // 数据全部加载完成
      if (this.vehicleList.length >= this.total) {
        this.finished = true;
      } else {
        this.finished = false;
      }
    },
    async onRefresh() {
      await this.resetHandler()
      setTimeout(() => {
        this.$toast('刷新成功');
        this.isLoading = false;
      }, 1000);
    },
    async getVehicleList(){
        let result = await supplierVehicleList({
          pageNum:this.pageNum,
          pageSize:this.pageSize,
          searchVal: this.searchVal,
          inputStatusList: this.inputStatusList,
          authStates: this.authStates,
          liabilityInsuranceAuditList: this.liabilityInsuranceAuditList,
          supplierId: this.supplierId || undefined,
        })
          this.total=result.total
          if(this.pageNum == 1){// 第一页直接赋值
            this.vehicleList=result.data;
          }else{// 第二页数据拼接
            let preList = this.vehicleList;
            let arr = result.data;
            this.vehicleList = preList.concat(arr)
          }
      },
    async getPermissions(){
      let res = await userOperationPermissions();
      this.permissonList = res.data
      // console.log("车辆管理",this.permissonList.includes('vehicleAddBtn','vehicleModifyBtn'))
    },
    deleteItem(id){//删除车辆
        this.show=true
        this.id=id
    },
   async handleConfirm(){//调删除车辆接口
      await deleteVehicle({
        vehicleId:this.id
      })
       this.$toast('删除成功');
      this.pageNum=1
      await this.getVehicleList();
    },
    async resetHandler() {
        this.pageNum=1
        this.finished = false;
        this.total = 0;
        // this.vehicleList = [];
        await this.getVehicleList();
    },
    updateStatus(item){
      if(item.vehicleStatus != 1){
        return
      }
      Dialog.confirm({
        message: '当前状态为启用，是否要改为停用?',
      }).then(async () => {
            // on confirm
        await enableVehicle({
          vehicleId:item.vehicleId,
          vehicleStatus:2,
        })
        this.pageNum=1
        await this.getVehicleList()
        console.log("item",item)
      }).catch(() => {
            // on cancel
      });
    },
    updateVehicle(item){//修改
      if( this.permissonList.includes('vehicleModifyBtn') ) {
        this.$router.push({
          name:'vehicleAdd',
          params:{
            id:item.vehicleId,
            supplierId:item.supplierId
          }
        })
      }
    },

  }
}
</script>

<style scoped lang="scss">
@import "@/styles/mixin.scss";
@import "@/styles/common.scss";
.ml10 {
  margin-left: 10px;
}
.wrap{
  background: #F4F5F7;
  @include wh(100%, 100%);
  overflow-y: auto;
}
.wrap_cls {
  width: 100%;
  padding-left: 13px;
  padding-right: 13px;
  box-sizing: border-box;
}
.common_cls {
  color: #fff;
  padding: 4px 8px;
  border-radius: 3px;
  margin-right: 6px;
}
.default_cls {
  background-color: #B0BEC5;
}
.danger_cls {
  background-color: red;
}
.success_cls {
  background-color: #4CAF50;
}
.info_cls {
  background-color: #FF9800;
}
.main_cls {
  background-color: #6C9BFF;
}
.navBar{
  margin-bottom: 46px;
  .rightWrap{
    @include wh(50px,20px);
    border-radius: 10px;
    opacity: 0.7;
    border: 1px solid #FFFFFF;
    @include flexTwoCenter;
    img{
      @include widHeiMar(9px,8px,4px);
    }
    .addTxt{
      @include fontWeightSize(bolder,11px);
      @include colorOpa(#FFFFFF,0.7);
    }
  }
}
.carItem{
  @include wh(100%,120px);
  background: #FFFFFF;
  box-shadow: 0px 2px 10px 0px rgba(216,216,216,0.5);
  @include radiusSizing(6px);
  padding: 11px 13px 11px 15px;
  margin-bottom: 10px;
  @include flexBetween;
  position: relative;
  .carCode{
    @include flexColBet;
    .codeLeft{
      @include fontWeightSize(bold,14px)
    }
    .codeRight{
      padding: 2px 8px;
      border: 1px solid #DDDDDD;
      border-radius: 3px;
      font-weight: bold;
    }
    .twoBtn{
      display: flex;
      align-items: center;
      button{
        border: none;
        padding: 4px  8px;
        border-radius: 3px;
        @include flexTwoCenter;
        @include fontWeightSize(bold,12px)
      }
      .del{
        border: 1px solid #DDDDDD;
        background-color: #FFFFFF;
      }
      .revise{
        @include bgFontColor( #FFFFFF,#354D93);
        margin-left: 15px;
      }
    }
  }
  .carType{
    width: 95%;
    white-space: nowrap; // 防止文本换行
    text-overflow: ellipsis; // 使用省略号表示超出部分
    overflow: hidden; // 隐藏超出容器宽度的内容
  }
  .carType,.zdJuhe{
    opacity: .7;
    @include fontWeightSize(400,12px)
  }
  .zdJuhe {
    width: 80px;
    text-align: right;
    margin-left: -10px;
  }
  .isYes{
    color: #09B820;
    @include fontWeightSize(400,12px);
  }
  .isNo{
    color: #FF0000;
    @include fontWeightSize(400,12px);
  }
}
.arrow_position {
  position: absolute;
  right: 5px;
  top: 50px;
  font-size: 20px;
  opacity: 0.6;
}
  .mr10 {
    margin-right: 10px;
  }
  .insuranceMain {
    color: #354D93;
  }
  .insuranceSuccess {
    color: green;
  }
  .insuranceTip {
    color: orange;
  }
  .insuranceDanger {
    color: red;
  }
  .insuranceGray{
    color: #aaa;
  }
  .flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

.filterWrap {
  width: 100%;
  padding-right: 13px;
  padding-left: 13px;
  display: flex;
  overflow-x: auto; /* 允许横向滚动 */
  white-space: nowrap; /* 防止子元素换行 */
  padding-bottom: 10px;
  -webkit-overflow-scrolling: touch; /* 在iOS上平滑滚动 */
  scrollbar-width: none; /* Firefox */
  padding-bottom: 10px;
  /*padding: 10px;*/
  margin-bottom: 10px;
  background-color: #fff;
  box-sizing: border-box;
  &::-webkit-scrollbar {
    display: none; /* Chrome/Safari */
  }
  .customSel {
    flex: 0 0 auto; /* 防止子元素被压缩 */
    width: calc(33% - 5px);
    /*width: 100%;*/
    height: 25px;
    background: #F5F5F5;
    border-radius: 4px;
    font-size: 10px;
    color: #323233;
    margin-right: 5px;
    ::v-deep .el-input__inner{
      padding: 0 2px;
      height: 25px;
      font-size: 10px;
      background: #F5F5F5;
      border-radius: 4px;
      border: none;
    }
    ::v-deep .el-input__icon{
      line-height: 25px;
      font-size: 10px;
      width: 18px;
      color: #2A5094;
    }
    ::v-deep .el-input__suffix{
      right: 2px;
    }
  }
  .customInput{
    /*width: 49%;*/
    width: 130px;
  }
  .has-value  ::v-deep .el-input__inner{
    background: #F1F6FF ;
    color: #007BE9;
    font-weight: bold;
    padding-left: 8px;
  }
  .has-value ::v-deep .el-input__icon{
    color: #007BE9;
  }
  .priceSel{
    display: flex;
    justify-content: space-around;
    align-items: center;
    color: #C0C4CC;
    .iconSpan{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 8px;
    }
  }
  .has-price{
    color: #007BE9 !important;
  }
}

::v-deep .el-select .el-select__tags>span {
  display: flex;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
  .flex-right {
    display: flex;
    flex: 1;
    justify-content: flex-start;
    margin-left: 10px;
  }
  .btn_wrap {
    width: 100%;
    padding: 15px 0;
    position: fixed;
    bottom: 10px;
    z-index: 10000;
    .btn {
      width: calc(100% - 80px);
      margin-left: 40px;
      height: 46px;
      background: #0E76F4;
      border-radius: 5px;
      font-size: 15px;
      color: #FFFFFF;
      text-align: center;
      line-height: 46px;
    }
  }

</style>
