<template>
  <el-main>
    <div class="alert alert-info" role="alert">
      Dear EXCHANGE users,<br>
      We have officially launched EXCHANGE 2.0, your current account is closed for any further transactions by 7am, 17<sup>th</sup> June 2021.<br>
      To create new bookings, you will need to click the below link and login using the same email and password in the new system.<br><br>
      <a href="https://stagging.exchange.cief-malaysia.com">
        <button class="btn btn-success">Go to new site</button>
      </a><br><br>

      尊贵的EXCHANGE用户<br>
      EXCHANGE 2.0 已正式推出， 当前户口最后下订单和汇款的截止时间为 6月17日，早上7点。<br>
      您可以点击以下网址， 使用同样的电子邮件和密码登录及下订单<br><br>
      <a href="https://stagging.exchange.cief-malaysia.com">
        <button class="btn btn-success">转到新站点</button>
      </a>
    </div>
    <!--&lt;!&ndash; Input-Amount &ndash;&gt;-->
      <!--<el-row :gutter="20" type="flex" justify="center" align="middle">-->
        <!--<el-col :span="20">-->
          <!--<div class="grid-content bg-purple" align="center">-->
            <!--I need :-->
            <!--<el-select v-model="value" placeholder="RMB">-->
              <!--<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />-->
            <!--</el-select>-->
          <!--</div>-->
        <!--</el-col>-->
      <!--</el-row>-->
      <!--<br>-->
      <!--<el-row :gutter="20" type="flex" justify="center" align="middle">-->
        <!--<el-col :xs="18" :sm="18" :md="8" :lg="8" :xl="8">-->
          <!--<div class="grid-content bg-purple" align="left">-->
            <!--<el-input v-model="booking.amount" placeholder="Amount" />-->
          <!--</div>-->
        <!--</el-col>-->
      <!--</el-row>-->
    <!--&lt;!&ndash; Input-Amount-end &ndash;&gt;-->

    <!--<div align="right">-->
    <!--<el-button type="primary" :loading="loading_btn" size="mini" @click="refreshRate()">Refresh Rate</el-button></div>-->

    <!--<hr>-->
    <!--&lt;!&ndash; Rate-Display &ndash;&gt;-->
    <!--<br>-->
    <!--<el-row :gutter="20" type="flex" justify="center" align="middle">-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="right" />-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="right" />-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">Cash/Bank Transfer</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">Cheque</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">BA</div>-->
      <!--</el-col>-->
    <!--</el-row>-->

    <!--<el-row :gutter="20" type="flex" justify="center" align="middle">-->
      <!--<el-col>-->
        <!--<el-tooltip class="item" effect="dark" content="With Invoice" placement="right">-->
          <!--<div class="grid-content bg-purple" align="right">-->
            <!--<i type="button" class="el-icon-question" circle/>-->
          <!--</div>-->
        <!--</el-tooltip>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="right">X1 :</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">{{ rate.x1_cash }}</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">{{ rate.x1_cheque }}</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">{{ rate.x1_ba }}</div>-->
      <!--</el-col>-->
    <!--</el-row>-->

    <!--<el-row :gutter="20" type="flex" justify="center" align="middle">-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" />-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" />-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">-->
          <!--<el-button type="text" @click="acceptTerm('x1_cash')">Book</el-button>-->
        <!--</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">-->
          <!--<el-button type="text" @click="acceptTerm('x1_cheque')">Book</el-button>-->
        <!--</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">-->
          <!--<el-button type="text" @click="acceptTerm('x1_ba')">Book</el-button>-->
        <!--</div>-->
      <!--</el-col>-->
    <!--</el-row>-->

    <!--<br>-->
    <!--<el-row :gutter="20" type="flex" justify="center" align="middle">-->
      <!--<el-col>-->
        <!--<el-tooltip class="item" effect="dark" content="Without Invoice" placement="right">-->
          <!--<div class="grid-content bg-purple" align="right">-->
            <!--<i type="button" class="el-icon-question" circle/>-->
          <!--</div>-->
        <!--</el-tooltip>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="right">X2 :</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">{{ rate.x2_cash }}</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">{{ rate.x2_cheque }}</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">{{ rate.x2_ba }}</div>-->
      <!--</el-col>-->
    <!--</el-row>-->

    <!--<el-row :gutter="20" type="flex" justify="center" align="middle">-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" />-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" />-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">-->
          <!--<el-button type="text" @click="acceptTerm('x2_cash')">Book</el-button>-->
        <!--</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">-->
          <!--<el-button type="text" @click="acceptTerm('x2_cheque')">Book</el-button>-->
        <!--</div>-->
      <!--</el-col>-->
      <!--<el-col>-->
        <!--<div class="grid-content bg-purple" align="center">-->
          <!--<el-button type="text" @click="acceptTerm('x2_ba')">Book</el-button>-->
        <!--</div>-->
      <!--</el-col>-->
    <!--</el-row>-->
    <!--&lt;!&ndash; Rate-Display-end &ndash;&gt;-->

    <!--&lt;!&ndash; Form_popup &ndash;&gt;-->
      <!--<el-dialog :visible.sync="dialogFormVisible" :fullscreen="true" title="Booking" center>-->
        <!--<el-form ref="bookingForm" :model="bookingForm" :rules="rules">-->
          <!--<div align="center"> -->
          <!--<el-form-item prop="payment_for"> &lt;!&ndash; TODO : this should be payment for order number &ndash;&gt;-->
            <!--<el-select v-model="bookingForm.payment_for" placeholder="Payment For" style="width: 80%" required="true">-->
              <!--<el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value" />-->
            <!--</el-select>-->
          <!--</el-form-item>-->
          <!--<el-form-item prop="order_no">-->
            <!--<el-input v-model="bookingForm.order_no" placeholder="Order No. (Optional)" style="width: 80%" required="true" />-->
          <!--</el-form-item>  -->
            <!--<br>-->
          <!--<div align=center>-->
            <!--<h6>China's Supplier Details</h6>-->
          <!--</div>-->
            <!--<br>-->
          <!--<el-form-item prop="account_name">-->
              <!--<el-input v-model="bookingForm.account_name" placeholder="Account Name" style="width: 80%" required="true" />-->
            <!--</el-form-item>-->
            <!--<el-form-item prop="account_num">-->
              <!--<el-input v-model="bookingForm.account_num" type="text" placeholder="Account Number" style="width: 80%"/>-->
            <!--</el-form-item>-->
            <!--<el-form-item prop="bank_name">-->
              <!--<el-input v-model="bookingForm.bank_name" type="text" placeholder="Bank Name" style="width: 80%" />-->
            <!--</el-form-item>-->
            <!--<el-form-item prop="bank_branch">-->
              <!--<el-input v-model="bookingForm.bank_branch" type="text" placeholder="Branch / 分行/支行 / 所在地" style="width: 80%" />-->
            <!--</el-form-item>-->
            <!---->
            <!--<el-form-item>-->
              <!--&lt;!&ndash; <el-button @click="dialogFormVisible = false">Cancel</el-button> &ndash;&gt;-->

              <!--<el-button :loading="loading" type="primary" @click="getCalculationValue('bookingForm')">Book Now</el-button>-->
            <!--</el-form-item>-->
          <!--</div>-->
        <!--</el-form>-->
      <!--</el-dialog>-->
      <!---->
    <!--&lt;!&ndash; Form_popup-end &ndash;&gt;-->

    <!--&lt;!&ndash; Booking_confirmation_popup &ndash;&gt;-->
    <!--<el-dialog :visible.sync="dialogFormVisible1" :fullscreen="true" title="Booking Confirmation" center>-->
      <!--<table class="table table-striped">-->
        <!--<tbody>-->
          <!--<tr>-->
            <!--<td>Date : </td>-->
            <!--<td> {{ bookingConfirmTable.date }}</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>Customer Marking : </td>-->
            <!--<td> {{ bookingConfirmTable.marking }}</td>-->
          <!--</tr>-->
          <!--<tr v-if="bookingConfirmTable.order_no != null">-->
            <!--<td>Payment for (Order No.) : </td>-->
            <!--<td> {{ bookingConfirmTable.order_no }}</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>Payment for : </td>-->
            <!--<td> {{ bookingConfirmTable.payment_for }}</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>Payment Method : </td>-->
            <!--<td> {{ bookingConfirmTable.payment_method }}</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>Remarks : </td>-->
            <!--<td> {{ bookingConfirmTable.remark }}</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td></td>-->
            <!--<td></td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>CNY/RMB :</td>-->
            <!--<td>-->
              <!--<b> CNY {{ bookingConfirmTable.amount }}</b>-->
            <!--</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>+ Service Charges :</td>-->
            <!--<td>-->
               <!--CNY {{ bookingConfirmTable.service_charge }}-->
            <!--</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>/ Rate :</td>-->
            <!--<td>-->
               <!--{{ bookingConfirmTable.rate }}-->
            <!--</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td></td>-->
            <!--<td>-->
               <!--MYR {{ bookingConfirmTable.subtotal }}-->
            <!--</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>+ Tax :</td>-->
            <!--<td>-->
              <!--MYR {{ bookingConfirmTable.taxAmount }}-->
            <!--</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>+ Billing Charge :</td>-->
            <!--<td>-->
               <!--MYR {{ bookingConfirmTable.billingChargeAmount }}-->
            <!--</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>Bank In Amount :</td>-->
            <!--<td>-->
              <!--<b> MYR {{ bookingConfirmTable.bankin_amount }}</b>-->
            <!--</td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>China Beneficiary Acc : <br>-->
              <!--Name : {{ bookingConfirmTable.acc_name }} <br>-->
              <!--Account No. : {{ bookingConfirmTable.acc_no }} <br>-->
              <!--Bank : {{ bookingConfirmTable.bank_name }}<br>-->
              <!--Branch. : {{ bookingConfirmTable.bank_branch }}-->
            <!--</td>-->
            <!--<td></td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td>Bank In Amount :</td>-->
            <!--<td><b>RM {{ bookingConfirmTable.bankin_amount }}</b></td>-->
          <!--</tr>-->
          <!--<tr>-->
            <!--<td></td>-->
            <!--<td></td>-->
          <!--</tr>-->
        <!--</tbody>-->
      <!--</table>-->
      <!--<span slot="footer" class="dialog-footer">-->
        <!--&lt;!&ndash; <el-button @click="dialogFormVisible = false">Cancel</el-button> &ndash;&gt;-->
        <!--<el-button :loading="loading" type="primary" @click="createBooking">Confirm</el-button>-->
      <!--</span>-->
    <!--</el-dialog>-->
    <!--&lt;!&ndash; Booking_confirmation_popup &ndash;&gt;-->

    <br>
    <br>
    <hr>
    <div align="right">
