<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('driverAddBtn') || supplierId">
          <div class="rightWrap" @click="addDriver" >
            <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">
      <el-select @change="resetHandler" multiple :collapse-tags="true" v-model="idCardStatusList" placeholder="身份证录入状态" :class="{'customSel':true , 'has-value': idCardStatusList }" clearable>
        <el-option
            v-for="item in idCardStatusListOptions"
            :key="item.value"
            :label="item.name"
            :value="item.value">
        </el-option>
      </el-select>
      <el-select @change="resetHandler" multiple :collapse-tags="true" v-model="driverLicenseStatusList" placeholder="驾驶证录入状态" :class="{'customSel':true , 'has-value': driverLicenseStatusList }" clearable>
        <el-option
            v-for="item in driverLicenseStatusListOptions"
            :key="item.value"
            :label="item.name"
            :value="item.value">
        </el-option>
      </el-select>
      <el-select @change="resetHandler" multiple :collapse-tags="true" v-model="authStatusList" placeholder="认证状态" :class="{'customSel':true , 'has-value': authStatusList }" clearable>
        <el-option
            v-for="item in authStatesOptions"
            :key="item.value"
            :label="item.name"
            :value="item.value">
        </el-option>
      </el-select>
    </div>
    <div class="wrap_cls">
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
        >
          <div class="itemWrap" v-for="(item,index) in driverList" :key="index" @click.stop="!isMiniProgram(item) && updateDriver(item)">
            <div class="name-status">
              <div class="namephone">{{ item.driverName }} / {{ item.driverPhone }}
                <span style="margin-left: 10px" :class="item.states?.code == 1 ? 'statusYes' : 'statusNo'">{{ item.states?.label }}</span>
              </div>
              <div class="twoBtn">
<!--               只有启用状态下才展示停用按钮，小程序来源司机不显示-->
                <button v-if="!isMiniProgram(item) && permissonList.includes('driverModifyBtn') && item.states?.code==1" class="del" @click.stop="handleStatus(item)">停用</button>
                <!--              <button v-if="permissonList.includes('driverModifyBtn')" class="revise" @click="updateDriver(item)">修改</button>-->
              </div>
            </div>
            <div class="juhe flex-between">
              <span class="zdJuhe">录入状态</span>
              <span class="flex-right">
            <span class="common_cls" v-if="item.idCardStatusStr" :class="getClass(item.idCardStatus)?.className">{{item.idCardStatusStr}}</span>
            <span class="common_cls" v-if="item.driverLicenseStatusStr" :class="getClass(item.driverLicenseStatus)?.className">{{item.driverLicenseStatusStr}}</span>
          </span>
<!--              <span class="flex-right" v-if="item.idCardStatusStr">
                <span class="common_cls" :class="getClass(item.idCardStatus)?.className">{{item.idCardStatusStr}}</span>
              </span>-->
            </div>
            <div class="juhe flex-between">
              <span class="zdJuhe">认证状态</span>
              <span class="flex-right" v-if="item.authStatusStr">
                <span class="common_cls"  :class="getClass(item.authStatusStr)?.className">{{item.authStatusStr}}</span>
              </span>
            </div>
            <div class="" style="display: flex">
              <div class="sex" style="margin-right: 40px">
                <span class="halfOpci">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>
                <span class="allOpci">{{item.sex?.label}}</span>
              </div>
              <div class="carType">
                <span class="halfOpci">准驾车型:</span>
                <span class="allOpci">{{item.drivingModel}}</span>
              </div>
            </div>
            <div>
              <span class="halfOpci">身份证号:</span>
              <span class="allOpci">{{ item.identityCardNumber }}</span>
            </div>
            <van-icon class="arrow_position" v-if="!isMiniProgram(item) && permissonList.includes('driverModifyBtn')" name="arrow" />
