<template>
  <div class="table-wrapper">
    <div class="title">
      <h1>{{ groupName }}</h1>
      <div class="btn-group">
        <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 class="title">
      <h1>Vehicle List</h1>
      <div class="btn-group">
        <el-button type="primary" size="small" @click="showVinDialog">Add New Vin</el-button>
      </div>
    </div>
    <el-table :data="vehicles" style="min-height:500px">
      <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>
      <el-table-column prop="action" label="Action" width="100px">
        <template v-slot="scope">
          <el-popconfirm
            confirm-button-text="Yes"
            cancel-button-text="No"
            icon="el-icon-info"
            icon-color="red"
            title="Are you sure to delete this?"
            @confirm="toDelete(scope.row.vin)"
          >
            <el-button type="danger" slot="reference" size="mini">Delete</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
      <template slot="empty" v-if="vehicles.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>
    <add-tag-dialog ref="addTagDialog" @getTagList='getTagList'/>
    <el-dialog title="Add Vin" :visible.sync="dialogVisible" width="600px">
      <el-form
        :model="form"
        ref="ruleForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="Vin" prop="vin">
          <el-input type="textarea" :rows="5" v-model="form.vin" placeholder='Separate multiple vin with commas ","'/>
        </el-form-item>
        <el-form-item label="ADS Version" prop="adsVersion">
          <el-input type="text" v-model="form.adsVersion"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" size="small" @click="addVin">Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {GetVehicleInfoByVid, GetVIDByVin, UpdateGroupVehicle} from "@/api/group";
import addTagDialog from './addTagDialog.vue';
import {uniqueArr} from "@/utils/utils";
export default {
  components: { addTagDialog },
  props: ["groupName"],
  data() {
    return {
      id: this.$route.query.id,
      allVehicles: [],
      vehicles: [],
      dialogVisible: false,
      form: {
        vin: "",
        adsVersion: ""
      },
      rules: {
        vin: [
          { required: true, message: "Please input vin", trigger: "blur" },
        ],
        adsVersion: [
          { required: true, message: "Please input ads version", trigger: "blur" },
        ],
      },
      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;
      if(this.allVehicles.length > 0) {
        let {id, tags, allVehicles, form } = this;
        UpdateGroupVehicle({
          id, tags, vinList: allVehicles, version: form.adsVersion
        }).then(() => {
          this.$router.back();
        })
      } else {
        this.$message('No vehicle data');
      }
    },
    getTagList(tagList){
      this.tags = tagList.map(item => item.name);
    },
    showVinDialog(){
      this.dialogVisible = true;
      setTimeout(() => {
        this.$refs.ruleForm.resetFields();
      }, 100)
    },
    addVin() {
      var check = true;
      var reg = /^(?=.*[0-9])(?=.*[A-Z]).{17}$/;
      let vinList = this.form.vin.split(',').map(item => item.trim());
      vinList.forEach(function(item, index, vinList) {
        if(item.match(reg) == null) {
          check = false;
        }      
      });
      if(!check) {
        this.$message('The input vines contains illegal characters.');
      } else {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.dialogVisible = false;
            let vinList = this.form.vin.split(',').map(item => item.trim());
            this.allVehicles = Array.from(new Set([...this.allVehicles, ...vinList]));
            this.total = this.allVehicles.length;
            this.getVehicles();
            this.change = true;
          }
        });
      }
    },
    getVehicles(){
      let { allVehicles, page, limit } = this;
      GetVIDByVin({
        vinList: allVehicles.slice((page - 1) * limit, page * limit)
      }).then(res => {
        this.vehicles = res.map(item => {
          return {
            ...item,
            brandCode: '',
            brandName: '',
            modelCode: '',
            modelName: '',
            modelYear: '',
            platformName: '',
            platformVariant: '',
            adsVersion: '',
          }
        });
        GetVehicleInfoByVid({
          vidList: res.map(item => item.vid),
          vinList: res.map(item => item.vin)
        }).then(res2 => {
          this.vehicles.forEach(item => {
            res2.forEach(ele => {
              if(item.vid === ele.vid){
                let info = JSON.parse(ele['infos']) || {};
                item.message = ele.message;
                item.brandCode = info['brand_code'] || '';
                item.brandName = info['vehicleOrgLevel2'] || '';
                item.modelCode = info['model/model_codes'] || '';
                item.modelName = info['model/model_name'] || '';
                item.modelYear = info['model/model_year'] || '';
                item.platformName = info['platform_name'] || '';
                item.platformVariant = info['platform_variant'] || '';
                item.adsVersion = info['ads_version'] || '';
              }
            })
          });
        })
      })
    },
    toDelete(vin){
      let index = this.allVehicles.findIndex(item => item === vin);
      this.allVehicles.splice(index, 1);
      this.total = this.allVehicles.length;
      this.getVehicles();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getVehicles();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.handleCurrentChange(1);
    },
  },
};
</script>


