<template>
  <div class="app-container">
    <div class="filter-container filter-view">
      <el-select
        class="filter-view-item"
        placeholder="Maintenance Type"
        v-model="params.pageCriteria.maintenanceType"
        @change="toSearch">
        <el-option
          v-for="(item, index) in options.type"
          :key="index"
          :label="item"
          :value="item"/>
      </el-select>
      <div style="flex: 1; max-width: 300px;">
        <el-input
          class="filter-view-item"
          v-model="params.pageCriteria.criteria"
          placeholder="Search by maintenance"
          prefix-icon="el-icon-search"
          @keyup.enter.native="toSearch"
          @change="toSearch"
          clearable/>
      </div>
      <div class="filter-flex-button"></div>
      <my-upload
        accept=".xls,.xlsx,.csv"
        :limit="1"
        :is-blob="true"
        :action="action"
        :headers="headers"
        :file-list="fileList"
        :show-file-list="false"
        :before-upload="onImportStart"
        :on-success="onImportExcel"
        :on-error="onImportExcelErr"
        v-if="!$route.meta.onlyView">
        <el-button
          icon="el-icon-upload2"
          type="primary"
          :loading="loading.upload">
          Batch Upload
        </el-button>
      </my-upload>
      <div v-if="!$route.meta.onlyView">
        <el-button
          icon="el-icon-download"
          type="primary"
          :loading="loading.download"
          @click="onDownloadTmp">
          Template
        </el-button>
      </div>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="onClickAdd">
        Create Maintenance
      </el-button>
    </div>
    <el-table
      v-loading="loading.table"
      :data="table.data">
      <el-table-column
        align="center"
        label="Maintenance ID"
        min-width="130">
        <template slot-scope="{row}" >
          <span
            class="link-type"
            @click="onClickEdit(row)"
            v-if="!$route.meta.onlyView && row.dataStatus != 'Inactive'">
            {{ row.downtimeId }}
          </span>
          <span v-else>{{ row.downtimeId }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Maintenance Type"
        align="center"
        prop="maintenanceType"
        min-width="150"/>
      <el-table-column
        label="Maintenance Type Category"
        align="center"
        prop="maintenanceTypeCategory"
        min-width="210"/>
      <el-table-column
        label="Start Time"
        align="center"
        prop="startTime"
        min-width="120"/>
      <el-table-column
        label="End Time"
        align="center"
        prop="endTime"
        min-width="120"/>
      <el-table-column
        label="Peak Downtime Min"
        align="center"
        prop="peakDowntimeMin"
        min-width="160"/>
      <el-table-column
        label="Off Peak Downtime Min"
        align="center"
        prop="offPeakDowntimeMin"
        min-width="180"/>
      <el-table-column
        label="Sent Notification"
        align="center"
        prop="notificationSent"
        min-width="140"/>
      <el-table-column
        label="Remarks"
        align="center"
        prop="remark"
        min-width="120"/>
      <el-table-column
        label="Reported By"
        align="center"
        prop="reportedBy"
        min-width="120"/>
      <el-table-column
        label="Approved By"
        align="center"
        prop="approvedBy"
        min-width="120"/>
      <el-table-column
        align="center"
        label="Action"
        min-width="70"
        v-if="!$route.meta.onlyView">
        <template v-slot="{ row }">
          <el-dropdown
            class="action-dropdown"
            @command="(v) => handleCommand(v, row)"
            v-if="row.dataStatus != 'Inactive'">
            <i class="el-icon-more icon-action"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="onClickAssign"
                v-if="false">
                Assign Connectors
              </el-dropdown-item>
              <el-dropdown-item
                command="onClickEdit">
                Edit
              </el-dropdown-item>
              <el-dropdown-item
                command="onClickDelete">
                Delete
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="right">
      <Pagination
        v-show="table.total > 0"
        :total="table.total"
        :page.sync="params.pageNum"
        :limit.sync="params.pageSize"
        @pagination="getTableData" />
    </div>
    <AssignmentDialog
      :visible="assign.visible"
      title="ASSIGN CONNECTORS"
      :item="assign.item"
      @hide="onClickAssign"/>
  </div>
</template>

<script>
import api from '../../api/apiMaintain.js';
import { baseURL } from '@/http/http'
import Pagination from '@/components/Pagination';
import AssignmentDialog from './AssignmentDialog';
import MyUpload from '@/components/MyUpload'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      params: {
        pageNum: 1,
        pageSize: 10,
        pageCriteria: {
          criteria: "",
          maintenanceType: ""
        }
      },
      table: {
        data: [],
        total: 0
      },
      loading: {
        table: false,
        upload: false,
        download: false
      },
      options: {
        type: []
      },
      fileList: [],
      assign: {
        item: {},
        visible: false
      },
      dialogAction: {
        id: "",
        isEdit: false,
        visible: false
      }
    };
  },
  components: {Pagination, MyUpload, AssignmentDialog},
  computed: {
    action() {
      return baseURL + process.env.VUE_APP_API_PREFIX + '/dawn/api/v1/batch-create-downtime'
    },
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.getTypeOptions();
    this.toSearch();
  },
  methods: {
    toSearch() {
      this.params.pageNum = 1;
      this.getTableData();
    },
    getTypeOptions() {
      api.getMaintainTypeOptions().then(res => {
        if (res.data && res.data.length > 0) {
          this.options.type = res.data;
        }
      }).catch(err => {
        
      })
    },
    getTableData() {
      this.loading.table = true;
      api.getMaintainPages(this.params).then(res => {
        if (res.data && res.data.totalRow) {
          this.table.data = res.data.records
          this.table.total = res.data.totalRow
        } else {
          this.table.data = []
          this.table.total = 0
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
        this.table.data = []
        this.table.total = 0
      }).finally(() => {
        this.loading.table = false
      })
    },
    handleCommand(cb, item) {
      this[cb](item)
    },
    onClickAssign(row) {
      if (row) {
        this.assign.item = row;
        this.assign.visible = true;
      } else {
        this.assign.item = {};
        this.assign.visible = false;
        this.getTableList();
      }
    },
    onClickAdd() {
      this.$router.push({
        path: "/incident-management/maintenance-settings/add"
      })
    },
    onClickEdit(row) {
      this.$router.push({
        path: "/incident-management/maintenance-settings/" + row.downtimeId
      })
    },
    onImportStart() {
      this.loading.upload = true;
    },
    onImportExcel(res, file, fileList) {
      fileList = [];
      this.fileList = [];
      if (res.success == undefined) {
        this.downloadExcel(res, "batch-maintenance-result.xls");
        this.loading.upload = false;
      } else {
        this.onImportExcelErr(res.msg, file, fileList);
      }
    },
    onImportExcelErr(err, file, fileList) {
      this.$message({
        type: 'error',
        message: err
      })
      this.loading.upload = false;
    },
    onDownloadTmp() {
      this.loading.download = true;
      api.downloadTemplate().then(res => {
        this.downloadExcel(res, "batch-maintenance-template.xlsx")
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.loading.download = false;
      })
    },
    downloadExcel(res, fileName) {
      const blob = new Blob([res], {
        type: 'application/vnd.ms-excel;charset=utf-8'
      })
      // let href = window.URL.createObjectURL(blob)
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }
  }
}
</script>

<style scoped>

</style>