<template>
  <div class="table-wrapper">
      <div class="title">
        <h1>Group List</h1>
        <div class="btn-group">
          <el-button type="primary" size="small" @click="showGroupDialog('add')">Add New Group</el-button>
          <el-button type="danger" size="small" @click="deleteAll">Delete</el-button>
        </div>
      </div>
      <div class="search">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="item">
              <label>Group Name</label>
              <el-input v-model="groupName" placeholder="Please input group name" clearable/>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="item">
              <label>Status</label>
              <el-select v-model="status" placeholder="Please select status">
                <el-option
                  v-for="(item, i) in statusList"
                  :key="i"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="item">
              <label>Vehicle Number</label>
              <el-input v-model="totalMin" onkeyup="this.value=this.value.replace(/\D/g,'')" clearable style="width: 100px;"/>
              <span style="display: inline-block; margin: 0 10px;">-</span>
              <el-input v-model="totalMax" onkeyup="this.value=this.value.replace(/\D/g,'')" clearable style="width: 100px;"/>
            </div>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="getTableData">Search</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table :data="tableData" @selection-change="handleSelectionChange" style="min-height:500px">
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column prop="groupName" label="Group Name"></el-table-column>
        <el-table-column prop="status" label="Status">
          <template v-slot="scope">
            <el-tooltip :content="scope.row.statusDes" placement="top">
              <el-tag v-if="scope.row.status == 'ENABLE'" type="success" style="width: 65px; text-align: center">{{ scope.row.status }}</el-tag>
              <el-tag v-else type="danger" style="width: 65px; text-align: center">{{ scope.row.status }}</el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="Vehicle Number"></el-table-column>
        <el-table-column prop="action" label="Action" width="170px">
          <template v-slot="scope">
            <el-button type="primary" size="mini" class="btn" v-if="scope.row.mold === 0" @click="showGroupDialog('edit', scope.row)">Edit</el-button>
            <el-button type="primary" size="mini" class="btn" v-else @click="detail(scope.row.id)">View</el-button>
            <el-popconfirm
              class="ml-10 mr-10"
              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>
        <el-table-column prop="mold" label="Group By Type">
          <template v-slot="scope">
            {{scope.row.mold ? (scope.row.mold === 1 ? 'By Criteria' : 'Manual') : ''}}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="Creator"></el-table-column>
        <el-table-column prop="creationDate" label="Create Time"></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"
        :current-page.sync="page"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        background
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
      ></el-pagination>
      <el-dialog :title="(groupId?'Edit':'Add') + ' Group'" :visible.sync="visible" width="600px">
        <el-form
          :model="form"
          ref="ruleForm"
          label-width="100px"
          :rules="rules"
        >
          <el-form-item label="Group Name" prop="name">
            <el-input v-model="form.name" :disabled="!!groupId" placeholder="Please input group name"></el-input>
          </el-form-item>
          <el-form-item label="Add Vehicle" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio label="1">Search by Condition</el-radio>
              <el-radio label="2">Manual Addition</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="visible = false">Cancel</el-button>
          <el-button type="primary" size="small" @click="addGroup">Confirm</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import pieChart from "./components/pieChart";
import barChart from "./components/barChart";
import { GetGroups, AddGroup, DeleteGroup, DeleteAllGroup } from "@/api/group";
export default {
  components: { pieChart, barChart },
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      groupId: "",
      visible: false,
      form: {
        name: "",
        type: "1",
      },
      rules: {
        name: [
          { required: true, message: "Please input group name", trigger: "blur" },
        ],
      },
      groupName: '',
      status: 'ALL',
      statusList: ['ALL', 'NONE', 'RUN', 'DISABLE', 'ENABLE'],
      totalMin: '',
      totalMax: '',
      page: 1,
      limit: 10,
      total: 0,
    };
  },
  created() {
    this.getTableData();
  },
  methods: {
    getTableData() {
      const { groupName, status, totalMin, totalMax, page, limit } = this;
      GetGroups({
        groupName,
        status,
        totalMin,
        totalMax,
        pageNo: page,
        pageSize: limit
      }).then((res) => {
        const { content, totalElements } = res;
        this.tableData = content;
        this.total = totalElements;
        if (page > 1 && content.length === 0) {
          this.handleCurrentChange(page - 1);
        }
      });
    },
    showGroupDialog(type, row = {}){
      this.visible = true;
      setTimeout(() => {
        this.$refs.ruleForm.resetFields();
        if(type === 'add'){
          this.groupId = '';
        }else {
          this.form.name = row['groupName']
          this.groupId = row['id'];
        }
      }, 100)

    },
    addGroup() {
      if(this.groupId){ //edit
        this.$router.push({ path: "/groupManagement/addVin", query: {id: this.groupId, type: this.form.type}});
      }else { //add
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            AddGroup({ groupName: this.form.name }).then((res) => {
              if (res.id) {
                this.$router.push({ path: "/groupManagement/addVin", query: {id: res.id, type: this.form.type}});
              }
            });
          }
        });
      }
    },
    detail(id) {
      this.$router.push({ path: "/groupManagement/detail", query: { id }});
    },
    toDelete(id) {
      DeleteGroup(id).then(() => {
        this.$message.success("Delete successfully!");
        this.handleCurrentChange(this.page);
      });
    },
    deleteAll(){
      if(!this.multipleSelection.length){
        this.$message.error("Please select some groups!");
        return;
      }
      this.$confirm('Are you sure to delete these groups?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        DeleteAllGroup({
          idList: this.multipleSelection.map(item => item.id)
        }).then(() => {
          this.$message.success("Delete successfully!");
          this.handleCurrentChange(this.page);
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.handleCurrentChange(1);
    },
  },
};
</script>

<style scoped lang="scss">
.btn {
  width: 60px !important;
}
</style>
