<template>
  <div class="card-container">
    <div class="card-content">
      <el-form
        v-loading="loading"
        label-width="130px"
        label-position="left">
        <div class="section-title">Transaction Overview</div>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Transaction ID:">
              <el-input
                class="add-text"
                v-model="details.transactionPk"
                readonly/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Start Date/Time:">
              <el-input
                class="add-text"
                v-model="details.startDateTime"
                readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="User Id:">
              <el-input
                class="add-text"
                v-model="details.userPk"
                readonly/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="End Date/Time:">
              <el-input
                class="add-text"
                v-model="details.endDateTime"
                readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Station ID:">
              <el-input
                class="add-text"
                v-model="details.stationId"
                readonly/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Stop Reason:">
              <el-input
                class="add-text"
                v-model="details.stopReason"
                readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Connector ID:">
              <el-input
                class="add-text"
                v-model="details.connectorId"
                readonly/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Stop Event Actor:">
              <el-input
                class="add-text"
                v-model="details.stopEventActor"
                readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="section-title">Charges</div>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Duration:"
              class="form-unit">
              <span class="item-unit">(minute)</span>
              <el-input
                class="add-text"
                v-model="details.duration"
                readonly/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Rate:">
              <el-input
                class="add-text"
                v-model="details.rate"
                readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Total Power:"
              class="form-unit">
              <span class="item-unit">(kWh)</span>
              <el-input
                class="add-text"
                v-model="details.totalPower"
                readonly/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Charges:">
              <el-input
                class="add-text"
                v-model="details.charges"
                readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="flexcr" style="margin: 10px 0;">
          <div class="section-title" style="margin: 20px 0;">Intermediate Meter Values</div>
          <el-button
            type="primary"
            style="margin: 0 10px;"
            v-if="!details.endDateTime"
            @click="onClickEnd"
            :loading="endLoading">
            End Transaction
          </el-button>
          <el-button
            v-else
            type="primary"
            style="margin: 0 10px;"
            icon="el-icon-download"
            @click="downloadInvoice"
            :loading="endLoading">
            Download Invoice
          </el-button>
          <div class="flex1"></div>
          <el-select v-model="measurand" @change="getDeatil">
            <el-option
              value=""
              label="All"/>
            <el-option
              v-for="(item, index) in optionsMeasurand"
              :key="index"
              :value="item"
              :label="item"/>
          </el-select>
        </div>
        <el-table :data="listData">
          <el-table-column
            label="Timestamp"
            align="center"
            class-name="fixed-width"
            min-width="130">
              <template slot-scope="{row}">
                <span>{{ row.timestamp }}</span>
              </template>
          </el-table-column>
          <el-table-column
            label="Value"
            align="center"
            min-width="80">
              <template slot-scope="{row}">
                <span>{{ row.value }}</span>
              </template>
          </el-table-column>
          <el-table-column
            label="Reading Context"
            align="center"
            class-name="fixed-width"
            min-width="130">
              <template slot-scope="{row}">
                <span>{{ row.readingContext }}</span>
              </template>
          </el-table-column>
          <el-table-column
            label="Format"
            align="center"
            min-width="100">
              <template slot-scope="{row}">
                <span>{{ row.format }}</span>
              </template>
          </el-table-column>
          <el-table-column
            label="Measureand"
            align="center"
            class-name="fixed-width"
            min-width="250">
              <template slot-scope="{row}">
                <span>{{ row.measureand }}</span>
              </template>
          </el-table-column>
          <el-table-column
            label="Location"
            align="center"
            min-width="100">
              <template slot-scope="{row}">
                <span>{{ row.location }}</span>
              </template>
          </el-table-column>
          <el-table-column
            label="Unit"
            align="center"
            min-width="80">
              <template slot-scope="{row}">
                <span>{{ row.unit }}</span>
              </template>
          </el-table-column>
          <el-table-column
            label="Phase"
            align="center"
            min-width="80">
              <template slot-scope="{row}">
                <span>{{ row.phase }}</span>
              </template>
          </el-table-column>
        </el-table>
        <div class="pagination" v-if="details.transactionMeters">
          <Pagination
            v-show="details.transactionMeters.length > 0"
            :total="details.transactionMeters.length"
            :page.sync="page"
            :limit.sync="pageSize"
            :autoScroll="false"
            @pagination="handlePageChange" />
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import api from '../../http/api/transaction'
  
  export default {
    components: { Pagination },
    data() {
      return {
        page: 1,
        pageSize: 10,
        details: {},
        listData: [],
        loading: false,
        measurand: "",
        endLoading: false,
        optionsMeasurand: []
      }
    },
    created() {
      this.getMeasuOptions()
      this.getDeatil()
    },
    methods: {
      getMeasuOptions() {
        api.getMeasurandOptions().then(res => {
          if (res.data) {
            this.optionsMeasurand = res.data
          }
        }).catch(err => {
          
        })
      },
      getDeatil() {
        this.loading = true;
        api.getTransactionDetail({
          transactionPk: this.$route.params.id,
          measurand: this.measurand
        }).then(res => {
          if (res.data) {
            this.details = res.data
            if (this.details.duration) {
              this.details.duration = Number((this.details.duration * 60).toFixed(2))
            }
            if (this.details.transactionMeters && this.details.transactionMeters.length) {
              this.handlePageChange()
            } else {
              this.listData = []
            }
          }
        }).catch(err => {
          this.$message({
            type: 'error',
            message: err
          })
        }).finally(() => {
          this.loading = false
        })
      },
      onClickEnd() {
        this.$confirm('This operation only for settling abnormal transactions and will not end charging. Select Confirm to proceed.', 'Warning', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(res => {
          this.endTransaction();
        })
      },
      endTransaction() {
        this.endLoading = true;
        api.endTransaction({
          transactionPk: this.$route.params.id
        }).then(res => {
          this.$message({
            type: 'success',
            message: 'Operation Successfully!'
          })
          this.getDeatil()
        }).catch(err => {
          this.$message({
            type: 'error',
            message: err
          })
        }).finally(() => {
          this.endLoading = false
        })
      },
      downloadInvoice() {
        this.endLoading = true;
        api.downloadInvoice(this.$route.params.id).then(res => {
          if (res && res.size > 0) {
            const name = 'T' + this.$route.params.id + '-' + new Date().getTime() + '.pdf'
            this.downloadFile(res, name);
          } else {
            this.$message.error('Empty files');
          }
        }).catch(err => {
          this.$message({
            type: 'error',
            message: err
          })
        }).finally(() => {
          this.endLoading = false
        })
      },
      downloadFile(res, fileName) {
        const blob = new Blob([res], {
          type: 'application/pdf;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)
        }
      },
      handlePageChange() {
        this.listData = []
        var i = (this.page - 1) * this.pageSize
        var max = this.page * this.pageSize
        if (max > this.details.transactionMeters.length)
          max = this.details.transactionMeters.length
        for (i; i < max; i++) {
          this.listData.push(this.details.transactionMeters[i])
        }
      }
    }
  }
</script>

<style scoped="scoped" lang='scss'>
  @import '../../styles/variables.scss';

  .card-container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }
  .card-content {
    padding: 15px 80px;
    border-radius: 6px;
    background-color: white;
  }
  .section-title {
    color: #333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 16px;
    user-select: none;
    line-height: 24px;
    font-weight: 500;
    font-family: sans-serif;
    text-transform: uppercase;
  }
  .add-text {
    width: 100%;
    max-width: 300px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .hr {
    height: 2px;
    margin: 10px -40px;
    background-color: #F0F5FC;
  }
  .hr-full {
    height: 2px;
    margin: 20px -80px;
    background-color: #F0F5FC;
  }
  .rate-list-view {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  .rate-text {
    max-width: 150px;
    padding-right: 14px;
  }
  .list-item-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    margin: 0 10px 22px;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 30px;
  }
  @media screen and (max-width: 500px) {
    .card-container {
      padding: 0px;
    }
    .card-content {
      padding: 15px 40px;
    }
  }
  .form-unit ::v-deep .el-form-item__label {
    line-height: 30px;
  }
  .item-unit {
    top: 12px;
    left: -130px;
    font-size: 12px;
    position: absolute;
  }
  .el-table ::v-deep tr div {
    font-size: 12px;
    white-space: nowrap;
  }
  .pagination {
    width: 100%;
    text-align: right;
    overflow-x: auto;
  }
</style>