<template>
  <el-main>
    <x2-progress-track v-if="(trackerConfig.term == 'x2_cash' || trackerConfig.term == 'x2_cheque' || trackerConfig.term == 'x2_ba')" v-model="trackerConfig" />
    <progress-track v-else v-model="trackerConfig" />
    <div v-if="!isLegacy" id="new-invoice">
      <new-invoice :booking_details="booking_details" :booking_id="booking_id.toString()"/>
    </div>
    <div v-if="isLegacy" id="legacy-invoice">
      <h1>Transfer Completed</h1>
      <h2> Please upload your purchase order </h2>
      <!-- upload card -->
      <div class="row">
        <div class="col">
          <div class="card">
            <div class="card-header">Upload PO
              <a href="/CIEF-X-Plan-PO-Format-15.0.xlsm" target="_blank">(Download Po Format)</a>
            </div>
            <!-- upload image -->
            <div class="card-body">

              <el-upload :action="'/api/booking/' + booking_id + '/upload-po'" :auto-upload="false" :on-change="beforeFileUpload" :on-exceed="handleExceed" :on-preview="handlePreview" :on-remove="handleRemove" :on-error="uploadError" class="upload-demo  uploadAreaOne" accept=".jpeg, .jpg, .png, .bmp, .doc, .docx, .xls, .xlsx, .pdf" drag multiple>
                <i class="el-icon-upload" />
                <div class="el-upload__text">Drop file here or
                  <em>click to upload</em>
                </div>
                <div slot="tip" class="el-upload__tip">bmp/jpeg/jpg/png/pdf/xls/xlxs/doc/docx files with a size less than 3MB</div>
              </el-upload>
              <el-upload :action="'/api/booking/' + booking_id + '/upload-po'" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :file-list="fileList" multiple class="upload-demo uploadAreaTwo" >
                <el-button size="small" type="primary">Click to upload</el-button>
                <div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div>
              </el-upload>

              <div class="bottom clearfix" style="text-align:right;">
                <el-button :loading="loading_btn" type="primary" @click="uploadPo">Submit</el-button>
              </div>
              <!-- upload image end -->
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="card">
      <div class="card-header">China Bank Slip</div>
      <div class="card-body">
        <a :href="getURL(booking_details.china_bankslip_path)" target="_blank" >
          <img v-if="isImage(booking_details.china_bankslip_path)" :src="booking_details.china_bankslip_path" class="image">
          <p v-else>Download</p>
        </a>
      </div>
    </div>
    <!-- order details -->
    <div class="card">
      <div class="card-header">Order Details</div>
      <div class="card-body">
        <div class="row">
          <div class="col">
            <table class="table table-striped">
              <tbody>
              <tr>
                <td>Ref No :</td>
                <td>{{ booking_details.id }}</td>
              </tr>
              <tr>
                <td>Date :</td>
                <td>{{ booking_details.created_at }}</td>
              </tr>
              <tr>
                <td>Customer Marking :</td>
                <td>{{ booking_details.marking }}</td>
              </tr>
              <tr>
                <td>Term: </td>
                <td>{{ booking_details.term }}</td>
              </tr>
              <tr>
                <td>Beneficiary Account : </td>
                <td>{{ booking_details.account_name }}</td>
              </tr>
              </tbody>
            </table>
          </div>
          <div class="col">
            <table class="table table-striped">
              <tbody>
              <tr>
                <td>CNY/RMB :</td>
                <td>CNY {{ booking_details.amount }}</td>
              </tr>
              <tr>
                <td>+ Service Charge :</td>
                <td>CNY {{ booking_details.service_charge }}</td>
              </tr>
              <tr>
                <td>RATE :</td>
                <td>{{ booking_details.rate }}</td>
              </tr>
              <tr>
                <td/>
                <td>
                  <b>MYR {{ booking_details.bia }}</b>
                </td>
              </tr>
              <tr>
                <td>Beneficiary Account Number : </td>
                <td>{{ booking_details.account_num }}</td>
              </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <div class="card">
      <div class="card-header">Order Bankin Slip</div>
      <div class="row">
        <div class="card-body">
          <a :href="getURL(booking_details.user_bankslip_path)" target="_blank" >
            <img v-if="isImage(booking_details.user_bankslip_path)" :src="booking_details.user_bankslip_path" class="image">
            <p v-else>Download</p>
          </a>
        </div>
      </div>
    </div>
  </el-main>
