<template>
  <div>
    <div class="table-wrapper">
      <div class="title">
        <h1>Configuration List</h1>
        <div class="btn-group">
          <el-button type="primary" size="small" @click="showConfigDialog">New Configuration</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>Source API</label>
              <el-select v-model="apiForm" placeholder="Please select API">
                <el-option v-for="(item, i) in apiFormList" :key="i" :label="item" :value="item"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="item">
              <label>ADS Version</label>
              <el-input v-model="adsVersion" placeholder="Please input adsVersion" clearable/>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="item">
              <label>Subscription</label>
              <el-input v-model="subscription" placeholder="Please input subscription" clearable/>
            </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" :default-sort="{prop: 'creationDate', order: 'descending'}" @sort-change="handleSort" @selection-change="handleSelectionChange1" style="min-height:500px">
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column prop="apiForm" label="Source API"></el-table-column>
        <el-table-column prop="adsVersion" label="ADS Version" sortable="custom" :sort-orders="['ascending', 'descending']"></el-table-column>
        <el-table-column prop="subscription" label="Subscription" sortable="custom" :sort-orders="['ascending', 'descending']"></el-table-column>
        <el-table-column prop="description" label="Comments" sortable="custom" :sort-orders="['ascending', 'descending']" show-overflow-tooltip>
          <!-- <template slot-scope="scope">
            <el-tooltip :content="scope.row.description"></el-tooltip>
          </template> -->
        </el-table-column>
        <el-table-column prop="groupName" label="Group Name" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createBy" label="Creator"></el-table-column>
        <el-table-column prop="creationDate" label="Create Time" sortable="custom" :sort-orders="['ascending', 'descending']"></el-table-column>
        <el-table-column prop="action" label="Action" width="170px">
          <template v-slot="scope">
            <el-button type="primary" size="mini" @click="showDetail(scope.row.dccDetail)">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>
        <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>
    </div>
    <el-dialog title="Create New Configuration" :visible.sync="visible" width="800px">
      <el-form
        :model="form"
        ref="ruleForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="Subscription" prop="subscription">
          <el-input v-model="form.subscription" placeholder="Please input subscription, subscription needs to be unique" clearable></el-input>
        </el-form-item>
        <el-form-item label="Comments" prop="comments">
          <el-input v-model="form.comments" placeholder="Please input comments" clearable></el-input>
        </el-form-item>
        <el-form-item label="Source API" prop="apiForm">
          <el-select v-model="form.apiForm" @change="showApiFormContent" placeholder="Please select API" clearable>
            <el-option v-for="(item, index) in apiFormList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="StartTime" v-show="isShowTime" prop="sTime" clearable>
          <el-date-picker v-model="form.sTime" type="datetime" placeholder="Please Select start time" clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="EndTime" v-show="isShowTime" prop="eTime" clearable>
          <el-date-picker v-model="form.eTime" type="datetime" placeholder="Please select end time" clearable></el-date-picker>
        </el-form-item> -->
        <el-form-item label="Time Slot" v-show="isShowTime" prop="timeSlot" clearable>
          <el-date-picker v-model="form.timeSlot" type="datetimerange" start-placeholder="Start Time" end-placeholder="End Time" value-format="timestamp" :picker-options="{disabledDate: (time) => {return time.getTime() > Date.now() - 60 * 1000 ;},selectableRange: selectTimeRange,}"></el-date-picker>
        </el-form-item>
        <el-form-item label="ADS Version" prop="adsVersion">
          <el-select v-model="form.adsVersion" @change="getEventData" placeholder="Please select ads version" clearable>
            <el-option v-for="(item, i) in adsVersionList" :key="i" :label="Object.keys(item)[0]" :value="Object.keys(item)[0]"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table :data="eventList" @selection-change="handleSelectionChange2">
        <el-table-column type="selection" :selectable="checkSelectable" align="center" width="100px"></el-table-column>
        <el-table-column property="eventId" label="Event ID" show-overflow-tooltip></el-table-column>
        <el-table-column property="eventName" label="Event Name" show-overflow-tooltip></el-table-column>
        <el-table-column property="eventDesc" label="Event Desc" show-overflow-tooltip></el-table-column>
        <el-table-column property="eventType" label="Event Type" show-overflow-tooltip></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible = false">Cancel</el-button>
        <el-button type="primary" size="small" @click="addConfig">Confirm</el-button>
      </div>
    </el-dialog>
    <config-dialog ref="configDialog" />
  </div>
</template>