<el-button :loading="loading_btn" type="primary" size="mini" @click="RefreshBooking(); RefreshBookingTableComplete()">Refresh</el-button></div>
<!-- Booking Table -->

<el-tabs type="border-card" class="table-switch">
  <el-tab-pane label="Booking Table">
  <el-row :gutter="20">
      <div>
        <el-table :data="bookingTable">
          <el-table-column label="Ref No." width="100" >
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Update</el-button>
            <el-button slot-scope="scope" type="text" @click="(event) => { BookingStatus(scope.row.status, scope.row.id, scope.row.term) }"> {{ scope.row.id }}</el-button>
          </el-table-column>
          <el-table-column label="DateTime" prop="created_at" width="180" sortable/>
          <el-table-column label="Marking" width="120" prop="marking" />
          <el-table-column :filters="[{text: 'X1 cash', value: 'x1_cash'}, {text: 'X1 ba', value: 'x1_ba'}, {text: 'X1 cheque', value: 'x1_cheque'}]" :filter-method="filterHandler" label="Term" prop="term" width="100"/> -->
          <el-table-column label="Rate" width="100" prop="rate" sortable/>
          <el-table-column label="Amount" prop="amount" justify="center" width="110" sortable/>
          <el-table-column label="Transfer Amount" prop="transfer_amount" width="170" sortable/>
          <!-- <el-table-column label="ETA" sortable width="100"/> -->
          <!-- <el-table-column label="Payment Method" :filters="[{text: 'Cash', value: 'Cash'}, {text: 'Cheque', value: 'Cheque'}, {text: 'BA', value: 'BA'}]" :filter-method="filterHandler">
        </el-table-column> -->
          <!-- <el-table-column :filters="[{text: '(1/6)', value: '(1/6) Order Done'}, {text: '(2/6)', value: '(2/6) Waiting for Upload Bank in Slip'}, {text: '(3/6)', value: '(3/6) Order Confirmation'}, {text: '(4/6)', value: '(4/6) Processing Transfer'}, {text: '(5/6)', value: '(5/6) Waiting for Upload PO'}, {text: '(6/6)', value: '(6/6) Order Complete'}]" :filter-method="filterHandler" prop="status" label="Status"/> -->
          <el-table-column label="Status" width="106" >
            <template slot-scope="scope">
              <el-popover trigger="click" placement="top">
                <p>{{ scope.row.status_desc }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.track_status }}</el-tag>
                </div>
              </el-popover>       
            </template>
          </el-table-column>
          <!-- <el-table-column label="Balance" prop="transfer_amount" sortable width="100"/> -->
          <!-- <el-table-column prop="timeout" label="Bankin Timeout" /> -->
          <el-table-column :filters="[{ text: 'Success', value: 'Success' }, { text: 'Pending', value: 'Pending' }]" :filter-method="filterTag"
                           label="" width="180" filter-placement="bottom-end">
            <el-button slot-scope="scope" type="text" @click="(event) => { BookingStatus(scope.row.status, scope.row.id, scope.row.term) }"> View Status </el-button>
            
             
            <!-- <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">View Status</el-button>
              <el-button size="mini" type="danger" @click="BookingStatus(scope.$index, scope.row)">Cancel</el-button>
            </template> -->
          </el-table-column>
          <el-table-column :filters="[{ text: 'Success', value: 'Success' }, { text: 'Pending', value: 'Pending' }]" :filter-method="filterTag"
                          label="" width="180" filter-placement="bottom-end">
          <!-- <el-button slot-scope="scope" type="text" @click="(event) => { cancelBooking(scope.row.id) }"> Cancel Booking </el-button> -->
          </el-table-column>
        </el-table>
        <div align="right">
      <el-button type="primary" size="mini" @click="fetchPaginateBooking(pagination.prev_page_url)" :disabled="!pagination.prev_page_url">
        Previous
      </el-button>
      <span>Page {{pagination.current_page}} of {{pagination.last_page}}</span>
      <el-button type="primary" size="mini" @click="fetchPaginateBooking(pagination.next_page_url)" :disabled="!pagination.next_page_url">
        Next
      </el-button>
    </div>
      </div>
    </el-row><br><br></el-tab-pane>
      
  <el-tab-pane label="Completed">
  <el-row :gutter="20">
      <div>
        <el-table :data="bookingTableComplete">
          <el-table-column label="Ref No." width="100" >
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Update</el-button>
            <el-button slot-scope="scope" type="text" @click="(event) => { BookingStatus(scope.row.status, scope.row.id, scope.row.term) }"> {{ scope.row.id }}</el-button>
          </el-table-column>
          <el-table-column label="DateTime" prop="created_at" width="180" sortable/>
          <el-table-column :filters="[{text: 'X1 cash', value: 'x1_cash'}, {text: 'X1 ba', value: 'x1_ba'}, {text: 'X1 cheque', value: 'x1_cheque'}]" :filter-method="filterHandler" label="Term" prop="term" width="100"/> -->
          <el-table-column label="Rate" width="120" prop="rate" sortable/>
          <el-table-column label="Amount" prop="amount" justify="center" width="110" sortable />
          <el-table-column label="Transfer Amount" prop="transfer_amount" width="170" sortable/>
          <!-- <el-table-column label="ETA" sortable width="100"/> -->
          <!-- <el-table-column label="Payment Method" :filters="[{text: 'Cash', value: 'Cash'}, {text: 'Cheque', value: 'Cheque'}, {text: 'BA', value: 'BA'}]" :filter-method="filterHandler">
        </el-table-column> -->
          <!-- <el-table-column :filters="[{text: '(1/6)', value: '(1/6) Order Done'}, {text: '(2/6)', value: '(2/6) Waiting for Upload Bank in Slip'}, {text: '(3/6)', value: '(3/6) Order Confirmation'}, {text: '(4/6)', value: '(4/6) Processing Transfer'}, {text: '(5/6)', value: '(5/6) Waiting for Upload PO'}, {text: '(6/6)', value: '(6/6) Order Complete'}]" :filter-method="filterHandler" prop="status" label="Status"/> -->
          <el-table-column label="Status" width="106">
            <template slot-scope="scope">
              <el-popover trigger="click" placement="top">
                <p>{{ scope.row.status_desc }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.track_status }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <!-- <el-table-column label="Balance" prop="transfer_amount" sortable width="100"/> -->
          <!-- <el-table-column prop="timeout" label="Bankin Timeout" /> -->
          <el-table-column :filters="[{ text: 'Success', value: 'Success' }, { text: 'Pending', value: 'Pending' }]" :filter-method="filterTag"
                           label="" width="180" filter-placement="bottom-end">
            <el-button slot-scope="scope" type="text" @click="(event) => { BookingStatus(scope.row.status, scope.row.id, scope.row.term) }"> View Status </el-button>
            <!-- <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">View Status</el-button>
              <el-button size="mini" type="danger" @click="BookingStatus(scope.$index, scope.row)">Cancel</el-button>
            </template> -->
          </el-table-column>
          
        </el-table>
        <div align="right">
      <el-button type="primary" size="mini" @click="fetchCompletePaginateBooking(completePagination.prev_page_url)" :disabled="!completePagination.prev_page_url">
        Previous
      </el-button>
      <span>Page {{completePagination.current_page}} of {{completePagination.last_page}}</span>
      <el-button type="primary" size="mini" @click="fetchCompletePaginateBooking(completePagination.next_page_url)" :disabled="!completePagination.next_page_url">
        Next
      </el-button>
    </div>
      </div>
    </el-row><br><br>
  </el-tab-pane>
  