</template>
<style>
  * {
    box-sizing: border-box;
  }

  h1 {
    margin-top: 5%;
    font-size: 3vw;
    text-align: center;
  }

  h2 {
    font-size: 2vw;
    text-align: center;
    margin-bottom: 3%;
  }

  .booking-details {
    font-weight: bold;
  }

  .bankinSlipImage {
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 150px;
    display: block;
  }

  .bankinSlipImage:hover {
    box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
  }

  .uploadAreaTwo {
    display: none;
  }

  .card {
    margin-bottom: 3%;
  }

  @media only screen and (max-width: 767px) {
    .uploadAreaOne {
      display: none;
    }
    .uploadAreaTwo {
      display: unset;
    }
    .table {
      font-size: 3.5vmin;
    }
    h1 {
      font-size: 1em;
    }
    h2 {
      font-size: 0.8em;
    }
  }
</style>
<script>
import ProgressTrack from '~/components/ProgressTrack'
import X2ProgressTrack from '~/components/X2ProgressTrack'
import NewInvoice from '~/components/NewInvoice'
import axios from 'axios'
import ImageCompressor from 'image-compressor.js'

export default {
  components: {
    'progress-track': ProgressTrack,
    'x2-progress-track': X2ProgressTrack,
    'new-invoice': NewInvoice
  },
  data () {
    return {
      booking_id: this.$route.params.id,
      trackerConfig: {
        status: 5,
        term: null
      },
      purchaseOrderArray: [],
      loading_btn: false,
      booking_details: {
        id: null,
        amount: null,
        bia: null,
        user_bankslip_path: null,
        china_bankslip_path: null
      }
    }
  },
  computed: {
    isLegacy: function () {
      return this.booking_details.user_po_path && this.booking_details.user_po_path.length > 0
    }
  },
  beforeCreate () {
    const loading = this.$loading({
      lock: true,
      text: 'Please wait..',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    axios
      .get('/api/booking/' + this.$route.params.id)
      .then((response) => {
        console.log(response)
        this.booking_details = response.data
        this.trackerConfig.term = response.data.term
        loading.close()
      }).catch((error) => {
        console.log(error)
        loading.close()
        this.$router.push({
          name: 'notfound'
        })
      })
  },
  methods: {
    uploadPo () {
      this.loading_btn = true
      console.log(this.purchaseOrderArray)
      axios
        .post('/api/booking/' + this.$route.params.id + '/confirm-po', { images: this.purchaseOrderArray })
        .then((response) => {
          this.$message({
            showClose: true,
            message: 'Your PO has been uploaded. We are processing the Invoice.',
            type: 'success',
            duration: 5000
          })
          this.$router.push({
            name: 'home'
          })
          this.loading_btn = false
        }).catch((error) => {
          console.error(error)
          this.$message({
            showClose: true,
            message: 'Please upload your purchase order',
            type: 'error',
            duration: 30000
          })
          this.loading_btn = false
        })
    },
    beforeFileUpload (file, fileList) {
      this.purchaseOrderArray = []
      const vm = this
      for (let i in fileList) {
        const filetype = fileList[i].raw.type.split('/')[0]
        if (filetype === 'image') {
          ImageCompressor(fileList[i].raw, {
            quality: 0.4,
            convertSize: 1500000,
            success (result) {
              vm.convertFile(result)
            },
            error (e) {
              console.error(e.message)
            }
          })
        } else {
          this.convertFile(fileList[i].raw)
        }
      }
    },
    convertFile (file) {
      let vm = this
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onloadend = function () {
        vm.purchaseOrderArray.push(reader.result)
        console.log(vm.purchaseOrderArray)
      }
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
      // Should send some reqeust to controller to delete the file
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + fileList.length} totally`
      )
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    uploadError (file, fileList) {
      this.$message.warning(`Incorrect file format or file size too big.`)
    },
    getExtension (path) {
      return path.slice(-3)
    },
    isImage (path) {
      if (path != null) {
        const ext = this.getExtension(path)
        return ext === 'jpg' || ext === 'jpeg' || ext === 'bmp' || ext === 'png'
      } else {
        return false
      }
    },
    getURL (path) {
      const getUrl = window.location
      const baseUrl = getUrl.protocol + '//' + getUrl.host
      return baseUrl + path
    }
  }
}
</script>
