<template>
  <div>
    <div class="table-wrapper">
      <div class="title">
        <h1>{{ groupName }}</h1>
        <div class="btn-group">
<!--          <el-button type="primary" size="small">Refresh Vehicle Info</el-button>-->
          <el-button type="primary" size="small" @click="done">Done</el-button>
        </div>
      </div>
      <div class="tags grey-bg">
        <label>Tags: </label>
        <ul v-if="tags.length">
          <li v-for="(item, i) in tags" :key="i">
            <i class="iconfont icon-tag"></i>
            {{item}}
          </li>
        </ul>
        <el-button type="primary" size="mini" @click="$refs.addTagDialog.show()">Add Tag</el-button>
      </div>
    </div>
    <div class="table-wrapper">
      <div class="title">
        <h1>Vehicle List</h1>
      </div>
      <div class="search">
        <div>
          <el-row :gutter="20">
            <el-col :span="6" v-for="(item, index) in vehicleAttrs" :key="index">
              <label>{{ item.name }}:</label>
                   <el-tooltip
                    class="box-item"
                    effect="dark"
                    :content="item.value"
                    placement="top-start"
                    :disabled='!item.value'
                  >
                    <el-select v-model="item.value" placeholder=" " no-match-text="No match data" no-data-text="No data" filterable clearable>
                      <el-option
                        v-for="(ele, index) in item.options"
                        :key="index"
                        :label="Object.keys(ele)[0]"
                        :value="ele[Object.keys(ele)[0]]">
                      </el-option>
                    </el-select>
                  </el-tooltip>
            </el-col>
          </el-row>
        </div>
        <div class="btn-group">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="$refs.vehicleAttrDialog.show()"></el-button>
          <el-button type="primary" size="small" @click="getTableData">Search</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="min-height:500px">
<!--        <el-table-column type="selection" width="100" align="center"></el-table-column>-->
        <el-table-column prop="vin" label="VIN"></el-table-column>
        <el-table-column prop="vid" label="VID"></el-table-column>
        <el-table-column prop="brandCode" label="Brand Code"></el-table-column>
        <el-table-column prop="brandName" label="Brand Name"></el-table-column>
        <el-table-column prop="modelCode" label="Model Code"></el-table-column>
        <el-table-column prop="modelName" label="Model Name"></el-table-column>
        <el-table-column prop="modelYear" label="Model Year"></el-table-column>
        <!-- <el-table-column prop="modelFamily" label="Model Family"></el-table-column> -->
        <el-table-column prop="platformName" label="Platform Name"></el-table-column>
        <el-table-column prop="platformVariant" label="Platform Variant"></el-table-column>
        <el-table-column prop="adsVersion" label="ADS Version"></el-table-column>
        <el-table-column prop="message" label="Message" show-overflow-tooltip></el-table-column>
        <template slot="empty" v-if="tableData.length == 0">
          <span>No data available</span>
        </template>
      </el-table>
      <el-pagination
        v-if="total > 0"
        :page-size="limit"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next"
      ></el-pagination>
    </div>
    <vehicle-attr-dialog ref="vehicleAttrDialog" @getVehicleAttr="getVehicleAttr" @getAdsVersion="getAdsVersion"/>
    <add-tag-dialog ref="addTagDialog" @getTagList='getTagList'/>
  </div>
</template>

