<template>
    <div class="table-wrapper">
        <div class="title">
          <h1>Ticket Name: {{ ticketName }}
            <div style="display: inline-block; margin-left: 10px;">
              <el-tag v-if="status == 'DONE'" type="success">{{ status }}</el-tag>
              <el-tag v-else-if="status == 'HOLD'" type="warning">{{ status }}</el-tag>
              <el-tag v-else type="danger">{{ status }}</el-tag>
            </div>
          </h1>
          <div class="btn-group">
            <el-button type="primary" size="small" v-if="status === 'NONE'" @click="showVinDialog">Add New Vin</el-button>
            <el-button type="primary" size="small" v-if="status === 'NONE'" @click="submitVehicle">Submit Vehicle</el-button>
            <el-button type="primary" size="small" v-if="status === 'HOLD'" @click="changeStatus">Done</el-button>
          </div>
        </div>
        <div class="description">
          <p>Description: {{ description }} <span v-if="status !== 'DONE'" @click="showDescDialog">Edit description</span></p>
        </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="action" label="Action" width="100px" v-if="status === 'NONE'">
            <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>
        <el-dialog title="Add Vin" :visible.sync="vinVisible" width="600px">
          <el-form :model="vinForm" ref="vinForm" label-width="60px" :rules="vinRules">
            <el-form-item label="Vin" prop="vin">
              <el-input type="textarea" :rows="5" v-model="vinForm.vin" placeholder='Separate multiple vin with commas ","'/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="vinVisible = false"
              >Cancel</el-button
            >
            <el-button type="primary" size="small" @click="addVin"
              >Confirm</el-button
            >
          </div>
        </el-dialog>
        <el-dialog title="Edit Description" :visible.sync="descVisible" width="600px">
          <el-form
            :model="descForm"
            ref="descForm"
            label-width="0"
            :rules="rules"
          >
            <el-form-item label="" prop="description">
              <el-input
                type="textarea"
                v-model="descForm.description"
                rows="5"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="descVisible = false"
              >Cancel</el-button
            >
            <el-button type="primary" size="small" @click="confirmDescription"
              >Confirm</el-button
            >
          </div>
        </el-dialog>
      </div>
</template>

<script>
import {
  GetTicketDetail,
  UpdateTicketInfo,
  UpdateTicketVin,
  ChangeTicketStatus, GetTicketVehicles, GetTicketList,
} from "@/api/ticket";
import {GetVehicleInfoByVid, GetVIDByVin} from "@/api/group";
export default {
  data() {
    return {
      id: this.$route.query.id,
      allVehicles: [],
      vehicles: [],
      vinVisible: false,
      descVisible: false,
      vinForm: {
        vin: "",
      },
      vinRules: {
        vin: [
          { required: true, message: "Please input vin", trigger: "blur" },
          // { pattern: /^(?=.*[0-9])(?=.*[A-Z]).{17}$/, message: 'The input contains illegal characters', trigger: 'blur'},
        ],
      },
      descForm: {
        description: "",
      },
      rules: {
        description: [
          { required: true, message: "Please input description", trigger: "blur" },
        ],
      },
      ticketName: "",
      description: "",
      status: "",
      page: 1,
      limit: 10,
      total: 0,
      change:false,
    };
  },
  created() {
    this.getDetail();
  },
   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: {
    getDetail() {
      GetTicketDetail(this.id).then((res) => {
        this.ticketName = res.ticketName;
        this.status = res.status;
        this.description = res.ticketDetail || '';
        if(this.status === 'HOLD' || this.status === 'DONE'){
          this.getTicketVehicles();
        }
      });
    },
    getTicketVehicles(){
      const { id, page, limit } = this;
      GetTicketVehicles({ id, pageNo: page, pageSize: limit }).then((res) => {
        const { content, totalElements } = res;
        this.vehicles = content.map(item => {
          let info = JSON.parse(item['infos']) || {};
          this.adsVersion = info['ads_version'] || '';
          return {
            vin: item.vin,
            vid: item.vid,
            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.total = totalElements;
      });
    },
    showDescDialog(){
      this.descVisible = true;
      this.descForm.description = this.description;
    },
    confirmDescription() {
      this.$refs.descForm.validate((valid) => {
        if (valid) {
          UpdateTicketInfo({
            id: this.id,
            description: this.descForm.description,
          }).then(() => {
            this.descVisible = false;
            this.getDetail();
          });
        }
      });
    },
    submitVehicle(){
      let { id, allVehicles } = this;
      this.change =false;
      if(allVehicles.length == 0) {
        this.$message('Please add vin.');
      } else {
        UpdateTicketVin({ id, vinList: allVehicles }).then(() => {
          this.vinVisible = false;
          this.getDetail();
        });
      }  
    },
    showVinDialog(){
      this.vinVisible = true;
      setTimeout(() => {
        this.$refs.vinForm.resetFields();
      }, 100)
    },
    addVin() {
      console.log(this.vinForm.vin);
      var check = true;
      var reg = /^(?=.*[0-9])(?=.*[A-Z]).{17}$/;
      let vinList = this.vinForm.vin.split(',').map(item => item.trim());
      vinList.forEach(function(item, index, vinList) {
        if(item.match(reg) == null) {
          check = false;
          // alert('The input contains illegal characters.');
          // this.$message('The input contains illegal characters.');
        }      
      });
      if(!check) {
        this.$message('The input vines contains illegal characters.');
      } else {
        this.$refs.vinForm.validate((valid) => {
          if (valid) {
            this.vinVisible = false;
            let vinList = this.vinForm.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;
          }
        });
      }
      // this.$refs.vinForm.validate((valid) => {
      //   if (valid) {
      //     this.vinVisible = false;
      //     let vinList = this.vinForm.vin.split(',').map(item => item.trim());
      //     // this.allVehicles = Array.from(new Set([...this.allVehicles, ...vinList]));
      //     // this.total = this.allVehicles.length;
      //     // this.getVehicles();
      //   }
      // });
    },
    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.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'] || '';
              }
            })
          });
        })
      })
    },
    changeStatus() {
      ChangeTicketStatus({ id: this.id, status: "DONE" }).then((res) => {
        if (res.status === "DONE") {
          this.$message.success("Change Status successfully!");
          this.$router.push('/ticketManagement');
        }
      });
    },
    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>

<style lang="scss" scoped>
.description {
  padding-left: 5px;
  margin-bottom: 20px;
  span {
    display: inline-block;
    margin-left: 10px;
    color: #0241a5;
    text-decoration: underline;
    cursor: pointer;
  }
}
</style>
