<template>
  <div class="table-wrapper">
    <div class="title">
      <h1>Condition for vehicle group creation(Configuration)</h1>
      <div class="flex-row">
       
        <el-upload size="small"
          accept=".xlsx"
          class="upload-demo mr-10"
          :action="uploadPath"
          :show-file-list="false"
          :before-upload="beforeUploadFile"
          :headers="{ Authorization: getToken(), Deviceid: getDeviceId()}"
          :on-success="uploadFileSuccess"
          :on-error="uploadFileError"
        >
          <el-button type="primary">Import</el-button>
        </el-upload>
        <el-button type="primary" size="small" @click="updateVehicle"
          >Update Vehicle Attributes</el-button
        >
        <el-button type="primary" size="small" @click="verificationAllData"
          >Verification</el-button
        >
        <el-button type="primary" size="small" @click="showAddDialog"
          >Add Attribute</el-button
        >
        <a style="margin-left:10px" href="VehicleAttribute.xlsx">
          <el-button type="primary" style="line-height:19px" icon="el-icon-download" class="m-search-btn" size="small">VehicleAttribute.xlsx</el-button>
        </a>
      </div>
    </div>
    <el-table :data="tableData" style="min-height: 500px">
      <el-table-column prop="attrName" label="Attribute Name"></el-table-column>
      <el-table-column
        prop="mappingName"
        label="Mapping Name"
      ></el-table-column>
      <el-table-column prop="isDisplay" label="Is Display">
        <template v-slot="scope">
          <el-switch
            v-if="scope.row.attrName !== 'ecus/8103/sw_version'"
            v-model="scope.row.isDisplay"
            active-color="#13ce66"
            @change="changeStatus(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="Remark"></el-table-column>
      <el-table-column prop="action" label="Action" width="150">
        <template v-slot="scope">
          <el-popconfirm
            v-if="scope.row.attrName !== 'ecus/8103/sw_version'"
            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.id)"
          >
            <el-button type="danger" slot="reference" size="mini"
              >Delete</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
      <template slot="empty" v-if="tableData.length == 0">
        <span>No data available</span>
      </template>
    </el-table>
    <el-dialog
      title="Add Attribute"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form :model="form" ref="ruleForm" label-width="120px" :rules="rules">
        <el-form-item prop="attrName" label="Attribute Name">
          <el-input v-model="form.attrName"></el-input>
        </el-form-item>
        <el-form-item prop="mappingName" label="Mapping Name">
          <el-input v-model="form.mappingName"></el-input>
        </el-form-item>
      </el-form>
      <el-alert
        v-if="verificationText"
        :title="verificationText"
        type="error"
        :closable="false"
      ></el-alert>
      <span slot="footer" class="dialog-footer">
        <el-button type="warning" size="small" @click="verificationField"
          >Verification</el-button
        >
        <el-button type="primary" size="small" @click="addAttribute"
          >Confirm</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  ChangeAttributeStatus,
  DeleteAttribute,
  GetAttribute,
  UploadAttribute,
  VerificationAttribute,
  AddAttribute,
  CheckedAttr,
  UpdateVehicle,
} from "@/api/datasource";
import { Loading } from "element-ui";
import { getToken, getDeviceId } from "@/utils/auth";
export default {
  data() {
    return {
      loading: null,
      uploadPath: `${process.env.VUE_APP_BASE_API}/attribute/excel/upload/check`,
      tableData: [],
      form: {
        attrName: "",
        mappingName: "",
      },
      rules: {
        attrName: [
          {
            required: true,
            message: "Please input attribute name",
            trigger: "blur",
          },
        ],
        mappingName: [
          {
            required: true,
            message: "Please input mapping name",
            trigger: "blur",
          },
        ],
      },
      dialogVisible: false,
      verificationText: "",
    };
  },
  created() {
    this.getTableData();
  },
  methods: {
    getToken,
    getDeviceId,
    getTableData() {
      GetAttribute().then((res) => {
        this.tableData = res.map((item) => {
          return {
            ...item,
            isDisplay: item.status === "ENABLE",
          };
        });
      });
    },
    toDelete(id) {
      DeleteAttribute(id).then(() => {
        this.$message.success("Delete successfully!");
        this.getTableData();
      });
    },
    changeStatus(row) {
      ChangeAttributeStatus({
        id: row.id,
        status: row.status === "ENABLE" ? "DISABLE" : "ENABLE",
      }).then(() => {
        this.getTableData();
      });
    },
    beforeUploadFile() {
      this.loading = Loading.service({
        text: "Loading",
        customClass: "loading",
      });
    },
    uploadFileSuccess(data) {
      this.loading.close();

      const uploadData = {
        list: data?.list ?? [],
        adapterlist: data?.adapterlist ?? []
      };

      if (data.message) {
        this.$confirm(data.message, "", {
          confirmButtonText: "Confirm",
          cancelButtonText: "Cancel",
          type: "warning",
        }).then(() => {
            // this.$message({
            //   type: 'success',
            //   message: 'Import was successful'
            // });
            UploadAttribute(uploadData).then(() => {
              // this.$message.success("Delete successfully!");
              this.getTableData();
            });
            console.log(data.list);
          }).catch(() => {
            this.$message({
              type: "info",
              message: "Import has been cancelled",
            });
          });
      } else {
        UploadAttribute(uploadData).then(() => {
          // this.$message.success("Delete successfully!");
          this.getTableData();
        });
      }

      // this.getTableData();
    },
    uploadFileError(err) {
      this.loading.close();
      this.$message.error(JSON.parse(err.message).message);
    },
    updateVehicle() {
      this.$confirm(
        "Are you sure synchronize the field information of vehicles coming from DT?",
        "Warning",
        {
          confirmButtonText: "Confirm",
          cancelButtonText: "Cancel",
          type: "warning",
        }
      ).then(() => {
        UpdateVehicle().then(() => {
          this.$message.success("Update Vehicle Attributes successfully!");
          this.getTableData();
        });
      });
    },
    verificationAllData() {
      VerificationAttribute().then((res) => {
        if (!res) {
          this.$message.success("Verification successfully!");
          this.getTableData();
        }
      });
    },
    showAddDialog() {
      this.verificationText = "";
      this.dialogVisible = true;
      setTimeout(() => {
        this.$refs.ruleForm.resetFields();
      }, 100);
    },
    verificationField() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          CheckedAttr(this.form).then((res) => {
            if(res === '') {
               this.$message.success("Verification successfully!");
               this.verificationText = res;
            } else {
               this.verificationText = res;
            }
          });
        }
      });
    },
    addAttribute() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          AddAttribute(this.form).then((res) => {
            if (res.id) {
              this.dialogVisible = false;
              this.getTableData();
            }
          });
        }
      });
    },
  },
};
</script>