<script>
import {GetVehicleByCondition, UpdateGroupCondition, GetVehicleInfoByVid, GetVINByVid} from "@/api/group";
import vehicleAttrDialog from './vehicleAttrDialog.vue';
import addTagDialog from './addTagDialog.vue';
export default {
  components: { vehicleAttrDialog, addTagDialog },
  props: ['groupName'],
  data() {
    return {
      id: this.$route.query.id,
      tableData: [],
      vehicleAttrs: [],
      tags: [],
      page: 1,
      limit: 10,
      total: 0,
      change:false
    };
  },
   mounted(){
    let that = this;
    this.$router.beforeEach((to, from, next) => {
      if (that.change) {
         this.$confirm(
        "Changes you made may not be saved.",
        "Are you sure you're leaving?",
        {
          confirmButtonText: "Confirm",
          cancelButtonText: "Cancel",
          type: "warning",
        }
      ).then(() => {
        that.change = false;
        next();
      })
      }else{
        next();
      }
    });

    window.onbeforeunload = function(e) {
      if (that.change) {
        var dialogText = 'Dialog text here';
        e.returnValue = dialogText;
        return dialogText;
      }else{
        return null
      }
    };
  },
  beforeDestroy(){
    window.onbeforeunload = null;
    this.change = false;
  },
  methods: {
    done(){
      this.change = false;
      let adsVersion = this.vehicleAttrs[0]
      if(!adsVersion.value){
        this.$message.error("Please select ADS version!");
        return;
      }
      let vehicleAttrs = this.vehicleAttrs.filter(item => item.value);
      let {id, groupName, tags} = this;
      // {\"and\":[{\"color\":\"blue\"},{\"brand_name\":\"Audi\"}]}
      let specificationJson = JSON.stringify({
        and: vehicleAttrs.map(item => {
          return {
            [item.field]: item.value
          }
        })
      })
      UpdateGroupCondition({
        id, groupName, specificationJson, tags
      }).then(() => {
        this.$router.back();
      })
    },
    getAdsVersion(adsVersion){
      this.vehicleAttrs.push({
        name: adsVersion.mappingName || adsVersion.attrName,
        field: adsVersion.attrName,
        value: '',
        options: adsVersion.values,
      });
    },
    getVehicleAttr(vehicleAttrs){
      let attrNameList = this.vehicleAttrs.map(item => item.field);
      vehicleAttrs.forEach(item => {
        if(!attrNameList.includes(item.mappingName)){
          this.vehicleAttrs.push({
            name: item.mappingName || item.attrName,
            field: item.attrName,
            value: '',
            options: item.values,
          });
        }
      })
      let attrNameArr = vehicleAttrs.map(item => item.attrName);
      this.vehicleAttrs = this.vehicleAttrs.filter(item => attrNameArr.includes(item.field) || item.field === 'ecus/8103/sw_version')
    },
    getTagList(tagList){
      this.tags = tagList.map(item => item.name);
    },
    getTableData() {
      let adsVersion = this.vehicleAttrs[0]
      if(!adsVersion.value){
        this.$message.error("Please select ADS version!");
        return;
      }
      this.change = true;
      this.page = 1;
      let vehicleAttrs = this.vehicleAttrs.filter(item => item.value);
      // {\"and\":[{\"color\":\"blue\"},{\"brand_name\":\"Audi\"}]}
      let specificationJson = JSON.stringify({
        and: vehicleAttrs.map(item => {
          return {
            [item.field]: item.value
          }
        })
      })
      GetVehicleByCondition({
        id: this.id,
        specificationJson
      }).then(res => {
        this.allTableData = res;
        this.total = this.allTableData.length;
        this.getTableDataByPage();
      })
    },
    getTableDataByPage(){
      let { page, limit } = this;
      let vidList = this.allTableData.slice((page - 1) * limit, page * limit);
      // if(!vidList.length) return;
      GetVehicleInfoByVid({vidList}).then(res => {
        GetVINByVid({vidList}).then(res2 => {
          this.tableData = res.map(item => {
            let info = JSON.parse(item['infos']) || {};
            return {
              vin: '',
              vid: item.vid,
              message: '',
              brandCode: info['brand_code'] || '',
              brandName: info['vehicleOrgLevel2'] || '',
              modelCode: info['model/model_codes'] || '',
              modelName: info['model/model_name'] || '',
              modelYear: info['model/model_year'] || '',
              platformName: info['platform_name'] || '',
              platformVariant: info['platform_variant'] || '',
              adsVersion: info['ads_version'] || '',
            }
          })
          this.tableData.forEach(item => {
            res2.forEach(ele => {
              if(item.vid === ele.vid){
                item.vin = ele.vin
                item.message = ele.message
              }
            })
          })
        })
      })
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getTableDataByPage();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getTableDataByPage();
    }
  },
};
</script>

<style scoped lang="scss">
.search {
  display: flex;
  padding: 0 5px;
  justify-content: space-between;
  >div{
    width: 100%;
    .el-row {
      .el-col {
        display: flex;
        margin-bottom: 20px;
        align-items: center;
        label {
          width: 120px;
          padding-right: 10px;
          font-size: 14px;
        }
        .el-select {
          flex: 1;
        }
      }
    }
  }
  .btn-group {
    width: 200px;
  }
}
</style>