<script>
import {GetPolicy, GetEventList, CreateConfig, DetelePolicy, GetAdsVersion} from "@/api/configuration";
import { getAttributeKV } from '@/api/group';
import configDialog from "./components/configDialog.vue";
export default {
  components: { configDialog },
  data() {
    return {
      apiFormList: ['Common', 'On-Demand Pull'],
      isShowTime: false,
      apiForm: "",
      adsVersion: '',
      subscription: '',
      tableData: [],
      visible: false,
      adsVersionList: [],
      form: {
        subscription: "",
        comments: "",
        apiForm: "",
        sTime: "",
        eTime: "",
        timeSlot: [],
        adsVersion: ""
      },
      rules: {
        subscription: [
          { required: true, message: "Please input subscription", trigger: "blur" },
        ],
        comments: [
          { required: true, message: "Please input comments", trigger: "blur" },
        ],
        apiForm: [
          { required: true, message: "Please select apiForm", trigger: "change" },
        ],
        adsVersion: [
          { required: true, message: "Please select ads version", trigger: "change" },
        ],
        // sTime: [
        //   { required: true, message: "Please select start time", trigger: "change" },
        // ],
        // eTime: [
        //   { required: true, message: "Please select end time", trigger: "change" },
        // ],
        timeSlot: [
          { type: 'array', required: true, message: "Please select time", trigger: "change" },
        ]
      },
      eventList: [],
      multipleSelection1: [],
      multipleSelection2: [],
      sortBy: {sortField: 'creationDate', sortOrder: 'desc'},
      page: 1,
      limit: 10,
      total: 300,
      pickerOptions: {
        value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      }
    };
  },
  created() {
    this.getTableData();
    this.getAdsVersionList();
  },
  methods: {
    handleSort({prop, order}) {
      let sortOrderObj = {
        'ascending': 'asc',
        'descending': 'desc',
      }
      if(!(prop || order)) {
        this.sortBy = {sortField: '', sortOrder: ''}
      }else {
        let sortField = prop;
        let sortOrder = sortOrderObj[order];
        this.sortBy = {sortField, sortOrder}
      }
      this.getTableData();
    },
    getTableData() {
      const { apiForm, adsVersion, subscription, sortBy, page, limit } = this;
      GetPolicy({
        apiForm,
        adsVersion,
        subscription,
        sortField: sortBy['sortField'],
        sortOrder: sortBy['sortOrder'],
        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);
        }
      });
    },
    showConfigDialog(){
      this.visible = true;
      this.isShowTime = false;
      this.form.sTime = "";
      this.form.eTime = "";
      setTimeout(() => {
        this.$refs.ruleForm?.resetFields();
        this.eventList = [];
      }, 100)
    },
    addConfig() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let {timeSlot} = this.form;
          if(new Date(timeSlot[1]).getTime() - new Date(timeSlot[0]).getTime() > 2 * 60 * 60 * 1000){
            this.$message.error('You can only choose a time range within 2 hours!')
            return;
          }
          CreateConfig({
            ...this.form,
            events: this.multipleSelection2
          }).then(() => {
            this.visible = false;
            this.getTableData();
          })
        }
      });
    },
    getAdsVersionList(){
      // GetAdsVersion().then(res => {
      //   this.adsVersionList = res;
      // })
      getAttributeKV().then(res => {
        this.adsVersionList = res.filter(item=>item.attrName=='ecus/8103/sw_version')[0].values
      })
    },
    getEventData() {
      if (!this.form.adsVersion) {
        this.eventList = [];
        return;
      }
      GetEventList({
        adsVersion: this.form.adsVersion
      }).then(res => {
        if(res && res.code && res.code !== 200){
          this.eventList = [];
        }else {
          this.eventList = res;
        }
      })
    },
    checkSelectable(row){
      if("Common" == this.form.apiForm && row.eventType === 'precollection') {
        return false;
      }else {
        return true;
      }
    },
    showApiFormContent() {
      if("Common" == this.form.apiForm) {
        this.isShowTime = false;
        // this.rules.sTime[0].required = false;
        // this.rules.eTime[0].required = false;
        // this.form.sTime = "";
        // this.form.eTime = "";
        this.rules.timeSlot[0].required = false;
        this.form.timeSlot = [];
      } else if("On-Demand Pull" == this.form.apiForm) {
        this.isShowTime = true;
        // this.rules.sTime[0].required = true;
        // this.rules.eTime[0].required = true;
        this.rules.timeSlot[0].required = true;
      }
    },
    toDelete(id) {
      DetelePolicy({
        idList: [id]
      }).then(() => {
        this.$message.success("Delete successfully!");
        this.handleCurrentChange(this.page);
      });
    },
    deleteAll(){
      if(!this.multipleSelection1.length){
        this.$message.error("Please select some configurations!");
        return;
      }
      this.$confirm('Are you sure to delete these configurations?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        DetelePolicy({
          idList: this.multipleSelection1.map(item => item.id)
        }).then(() => {
          this.$message.success("Delete successfully!");
          this.handleCurrentChange(this.page);
        })
      })
    },
    handleSelectionChange1(val) {
      this.multipleSelection1 = val;
    },
    handleSelectionChange2(val) {
      this.multipleSelection2 = val;
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.handleCurrentChange(1);
    },
    showDetail(json) {
      this.$refs.configDialog.show(json);
    },
  },
  disabledDate (current) {
      return current < moment().subtract(1, 'days')
  }
};
</script>
