<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 align="center">
      <h4 style="margin-top:5%;"></h4>
      <br>
      <h5> Upload China Bankslip To Customer </h5>
      <br>
      <!-- <el-button type="primary" @click="$router.go(-1)">Go Back</el-button> -->
    </div>
    <br>
      <el-row justify="center" align="center">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>Upload China Bankslip</span>
          <!-- <el-button style="float: right; padding: 3px 0" type="text">Operation button</el-button> -->
        </div>
        <el-row :gutter="12" style="text-align:center">
          <el-col :span="20" style="text-align:center">

            <el-form ref="chinaSlipForm" :model="chinaSlipForm" :rules="rules">
              <div align="center">

                <!-- upload image -->
                <el-upload class="upload-demo" :action="'/api/booking/' + booking_id + '/upload-china-bankslip'" :on-preview="handlePreview"
                  :on-error="uploadError" accept=".jpeg, .jpg, .png, .bmp, .doc, .docx, .xls, .xlsx, .pdf" :on-remove="handleRemove"
                  :multiple="false" list-type="picture">
                  <el-button size="small" type="primary">Click to upload</el-button>
                  <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>

                <br>
                <!-- upload image end -->
                <!--                 <el-form-item prop="date">
                  <el-date-picker v-model="chinaSlipForm.date" type="date" placeholder="Pick a day" :picker-options="pickerOptions1">
                  </el-date-picker>
                </el-form-item> -->
                <el-form-item prop="actual_transfer_amount">
                  <el-input v-model.number="chinaSlipForm.actual_transfer_amount" type="text" placeholder="Amount" style="width: 80%" />
                </el-form-item>

                <el-form-item prop="details">
                  <el-input v-model="chinaSlipForm.details" type="text" placeholder="Details" style="width: 80%" />
                </el-form-item>
                <el-form-item>
                  <el-button :loading="loading_btn" type="primary" @click="submitChinaSlip('chinaSlipForm')">Submit</el-button>
                </el-form-item>
              </div>
            </el-form>
          </el-col>
        </el-row>
      </el-card>
    </el-row>
    <br>
    <el-row justify="center" align="center">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>Order Details</span>
          <!-- <el-button style="float: right; padding: 3px 0" type="text">Operation button</el-button> -->
        </div>
        <div class="el-row" style="margin-left: -6px; margin-right: -6px;">
          <div class="el-col el-col-12" style="padding-left: 6px; padding-right: 6px;">
            <div class="el-table el-table--fit el-table--enable-row-hover el-table--enable-row-transition" align="center">

              <div class="el-table__body-wrapper is-scrolling-none">
                <table class="el-table__body" style="width: 400px;" cellspacing="0" cellpadding="0" border="0">
                  <colgroup>
                    <col name="el-table_2_column_9" width="210">
                    <col name="el-table_2_column_10" width="210">
                  </colgroup>
                  <tbody>
                    <tr class="el-table__row">
                      <td class="el-table_2_column_9 is-right ">
                        <div class="cell">Ref No :</div>
                      </td>
                      <td class="el-table_2_column_10 is-left ">
                        <div class="cell">{{ booking_details.id }}</div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_2_column_9 is-right ">
                        <div class="cell">Date :</div>
                      </td>
                      <td class="el-table_2_column_10 is-left ">
                        <div class="cell">{{ booking_details.created_at }}</div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_2_column_9 is-right ">
                        <div class="cell">Customer Marking :</div>
                      </td>
                      <td class="el-table_2_column_10 is-left ">
                        <div class="cell">{{ booking_details.marking }}</div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_2_column_9 is-right ">
                        <div class="cell">Term :</div>
                      </td>
                      <td class="el-table_2_column_10 is-left ">
                        <div class="cell">{{ booking_details.term }}</div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_2_column_9 is-right ">
                        <div class="cell">Beneficiary Account : </div>
                      </td>
                      <td class="el-table_2_column_10 is-left ">
                        <div class="cell">{{booking_details.account_name}}</div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_2_column_9 is-right ">
                        <div class="cell">Beneficiary Account Number : </div>
                      </td>
                      <td class="el-table_2_column_10 is-left ">
                        <div class="cell">{{booking_details.account_num}}</div>
                      </td>
                    </tr>
                    <!---->
                  </tbody>
                </table>
                <!---->
                <!---->
              </div>
              <!---->
              <!---->
              <!---->
              <!---->
              <div class="el-table__column-resize-proxy" style="display: none;"></div>
            </div>
          </div>
          <div class="el-col el-col-12" style="padding-left: 6px; padding-right: 6px;">
            <div class="el-table el-table--fit el-table--enable-row-hover el-table--enable-row-transition" align="center">
              <div class="hidden-columns">
                <div></div>
                <div></div>
              </div>
              <!---->
              <div class="el-table__body-wrapper is-scrolling-none">
                <table class="el-table__body" style="width: 400px;" cellspacing="0" cellpadding="0" border="0">
                  <colgroup>
                    <col name="el-table_3_column_11" width="200">
                    <col name="el-table_3_column_12" width="200">
                  </colgroup>
                  <tbody>
                    <tr class="el-table__row">
                      <td class="el-table_3_column_11 is-right ">
                        <div class="cell">CNY/RMB :</div>
                      </td>
                      <td class="el-table_3_column_12 is-left ">
                        <div class="cell">CNY {{ booking_details.amount }}</div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_3_column_11 is-right ">
                        <div class="cell">+ Service Charge :</div>
                      </td>
                      <td class="el-table_3_column_12 is-left ">
                        <div class="cell">CNY {{ booking_details.service_charge }}</div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_3_column_11 is-right ">
                        <div class="cell">/ RATE :</div>
                      </td>
                      <td class="el-table_3_column_12 is-left ">
                        <div class="cell">{{ booking_details.rate }}</div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_3_column_11 is-right ">
                        <div class="cell"></div>
                      </td>
                      <td class="el-table_3_column_12 is-left ">
                        <div class="cell">MYR {{ booking_details.bia }}</div>
                      </td>
                    </tr>
                    <!-- <tr class="el-table__row">
                      <td class="el-table_3_column_11 is-right ">
                        <div class="cell">+ GST 6% :</div>
                      </td>
                      <td class="el-table_3_column_12 is-left ">
                        <div class="cell">MYR 4,430.88</div>
                      </td>
                    </tr> -->
                    <tr class="el-table__row">
                      <td class="el-table_3_column_11 is-right ">
                        <div class="cell"></div>
                      </td>
                      <td class="el-table_3_column_12 is-left ">
                        <div class="cell">
                          <b>MYR {{ booking_details.bia }}</b>
                        </div>
                      </td>
                    </tr>
                    <tr class="el-table__row">
                      <td class="el-table_3_column_11 is-right ">
                        <div class="cell"></div>
                      </td>
                      <td class="el-table_3_column_12 is-left ">
                        <div class="cell"></div>
                      </td>
                    </tr>
                    <!---->
                  </tbody>
                </table>
                <!---->
                <!---->
              </div>
              <div class="el-table__column-resize-proxy" style="display: none;"></div>
            </div>
          </div>
        </div>
      </el-card>
    </el-row>

    <br>
    <el-row justify="center" align="center">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>Supplier Report</span>
          <!-- <el-button style="float: right; padding: 3px 0" type="text">Operation button</el-button> -->
        </div>
        <el-row :gutter="12" style="text-align:center">
          <el-col :span="20" style="text-align:center">
            <canvas id="myCanvas" ref="myCanvas" v-insert-message="supplier_booking"></canvas>
            <br>
            <el-button @click="downloadReport()" type="text">Download Now</el-button>
          </el-col>
        </el-row>
      </el-card>
      <br>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>User BankinSlip</span>
          <!-- <el-button style="float: right; padding: 3px 0" type="text">Operation button</el-button> -->
        </div>
        <el-row :gutter="12">
          <el-col :span="22" style="text-align:center">
            <a target="_blank" :href="getURL(booking_details.user_bankslip_path)">
              <img v-if="isImage(booking_details.user_bankslip_path)" v-bind:src="booking_details.user_bankslip_path" class="image">
              <p v-else>Download</p>
            </a>
          </el-col>
        </el-row>
      </el-card>
    </el-row>
  </el-main>