<!--            <div>
              <span class="halfOpci">状&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;态:</span>
              <span :class="item.states?.code == 1 ? 'statusYes' : 'statusNo'">{{ item.states?.label }}</span>
            </div>-->
          </div>
        </van-list>
      </van-pull-refresh>

    </div>
    <div class="btn_wrap" v-if="supplierId">
      <div class="btn" @click="nextToResult">下一步</div>
    </div>
  </div>
</template>

<script>

import {myMixins} from "@/utils/myMixins"
import {driverList, enableAction, userOperationPermissions} from "@/api/mine"
import {Dialog} from "vant";
export default {
  name: "driverManage",
  mixins:[myMixins],
  data(){
    return{
      pageNum:1,
      pageSize:10,
      total:'',
      driverList:[],
      states:'',
      supplierId: '',
      routeId: '',
      initialized: false,
      potentialFlag: '',
      supplierType:'',
      count: 0,
      isLoading: false,
      loading: false,
      finished: false,
      permissonList:[],
      searchVal:'',
      idCardStatusList:[],
      driverLicenseStatusList:[],
      authStatusList:[],
      idCardStatusListOptions: [{
        name: '身份证未录入',
        value: 0
      },{
        name: '身份证核验通过',
        value: 1
      },{
        name: '身份证核验不通过',
        value: 2
      }],
      authStatesOptions: [{
        name: '免冠正面照未录入',
        value: 1
      },{
        name: '免冠正面照认证通过',
        value: 3
      },{
        name: '免冠正面照认证不通过',
        value: 2
      }],
      driverLicenseStatusListOptions: [{
        name: '驾驶证未录入',
        value: 0
      },{
        name: '驾驶证认证通过',
        value: 1
      },{
        name: '驾驶证认证不通过',
        value: 2
      }],
    }
  },
  mounted() {
    const urlParams = new URLSearchParams(window.location.search);
    this.supplierType = urlParams.get('supplierType');
    const rawId = this.$route.query.id || urlParams.get('id');
    this.supplierId = rawId ? Number(rawId) : '';
    const potentialId = this.$route.query.potentialId || urlParams.get('potentialId');
    this.routeId = potentialId;
    this.potentialFlag = this.$route.query.potentialFlag || urlParams.get('potentialFlag') || '';
    if(!rawId) {
      this.getPermissions();
    }
    // this.getDriverList()
  },
  methods:{
    nextToResult() {
      localStorage.setItem('lastRoute', JSON.stringify({ name: 'supplierAddResult', query: { id: this.routeId, potentialFlag: this.potentialFlag } }));
      this.goPage('supplierAddResult', { id: this.routeId, potentialFlag: this.potentialFlag });
    },
    isMiniProgram(item) {
      return item.registerFrom === '小程序' || (item.jobNumber && item.jobNumber.includes('小程序'))
    },
    getClass(id) {
      const ids = String(id)
      const steps = {
        0: {
          className: 'default_cls'
        },
        1: {
          className: 'success_cls'
        },
        2: {
          className: 'danger_cls'
        },
        '免冠正面照未录入': {
          className: 'default_cls'
        },
        '免冠正面照认证通过': {
          className: 'success_cls'
        },
        '免冠正面照认证不通过': {
          className: 'danger_cls'
        },
      }
      return steps[ids] || { className: 'default_cls' }
    },
    async resetHandler() {
      this.pageNum=1
      this.finished = false;
      this.total = 0;
      await this.getDriverList();
    },
    async onLoad(){
      await this.getDriverList()
      if (this.total>10){
        this.pageNum++;
      }
      // 加载状态结束
      this.loading = false;
      // 数据全部加载完成
      if (this.driverList.length >= this.total) {
        this.finished = true;
      }
    },
    onRefresh() {
      this.pageNum=1;
      // this.getDriverList()
      setTimeout(() => {
        this.$toast('刷新成功');
        this.isLoading = false;
      }, 1000);
    },
    addDriver(){
      if(this.supplierType == 1){
        this.$toast("无权添加")
      }else{
        this.$router.push({
          name: 'driverAdd',
          params: { supplierId: this.supplierId || undefined, potentialFlag: this.potentialFlag || undefined }
        })
      }
    },
    async getDriverList(){
        let res = await  driverList({
          pageNum:this.pageNum,
          pageSize:this.pageSize,
          searchVal: this.searchVal,
          idCardStatusList: this.idCardStatusList,
          driverLicenseStatusList: this.driverLicenseStatusList,
          authStatusList: this.authStatusList,
          supplierId: this.supplierId || undefined,
        });
        if(res.code == 200){
          this.total=res.total
          if(this.pageNum == 1){
            this.driverList=res.data
          }else{
            let preList = this.driverList;
            let arr = res.data;
            this.driverList = preList.concat(arr)
          }
        }
      console.log('this.driverList',this.driverList)
     },
    async getPermissions(){
      let res = await userOperationPermissions();
      this.permissonList = res.data
    },
    async handleStatus(item){
        if(item.states.code === 0){
            this.states = 1
        }else{
          this.states = 0
        }
      Dialog.confirm({
        message: '当前状态为启用，是否要改为停用?',
      }).then(async () => {
        await enableAction({
          driverId:item.driverId,
          states:this.states
        })
        this.pageNum = 1;
        await this.getDriverList();
      }).catch(() => {
      });

    },
    updateDriver(item){
      if(!this.permissonList.includes('driverModifyBtn')){//有权限才能修改
        return
      }
      // 在当前组件中进行路由跳转并传递参数对象
      this.$router.push({
        name: 'driverAdd',  // 目标路由的名称
        params: {
          id: item.driverId,                  // 参数对象的属性
          name: item.driverName,
          phone:item.driverPhone,
          drivingModel:item.drivingModel,
          identityCardNumber:item.identityCardNumber,
          states:item.states.code,
          createTime:item.createTime,
          supplierType:this.supplierType,
          drivingBeginDate: item.drivingBeginDate,
          drivingLicenceContrary: item.drivingLicenceContrary,
          drivingLicenceFront: item.drivingLicenceFront,
          drivingLicenceValidityDate: item.drivingLicenceValidityDate,
          icon: item.icon,
          identityCardContrary: item.identityCardContrary,
          identityCardFront: item.identityCardFront,
          lssueDate: item.lssueDate,
          drivingLicenceName: item.drivingLicenceName
        }
      });
    },
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/mixin.scss';
@import "@/styles/common.scss";

.wrap {
  background: #F4F5F7;
  //@include sizingPadding(13px,13px);
  @include wh(100%, 100%);
  overflow-y: auto;
}
.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);
    }
  }
}

.itemWrap {
  @include wh(100%, 140px);
  @include radiusSizing(6px);
  @include fontWeightSize(400, 12px);
  @include flexBetween;
  background: #FFFFFF;
  box-shadow: 0px 2px 10px 0px rgba(216, 216, 216, 0.5);
  margin-bottom: 10px;
  padding: 11px 13px 9px 15px;
  position: relative;
  .halfOpci {
    opacity: .5;
    margin-right: 5px;
  }
  .allOpci {
    opacity: 1;
  }
  .statusNo {
    color: red;
  }
  .statusYes {
    color: green
  }
}

.name-status {
  @include flexBetCen;
  .namephone {
    @include fontWeightSize(bold, 14px)
  }

  .twoBtn {
    display: flex;
    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;
    }
  }
}
.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;
  }
}
.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;
}
.arrow_position {
  position: absolute;
  right: 5px;
  top: 50px;
  font-size: 20px;
  opacity: 0.6;
}
.carType,.zdJuhe{
  opacity: .7;
  @include fontWeightSize(400,12px);
  margin-right: 8px;
}
/*.zdJuhe {
  width: 80px;
  text-align: right;
  margin-left: -10px;
}*/
.flex-between{
  line-height: 24px;
}
.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>