</el-tabs>

    <!-- Booking Table-end -->

  </el-main>
</template>
<style>
  .el-tag {
    cursor: pointer;
  }
</style>
<script>
import Form from 'vform'
import LoginWithGithub from '~/components/LoginWithGithub'
import store from '~/store'
import axios from 'axios'
import Echo from "laravel-echo"
import Pusher from "pusher-js"

export default {
  middleware: ['auth'],

  data () {
    return {
      loading_btn: false,
      confirmForm: new Form({
        term: '',
        amount: ''
      }),
      rate: {
        x1_ba: null,
        x1_cheque: null,
        x1_cash: null,
        x2_ba: null,
        x2_cash: null,
        x2_cheque: null,
      },
      loading : null,
      loading_btn: false,
      status: '',
      booking: {
        amount: '',
        rate: ''
      },
      bookingForm: {
        account_name: '',
        bank_name: '',
        bank_branch: '',
        account_num: ''
      },
      rules: {
          // order_no: [{
          //   required: true,
          //   message: 'Please input order number',
          //   trigger: 'change'
          // }],
          payment_for: [{
            required: true,
            message: 'Please input payment for',
            trigger: 'change'
          }],
        amount: [{
          required: true,
          message: 'Please input amount',
          trigger: 'change'
        } ],
        bank_name: [{
          required: true,
          message: 'Please input bank name',
          trigger: 'change'
        } ],
        account_name: [{
          required: true,
          message: 'Please input account name',
          trigger: 'change'
        }],
        bank_branch: [{
          required: true,
          message: 'Please input branch',
          trigger: 'change'
        }],
        account_num: [{
          required: true,
          message: 'Please input account number',
          trigger: 'change'
        }]
      },
      term: '',
      options1: [{
        value: 'RMB',
        label: 'RMB'
      }],
      options2: [{
        value2: 'MYR',
        label2: 'MYR'
      }],
      options3: [{
        value: 'Full Payment',
        label: 'Full Payment'
      },
      {
        value: 'Deposit',
        label: 'Deposit'
      },
      {
        value: 'Balance',
        label: 'Balance'
      },
      {
        value: 'Others',
        label: 'Others'
      }],
      value: 'RMB',
      dialogFormVisible: false,
      dialogFormVisible1: false,
      formLabelWidth: '0px',
      bookingTable: [],
      // cancelledBooking: [],
      bookingTableComplete: [],
      url: 'api/booking',
      completeBookingurl : "api/user-complete-booking",
      pagination: [],
      completePagination: [],
      bookingConfirmTable: {
        date: 'undefined',
        marking: 'undefined',
        payment_method: 'undefined',
        amount: 'undefined',
        service_charge: 'undefined',
        rate: 'undefined',
        bankin_amount: 'undefined',
        china_beneficiary: 'undefined',
        bank_name: null,
        bank_branch: null,
        status: 2
      }
    }
  },
  mounted () {
    this.getBooking()
    // this.getCancelledBookings()
    this.initBooking()
    this.getRate()
    this.getBookingTableComplete()
    this.listen()
  },
  methods: {
    // listen to update rate changes 
    listen(){
      window.Echo = new Echo({
          broadcaster: 'pusher',
          key: window.config.pusherUrl,
          cluster: 'ap1',
          encrypted: true,
          auth: {
              headers: {
                  Authorization: 'Bearer ' + localStorage.getItem("token")
              },
          },
        
      });
  
      window.Echo.channel('rate-updated')
      .listen('RateUpdated', response => {
        if (! ('Notification' in window)) {
              alert('Web Notification is not supported');
              return;
        }
        this.$message({
          showClose: true,
          message: 'New rate updated at ' + response.rate.created_at,
          duration: 20000
        });
        this.rate = response.rate      
      });
      
    },
    getBooking(){
      let $this = this
      axios.get(this.url).then(response => {
        this.bookingTable = response.data.data
        $this.makePagination(response.data)
      })
    },
    // getCancelledBookings(){
    //   let $this = this
    //   axios.get("booking/cancelled/list").then(response => {
    //     this.cancelledBooking= response.data.data
    //     $this.makePagination(response.data)
    //   })
    // },
    // cancelBooking(id){
    //   console.log(id)
    //   let $this = this
    //   axios.post("api/booking/"+id+"/cancel").then(response => {
    //     this.getBooking();
    //   })
    // },
    getBookingTableComplete(){
      let $this = this
      axios.get(this.completeBookingurl).then(response => {
        this.bookingTableComplete = response.data.data
        $this.makeCompletePagination(response.data)
      })
    },
    getRate() {
      let $this = this
      axios.get('api/rate').then(response => {
        this.rate = response.data
      })
    },
    refreshRate() {
      let $this = this
      this.loading_btn = true
      axios.get('api/rate').then(response => {
        this.loading_btn = false
        this.rate = response.data
        this.$message({
          showClose: true,
          message: 'Rate is updated',
          type: 'success',
          duration: 5000
        })
      })
    },
    initBooking() {
      let $this = this
      axios.get(this.url).then(response => {
        this.bookingTable = response.data.data
      })
    },
    RefreshBooking() {
      let $this = this
      this.loading_btn = true
      axios.get(this.url).then(response => {
        this.loading_btn = false;
        this.bookingTable = response.data.data
        this.$message({
          showClose: true,
          message: 'Booking is updated',
          type: 'success',
          duration: 5000
        })
      })
    },
    RefreshBookingTableComplete() {
      let $this = this
      this.loading_btn = true
      axios.get(this.completeBookingurl).then(response => {
        this.loading_btn = false;
        this.bookingTableComplete = response.data.data
      })
    },
    makePagination(data){
      let pagination ={
        current_page: data.current_page,
        last_page: data.last_page,
        next_page_url: data.next_page_url,
        prev_page_url: data.prev_page_url
      }
      this.pagination = pagination
    },
    
    makeCompletePagination(data){
      let pagination ={
        current_page: data.current_page,
        last_page: data.last_page,
        next_page_url: data.next_page_url,
        prev_page_url: data.prev_page_url
      }
      this.completePagination = pagination
    },
    fetchPaginateBooking(url) {
      this.url = url
      this.getBooking()
     
    },
    fetchCompletePaginateBooking(url) {
      this.completeBookingurl = url
      this.getCompleteBooking()
     },
     
    
    // TODO fetch booking data on load
    formatter (row, column) {
      return row.address
    },
    filterTag (value, row) {
      return row.tag === value
    },
    filterHandler (value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    acceptTerm: function (newterm) {
      if (this.booking.amount == '') {
        this.$message({
          message: 'Please input amount',
          type: 'warning'
        })
        return
      }
      this.dialogFormVisible = true
      this.term = newterm
    },
    // Get calculation before submitting booking
    getCalculationValue (formName) {
      this.loading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let newConfirmation = {
            amount: this.booking.amount,
            term: this.term,
            order_no: this.bookingForm.order_no,
            payment_for: this.bookingForm.payment_for,
            acc_name: this.bookingForm.account_name,
            acc_no: this.bookingForm.account_num,
            bank_name: this.bookingForm.bank_name,
            bank_branch: this.bookingForm.bank_branch
          }
          axios.post('api/booking/calculation', newConfirmation)
            .then((response) => {
              this.loading = false
              this.bookingConfirmTable = response.data;
              this.dialogFormVisible = false
              this.dialogFormVisible1 = true
            })
            .catch((error) => {
              this.$message({
                  showClose: true,
                  message: error.response.data.message,
                  type: 'error',
                  duration: 10000
              });
              this.loading = false
              console.log(error)
            })
        } else {
          this.loading = false
          this.$message({
                showClose: true,
                message: 'Please fill the booking form in full.',
                type: 'error',
                duration: 10000
              })
        }
      })
    },
    createBooking: function () {
      this.loading = true,
      this.dialogFormVisible1 = true
          let newBooking = {
            order_no: this.bookingForm.order_no,
            payment_for: this.bookingForm.payment_for,
            account_name: this.bookingForm.account_name,
            account_num: this.bookingForm.account_num,
            bank_name: this.bookingForm.bank_name,
            bank_branch: this.bookingForm.bank_branch,
            amount: this.booking.amount,
            term: this.term
          }
          axios.post('api/booking', newBooking)
            .then((response) => {
              console.log(response);
              this.loading = false
              // push with return id
              this.$router.push({
                name: 'booking.user.upload',
                params: {id: response.data.id }
              })
              // pass variable to another router
            })
            .catch((error) => {
              console.log(error)
              this.loading = false
              this.$message({
                showClose: true,
                message: 'Internal server error. Please contact support',
                type: 'error',
                duration: 10000
              })
             
            })
    },
    BookingStatus (status, booking_id, term) {
      // TODO : Get booking status from server
      // this.status = status;
      switch (status) {
        case 1:
          this.$router.push({
            name: 'booking.user.upload',
            params: {id: booking_id }
          });
          break;
        case 2:
          this.$router.push({
            name: 'booking.user.upload',
            params: {id: booking_id }
          });
          break;
        case 3:
          this.$router.push({
            name: 'booking.user.confirmation',
            params: {id: booking_id }
          });
          break;
        case 4:
          this.$router.push({
            name: 'booking.user.transfer',
            params: {id: booking_id }
          });
          break;

        case 5:
          if(term === 'x2_cash' || term === 'x2_cheque' || term === 'x2_ba'){
              this.$router.push({
              name: 'booking.user.x2complete',
              params: {id: booking_id }
            });
            break;
          } else {
              this.$router.push({
                  name: 'booking.user.uploadpo',
                  params: {id: booking_id }
              });
              break;
          }



        case 6:
          this.$router.push({
            name: 'booking.user.po',
            params: {id: booking_id }
          });
          break;

        case 7:
          this.$router.push({
            name: 'booking.user.complete',
            params: {id: booking_id }
          });
          break;

        default:
          break;
      }
    }
  }
}
</script>