</template>
<style>
  .booking-details {
    font-weight: bold;
  }
</style>
<script>
  import ProgressTrack from '~/components/AdminProgressTrack'
  import X2ProgressTrack from '~/components/X2AdminProgressTrack'
  import axios from 'axios'

  export default {
    components: {
      'progress-track': ProgressTrack,
      'x2-progress-track': X2ProgressTrack
    },
    data() {
      return {
        trackerConfig: {
          status: 5,
          term: null
        },
        loading_btn: false,
        booking_id: this.$route.params.id,
        booking_details: {
          id: null,
          amount: null,
          bia: null,
          user_bankslip_path: null,
        },
        supplier: null,
        supplier_booking: {},
        supplier_options: null,
        chinaSlipForm: {
          actual_transfer_amount: null,
          // date: null,
          details: null,
        },
        rules: {
          actual_transfer_amount: [{
              required: true,
              message: 'Please input amount',
              trigger: 'change'
            },
            {
              type: 'number',
              message: 'Amount must be a number',
              trigger: 'change'
            }
          ],
          // date: [{
          //   required: true,
          //   message: 'Please input date',
          //   trigger: 'change'
          // }],
          // details: [{
          //   required: true,
          //   message: 'Please input details',
          //   trigger: 'change'
          // }]
        },
        // pickerOptions1: {
        //   disabledDate(time) {
        //     return time.getTime() > Date.now();
        //   },
        //   shortcuts: [{
        //     text: 'Today',
        //     onClick(picker) {
        //       picker.$emit('pick', new Date());
        //     }
        //   }, {
        //     text: 'Yesterday',
        //     onClick(picker) {
        //       const date = new Date();
        //       date.setTime(date.getTime() - 3600 * 1000 * 24);
        //       picker.$emit('pick', date);
        //     }
        //   }, {
        //     text: 'A week ago',
        //     onClick(picker) {
        //       const date = new Date();
        //       date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
        //       picker.$emit('pick', date);
        //     }
        //   }]
        // }
      }
    },
    beforeCreate() {
      const loading = this.$loading({
        lock: true,
        text: 'Please wait..',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      axios
        .get('/api/admin/booking/' + this.$route.params.id + '/details')
        .then((response) => {
          this.booking_details = response.data
          this.trackerConfig.term = response.data.term;
          loading.close()
        }).catch((error) => {
          loading.close()
          console.log(error)
          this.$router.push({
            name: 'notfound'
          })
        })
      axios.get('/api/supplier-booking/' + this.$route.params.id)
        .then((response) => {
          this.supplier_booking = response.data
          loading.close()
        }).catch((error) => {
          console.log(error)
          this.$router.push({
            name: 'notfound'
          })
          loading.close()
        })

    },
    methods: {
      submitChinaSlip(formName) {
        this.loading_btn = true

        this.$refs[formName].validate((valid) => {
          if (valid) {
            let newChinaSlip = {
              date: this.chinaSlipForm.date,
              actual_transfer_amount: this.chinaSlipForm.actual_transfer_amount,
              details: this.chinaSlipForm.details,
            }

            axios.patch('/api/booking/' + this.booking_id + '/update-china-bankslip', newChinaSlip)
              .then((response) => {
                this.$message({
                  showClose: true,
                  message: 'Your bankinslip has been submitted, please wait customer to upload their purchase order',
                  type: 'success',
                  duration: 5000
                })
                console.log(response)
                this.$router.push({
                  name: 'home'
                })
              })
              .catch((error) => {
                console.log(error)
                this.loading_btn = false
                this.$message({
                  showClose: true,
                  message: 'Please upload your bankin slip first.',
                  type: 'warning',
                  duration: 10000
                })
              })
          } else {
            this.loading_btn = false
            this.$message({
              showClose: true,
              message: 'Please upload your bankin slip first.',
              type: 'warning',
              duration: 10000
            })
          }
        })
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      uploadError(file, fileList) {
        this.$message.warning(`Incorrect file format or file size too big.`)
      },
      getExtension(path){
        return path.slice(-3);
      },
      isImage(path){
        var ext = this.getExtension(path);
        return ext === 'jpg' || ext === 'jpeg' || ext === 'bmp' || ext === 'png';
      },
      getURL(path){
        var getUrl = window.location;
        var baseUrl = getUrl.protocol + "//" + getUrl.host;
        return baseUrl + path;
      }
    },
    directives: {
      insertMessage: function (canvasElement, binding) {
        setTimeout(function (canvasElement, binding) {
          ////////////////// variable //////////////////////////
          var canvasWidth = 450;
          var rowHeight = [20, 40, 60, 80, 100, 120, 140, 170, 190, 210, 230, 250, 270, 290, 310, 330, 350, 390,
            410,
            470, 490, 510, 610, 630
          ]
          const canvasHeight = rowHeight[rowHeight.length - 1];

          var column1X = 220;
          var column2X = 320;
          var column3X = 420;

          ///////////////////Canvast Init////////////////////
          var canvas = document.getElementById("myCanvas");
          canvas.width = canvasWidth;
          canvas.height = canvasHeight;
          // Get canvas context
          var ctx = canvasElement.getContext("2d");
          // Clear the canvas
          ctx.clearRect(0, 0, 300, 150);

          ctx.fillStyle = "#FFFFFF";
          ctx.fillRect(0, 0, canvasWidth, rowHeight[0]);
          for (var i = 1; i < rowHeight.length; i++) {
            if (i % 2 == 1)
              ctx.fillStyle = "#A9D08E";
            else
              ctx.fillStyle = "#FFFFFF";
            ctx.fillRect(0, rowHeight[i - 1], canvasWidth, rowHeight[i]);
          }
          ///////////// fillup with text////////////////
          //// config canvas
          ctx.fillStyle = "#000000";
          ctx.font = "13px Arial";
          ctx.textAlign = "right";
          //// Row 1
          ctx.fillText("Ref No. :", column1X, rowHeight[1] - 5);
          ctx.fillText(binding.value.booking_id, column3X, rowHeight[1] - 5);
          //// Row 2
          ctx.fillText("Date :", column1X, rowHeight[2] - 5);
          ctx.fillText(binding.value.date, column3X, rowHeight[2] - 5);
          //// Row 3
          ctx.fillText("Marking :", column1X, rowHeight[3] - 5);
          ctx.font = "bold 14px Arial";
          ctx.fillStyle = "#0070D5";
          ctx.fillText(binding.value.marking, column3X, rowHeight[3] - 5);
          ctx.fillStyle = "#000000";
          ctx.font = "13px Arial";
          //// Row 4
          ctx.fillText("Payment For(Order No.) :", column1X, rowHeight[4] - 5);
          ctx.fillText(binding.value.order_no, column3X, rowHeight[4] - 5);
          //// Row 4
          ctx.fillText("Payment For :", column1X, rowHeight[5] - 5);
          ctx.fillText(binding.value.payment_for, column3X, rowHeight[5] - 5);
          //// Row 5
          ctx.fillText("Payment Method :", column1X, rowHeight[6] - 5);
          ctx.fillText(binding.value.payment_method, column3X, rowHeight[6] - 5);
          //// Row 6
          ctx.fillText("Remark :", column1X, rowHeight[7] - 10);
          //// Row 7
          // Empty
          //// Row 8
          ctx.fillText("MYR/RM :", column1X, rowHeight[9] - 5);
          ctx.fillText("MYR", column2X, rowHeight[9] - 5);
          ctx.font = "bold 14px Arial";
          ctx.fillText(binding.value.amount_in_myr, column3X, rowHeight[9] - 5);
          ctx.font = "13px Arial";
          //// Row 8
          ctx.fillText("* RATE :", column1X, rowHeight[10] - 5);
          ctx.fillText(binding.value.rate, column3X, rowHeight[10] - 5);
          //// Row 9
          ctx.fillText("REBATE :", column1X, rowHeight[11] - 5);
          ctx.fillText("MYR", column2X, rowHeight[11] - 5);
          ctx.font = "14px Arial";
          ctx.fillText(binding.value.rebate, column3X, rowHeight[11] - 5);
          ctx.font = "13px Arial";
          //// Row 10
          ctx.font = "bold 14px Arial";
          ctx.fillText("CNY", column2X, rowHeight[12] - 5);
          ctx.fillText(binding.value.amountInRMB, column3X, rowHeight[12] - 5);
          ctx.font = "13px Arial";
          //line
          ctx.beginPath();
          ctx.lineWidth = 1;
          ctx.moveTo(column1X + 30, rowHeight[11]);
          ctx.lineTo(column3X + 20, rowHeight[11]);
          ctx.stroke();
          ctx.beginPath();
          ctx.lineWidth = 2;
          ctx.moveTo(column1X + 30, rowHeight[12]);
          ctx.lineTo(column3X + 20, rowHeight[12]);
          ctx.stroke();
          //// Row 11
          ctx.fillText("MYR/RM :", column1X, rowHeight[14] - 5);
          ctx.fillText("MYR", column2X, rowHeight[14] - 5);
          ctx.fillText(binding.value.amount_in_myr, column3X, rowHeight[14] - 5);
          //// Row 12
          // ctx.fillText("Billing(1.0%) :", column1X, rowHeight[15] - 5);
          // ctx.fillText("MYR", column2X, rowHeight[15] - 5);
          // ctx.fillText(binding.value.billing_amount, column3X, rowHeight[15] - 5);
          //// Row 13

          ctx.fillText("+ TAX " + (Math.round((binding.value.tax_rate * 100 - 100) * 100) / 100) + "% :",
            column1X, rowHeight[16] - 5); // TODO : Change to percentage 
          ctx.fillText("MYR", column2X, rowHeight[16] - 5);
          ctx.fillText(binding.value.salestax_amount, column3X, rowHeight[16] - 5);
          // //// Row 14
          // ctx.fillText("+ GST 6% :", column1X, rowHeight[17] - 15);
          // ctx.fillText("MYR", column2X, rowHeight[17] - 15);
          // ctx.fillText("289.84", column3X, rowHeight[17] - 15);
          //// Row 15
          ctx.font = "bold 14px Arial";
          ctx.fillText("Bank In Amount :", column1X, rowHeight[18] - 5);
          ctx.fillStyle = "#0070D5";
          ctx.fillText("MYR", column2X, rowHeight[18] - 5);
          ctx.fillText(binding.value.amount_after_tax, column3X, rowHeight[18] - 5);
          ctx.fillStyle = "#000000";
          ctx.font = "13px Arial";
          //line
          ctx.lineWidth = 1;
          ctx.beginPath();
          ctx.moveTo(column1X + 30, rowHeight[17]);
          ctx.lineTo(column3X + 20, rowHeight[17]);
          ctx.stroke();
          ctx.beginPath();
          ctx.moveTo(column1X + 30, rowHeight[18] + 1);
          ctx.lineTo(column3X + 20, rowHeight[18] + 1);
          ctx.stroke();
          ctx.beginPath();
          ctx.moveTo(column1X + 30, rowHeight[18] - 2);
          ctx.lineTo(column3X + 20, rowHeight[18] - 2);
          ctx.stroke();
          //// Row 16
          // ctx.fillText("Rebate :", column1X, rowHeight[19] - 25);
          // ctx.fillText("CNY", column2X, rowHeight[19] - 25);
          // ctx.fillText("224.68", column3X, rowHeight[19] - 25);
          //// Row 16
          ctx.font = "bold 14px Arial";
          ctx.fillText("Bank In to Account Below :", column1X, rowHeight[20] - 5);
          ctx.font = "bold italic 15px Arial";
          ctx.fillStyle = "#0070D5";
          ctx.fillText("CNY", column2X, rowHeight[20] - 5);
          ctx.fillText(binding.value.amountInRMB, column3X - 20, rowHeight[20] - 5);
          ctx.fillStyle = "#000000";
          ctx.font = "13px Arial";
          //// Row 17
          //// Row 18
          //// Row 19
          // var img = new Image();
          // img.src = "/banklogo.png";
          // img.crossOrigin = "anonymous";
          // var maxwidth = 70;
          // var ratio = maxwidth / img.width;
          // var offset = ((rowHeight[22] - rowHeight[21]) / 2) - (img.height * ratio / 2);
          // var y = rowHeight[21] + offset; // to make it always center

          // img.onload=function(){
          //   ctx.drawImage(img, 50, 530, 80, 50);
          // };

          // text
          ctx.font = "bold 14px Arial";
          ctx.textAlign = "center";
          ctx.fillText("China beneficiary Account", column2X - 40, rowHeight[22] - 80);
          ctx.fillText("户名 : " + binding.value.acc_name, column2X - 40, rowHeight[22] - 60);
          ctx.fillText(binding.value.acc_no, column2X - 40, rowHeight[22] - 40);
          ctx.fillText(binding.value.bank_name, column2X - 40, rowHeight[22] - 20);
          ctx.fillText(binding.value.bank_branch, column2X - 40, rowHeight[22] - 2);

          ctx.font = "13px Arial";
        }, 1000, canvasElement, binding);

      }
    }
  }
</script>