<template>
  <div>
    <div v-loading="loading">
      <div class="white-box">
        <div class="table">
          <el-table
            :data="goods"
            style="width: 100%"
            show-summary
            :summary-method="getSummaries">
             <el-table-column label="Product Name" prop="GOODS_NAME"><!--商品名称-->
            </el-table-column>

            <el-table-column label="Product Picture" ><!--图片-->
              <template slot-scope="scope">
                <el-image style="width: 100px; height: 100px" :src="tool.getArImage(scope.row.COVER, '/files/')" :preview-src-list="[tool.getArImage(scope.row.COVER, '/files/')]"></el-image>
              </template>
            </el-table-column>

            <el-table-column label="Product price" prop="member_price"><!--商品价格-->
              <template slot-scope="scope">
                <span>{{ Math.round(scope.row.member_price * 100) / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="Member BV" prop="member_pv" v-if="category_type === 1"><!--会员PV-->
              <template slot-scope="scope">
                <span>{{ Math.round(scope.row.member_pv * 100) / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="Tax rate" prop="TAX_RATE"><!--税率-->
              <template slot-scope="scope">
                <span>{{ Math.round(scope.row.TAX_RATE * 100) / 100 }}</span>
              </template>
            </el-table-column>

            <el-table-column label="Tax" prop="tax_amount_plus"><!--税额-->
              <template slot-scope="scope">
                <span>{{ Math.round(scope.row.tax_amount_plus * 100) / 100 }}</span>
              </template>
            </el-table-column>
<!--                    <el-table-column label="库存" prop="STORE_NUMS">-->
<!--                    </el-table-column>-->

            <el-table-column label="Quantity" prop="chose_num"><!--数量-->

            </el-table-column>
            <el-table-column label="Total Amount" prop="member_price_plus"><!--合计金额-->
              <template slot-scope="scope">
                <span>{{ Math.round(scope.row.member_price_plus * 100) / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="Total BV" prop="member_pv_plus" v-if="category_type === 1"><!--合计PV-->
              <template slot-scope="scope">
                <span>{{ Math.round(scope.row.member_pv_plus * 100) / 100 }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="address_box">
          Please select the shipping address：	<!--  请选择收货地址 -->
          <el-radio-group v-model="addressId" @change='choseAddress'>
            <div v-for="(item , index) in all_address" :key='index' class="address">
              <el-radio :label="item.ID" >
                Full address：{{item.ADDRESS}}, {{item.CITY_NAME}}, {{item.LGA_NAME}}, {{item.PROVINCE_NAME}}  &nbsp;&nbsp;&nbsp;&nbsp;
                <!-- 详细地址 -->  &nbsp;&nbsp;
                <!-- 收件人姓名 -->  Recipient name：{{item.CONSIGNEE}}&nbsp;&nbsp;&nbsp;&nbsp;
                <!-- 手机号码 --> Phone Number：{{item.MOBILE}}
              </el-radio>
            </div>
            <div class="address">
              <el-radio label="100000000000000000">Self Pick-up</el-radio><!--自提-->
            </div>
          </el-radio-group>
          </div>
          <div class="address_box">
            Please select payment method：<!-- 请选择支付方式 -->
            <el-radio-group v-model="payType" @change='chosePayType'>
              <div v-for="(item, index) in payList" :key='index' class="address">
                <el-radio :label="item.label">{{ item.name }}</el-radio>
              </div>
            </el-radio-group>
          </div>

          <div class="box address_box">
            Total orders：<!-- 订单合计 -->
              <div class="sum">
                <div class="sum_box" v-if="category_type === 1">
                  <div>Freight</div><!-- 运费 -->
                  <div>
                    <span v-if="category_type === 1">{{ prefixSign }}</span>
                      {{ pointFreight }}
                    <span v-if="category_type === 1">{{ unit }}</span>
                  </div>
                </div>
                <div class="sum_box">
                  <div>Amount paid</div><!-- 实付金额 -->
                  <div>
                    <span v-if="category_type === 1">{{ prefixSign }}</span>
                      {{ payType === "cash" ? cashSum : pointsSum }}
                    <span v-if="category_type === 1">{{ unit }}</span>
                  </div>
                </div>
              </div>
          </div>

          <div class="box address_box">
            Account Balance：	<!-- 账户余额 -->
            <div class="sum">
              <div v-if="category_type === 1">
  <!--              <div class="sum_box">-->
  <!--                  <div>账户积分</div>-->
  <!--                  <div>{{ balance.points }}</div>-->
  <!--              </div>-->
              <div class="sum_box">
                <div>Account Balance</div><!-- 账户余额 -->
                <div>₦ {{ balance.cash }} NGN</div>
              </div>
  <!--            <div class="sum_box">-->
  <!--              <div>Exchange points</div>&lt;!&ndash; 兑换点数 &ndash;&gt;-->
  <!--              <div>{{ balance.exchange }}</div>-->
  <!--            </div>-->
            </div>

            <div v-if="category_type === 4">
              <div class="sum_box">
                <div>Travel bonus</div><!-- 旅游积分 -->
                <div>{{ balance.tourism_points }}</div>
              </div>
            </div>

            <div v-if="category_type === 5">
              <div class="sum_box">
                <div>Car bonus</div><!-- 名车积分 -->
                <div>{{ balance.garage_points }}</div>
              </div>
            </div>

            <div v-if="category_type === 6">
              <div class="sum_box">
                <div>Villa bonus</div><!-- 豪宅积分 -->
                <div>{{ balance.villa_points }}</div>
              </div>
            </div>
          </div>
        </div>

        <div>
          <el-button type="danger" @click="cancelOrder()">Go Back</el-button>
          <el-button type="primary" @click="goToAccounts()" :loading="submitButtonStat">Pay</el-button><!--去结算-->
        </div>
      </div>
    </div>

    <el-dialog title="Pay" v-if="visible" :visible.sync="visible" width="30%" v-loading="payStackLoading" :before-close="handleClose">
      <section>
  <!--      <h1>Lorem Ipsum Dolor Sit Amet</h1>-->
        <div class="formcontainer">
          <el-divider></el-divider>
          <div class="container">
            <el-form :model="form">
              <el-form-item label="Email" label-width="100px" required>
                <el-input v-model="form.email" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="Amount" label-width="100px" required>
                <el-input v-model="form.amount" autocomplete="off" readonly></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </section>
      <paystack
          :firstname="form.firstname"
          :lastname="form.lastname"
          :amount="form.amount * 100"
          :email="form.email"
          :metadata="form.metadata"
          :currency="form.currency"
          :paystackkey="form.publicKey"
          :reference="reference"
          :channels="channels"
          :callback="processPayment"
          :close="processClose"
      >
        <el-button type="primary" size="small">Pay</el-button>
      </paystack>
      <el-button type="danger" size="small" class="cancelButton" @click="handleClose">Cancel</el-button>
    </el-dialog>

    <el-dialog title="Tips" :visible.sync="payDialog" :show-close="false" width="350px" :close="handleOrderList">
      <el-result icon="success" title="the order is successful">
        <template slot="extra">
          <span style="color: #008efa; font-size: 30px;">{{ countdown }}</span>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script>
import network from '@/utils/network'
import tool from '@/utils/tool'
import userInfo from '@/utils/userInfo'
import { PAY_STACK_PUBLIC_KEY, PAY_STACK_CURRENCY } from '@/utils/config'
import paystack from 'vue-paystack'

export default{
  name: 'order',
  data: function () {
    return {
      tool: tool,
      loading: true,
      goods: [],
      payList: [],
      all_address: [],
      balance: {},
      addressId: '',
      payType: '',
      payTypeId: '',
      pointsSum: '',
      cashSum: '',
      freight: '',
      pointFreight: '',
      freeShipping: '',
      goodsId: '',
      goodsNum: '',
      payPassword: '',
      submitButtonStat: false,
      category_type: '',
      prefixSign: '₦',
      unit: 'NGN',
      sn: '',
      payDialog: false,
      countdown: 5,
      visible: false,
      payStackLoading: false,
      channels: ["card", "bank", "ussd", "qr"], // eft(南非)  mobile_money(加纳)
      form: {
        publicKey: PAY_STACK_PUBLIC_KEY,
        currency: PAY_STACK_CURRENCY,
        firstname: userInfo.userName(),
        lastname: '',
        email: userInfo.userEmail(),
        amount: 0, // kobo
        orderSn: '',
        metadata: {
          cart_id: this.sn,
          custom_fields: [
            {
              display_name: 'orderSn',
              variable_name: 'orderSn',
              value: this.sn
            },
          ]
        },
      },
    }
  },
  components: {
    paystack
  },
  async created () {
    let option = sessionStorage.getItem('order_goods');
    this.category_type = parseInt(sessionStorage.getItem('category_type'))
    await this.getShowCart();
    if (option) {
      let pageGoodsList = JSON.parse(option);
      // console.log(pageGoodsList);
      let pageList;
      for (let i in pageGoodsList) {
        pageList = pageGoodsList[i];
        if (!pageList) continue;

        pageList.map((pageData, index) => {
          if (Number(pageData.chose_num) > 0) {
            let discount = pageData.DISCOUNT / 100;
            pageData.member_price = Math.round(pageData.SELL_PRICE * discount * 100) / 100;
            pageData.member_price_plus = Math.round(pageData.SELL_PRICE * Number(pageData.chose_num) * discount * 100) / 100;
            pageData.member_pv = Math.round(pageData.PRICE_PV * discount * 100) / 100;
            pageData.member_pv_plus = Math.round(pageData.PRICE_PV * Number(pageData.chose_num) * discount * 100) / 100;
            pageData.tax_amount_plus = Math.round((pageData.member_price - pageData.member_price / (1 + pageData.TAX_RATE / 100)) * pageData.chose_num * 100) / 100;
            this.goods.push(pageData)
          }
        })
      }

      await this.getSumMoney();
    }
  },
  computed: {
    reference () {
      let text = '';
      let possible =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      for (let i = 0; i < 10; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      return text;
    }
  },
  methods:{
    cancelOrder () {
      history.go(-1)
    },
    setFreight () {
      // 如果地址为自提，则运费为0
      if (this.addressId === '100000000000000000') {
        this.pointFreight = Number(0)
      } else {
        this.pointFreight = Number(this.freight)
      }
    },
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = 'Total'; // 合计
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if ((!values.every(value => isNaN(value))) && [5, 6, 7, 8].includes(index)) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return Math.round((prev + curr) * 100) / 100;
            } else {
              return Math.round(prev * 100) / 100;
            }
          }, 0);
        }
      });

      return sums;
    },
    goToAccounts () {
      let amountBalance = 0
      // 前置判断余额是否够支付
      if (this.category_type === 1) {
        if (this.payType === 'cash') {
          amountBalance = this.balance.cash
        } else if (this.payType === 'exchange') {
          amountBalance = this.balance.exchange
        }
      } else if (this.category_type === 4) {
        amountBalance = this.balance.tourism_points
      } else if (this.category_type === 5) {
        amountBalance = this.balance.garage_points
      }

      // 提示信息
      let tips = 'Ecoin' // 余额
      if (this.payType !== 'cash' && this.payType !== 'pay_stack') {
        let payObj = this.payList.find((item) => {
          return item.label === this.payType
        })
        tips = (payObj.length <= 0) ? '' : payObj.name
      }

      // 余额是否充足
      if ((amountBalance > 0) && (this.payType !== 'pay_stack') && ((amountBalance - this.cashSum) < 0)) {
        let tips = this.payList[this.payType] ? this.payList[this.payType].label : 'Ecoin'
        this.$message({
          message: tips + ' insufficient, unable to buy products', // 不足，无法购买商品
          type: 'error'
        })
        this.submitButtonStat = false
        return false
      }

      this.submitButtonStat = true
      // let path = 'sure-order'
      this.$prompt('Please enter your payment password', 'Hint', { // '请输入支付密码', '提示'
        confirmButtonText: 'Confirm', // 确定
        cancelButtonText: 'Cancel', // 取消
        inputType: 'password',
        inputPattern: /\S+/,
        inputErrorMessage: 'Please enter your payment password' // 请输入支付密码
      }).then(({value}) => {
        this.payPassword = value
        let params = {
          addressId: this.addressId,
          payType: this.payType,
          goodsId: this.goodsId,
          goodsNum: this.goodsNum,
          payPassword: this.payPassword,
          email: this.form.email,
        }

        // PayStack支付
        if (this.payType === 'pay_stack') {
          return network.postData('shop/sure-approach-order', params).then((response) => {
            this.submitButtonStat = false

            this.form.orderSn = response.SN
            this.form.amount = this.cashSum
            this.form.metadata.custom_fields[0].value = response.SN
            this.visible = true
          }).catch(() => {
            this.submitButtonStat = false
          })
        } else {
          // 非PayStack支付
          return network.postData('shop/sure-order', params).then(() => {
            this.submitButtonStat = false
            this.$router.push({path: `/shop/order-list`})
          }).catch(() => {
            this.submitButtonStat = false
          })
        }
      }).catch(() => {
        this.submitButtonStat = false
      })
    },
    getSumMoney () {
      // let points_plus_sum=[];
      let cash_plus_sum = [];
      let goodsId = [];
      let goodsNum = [];
      let choseNum = 0;
      this.goods.map((item,index)=> {
        choseNum = Number(item.chose_num);
        if (choseNum > 0) {
          // points_plus_sum.push(item.SELL_PRICE * choseNum);
          cash_plus_sum.push(item.SELL_PRICE * choseNum * (item.DISCOUNT / 100));
          goodsId.push(item.ID);
          goodsNum.push(choseNum);
        }
      })
      this.goodsNum = goodsNum;
      this.goodsId = goodsId;
      // 增加运费03-12yuan
      let payAmount = tool.sum(cash_plus_sum);
      // let payPointAmount = tool.sum(points_plus_sum);

      // 只有普通商品有运费
      if (this.category_type === 1) {
        // 商品自提,免运费
        this.setFreight();
        // 商品总价大于预定值,免运费
        this.pointFreight = (this.pointFreight > 0) ? ((payAmount >= this.freeShipping) ? 0 : this.freight) : 0
      } else {
        // 非普通商品,没有运费
        this.pointFreight = 0
      }
      // if(payPointAmount>=300){
      //     this.pointFreight = 0;
      // }else{
      //     this.pointFreight = 15;
      // }
      // console.log('points_plus_sum',points_plus_sum);
      // console.log('cash_plus_sum',cash_plus_sum);
      // this.pointsSum=tool.formatPrice(tool.sum(points_plus_sum) + this.pointFreight);
      this.pointsSum = this.cashSum = this.form.amount = tool.formatPrice(tool.sum(cash_plus_sum) + this.pointFreight) ;
    },
    async getShowCart () {
      await network.getData('shop/show-cart', {categoryType: this.categoryType}).then(response => {
        this.loading = false
        // 收货地址
        this.all_address = response.allAddress;
        this.all_address.map((item, index) => {
          if (item.IS_DEFAULT == 1) {
            this.addressId = item.ID
          }
        })
        // 账户
        this.balance = response.userBalance

        // 支付方式
        for (let item of response.sellType) {
          if (item.id === this.category_type) {
            this.payList = item.sell_type
            break
          }
        }

        // 支付方式的第一项默认选中
        this.payType = Object.values(this.payList)[1]['label']
        // 免运费阈值
        this.freeShipping = response.freeShipping
        // 运费
        this.freight = response.freight
      })
    },
    // 切换支付方式
    chosePayType (type) {
      this.payType = type
    },
    choseAddress (addressId) {
      this.addressId = addressId
      this.setFreight()
      this.getSumMoney()
    },
    // 关闭支付回调
    handleClose () {
      let _this = this
      _this.$confirm('Confirm to close?').then(() => {
        return network.postData('shop/delete-approach-order', {orderSn: this.form.orderSn}).then(() => {
          // 关闭支付模态框
          _this.visible = false
          // 关闭购物车页面,返回到订单列表页
          sessionStorage.setItem('order_goods', null)
          sessionStorage.setItem('category_type', null)
          this.$router.push({path: `/shop/index`})
        })
      }).catch(() => {
        // 关闭支付模态框
        _this.visible = false
        // 关闭购物车页面,返回到订单列表页
        sessionStorage.setItem('order_goods', null)
        sessionStorage.setItem('category_type', null)
        this.$router.push({path: `/shop/index`})
      })
    },
    // 支付成功回调
    processPayment (response) {
      // 关闭支付页面
      this.visible = false
      this.payStackLoading = false

      // 显示支付成功模态框
      this.payDialog = true
      this.handleCountdown()
    },
    // 关闭支付回调
    processClose () {
      // 关闭支付模态框
      this.visible = false
      // 关闭购物车页面,返回到订单列表页
      sessionStorage.removeItem('order_goods')
      sessionStorage.removeItem('category_type')
      this.$router.push({path: `/shop/index`})
    },
    handleOrderList () {
      this.$router.push({path: `/shop/order-list`})
    },
    // 启动倒计时
    handleCountdown () {
      // 创建定时器
      setInterval(() => {
        // 每隔1秒把time的值减一，赋值给span标签
        this.countdown--
        if (this.countdown === 0) {
          // 倒计时结束,跳转到订单列表
          this.$router.push({path: `/shop/order-list`})
        }
      }, 1000)
    },
  },
}
</script>

<style scoped>
.address{
    /* height: 3rem; */
    line-height: 3.5rem;

}
.address_box{
     border-bottom: 1px solid #e3e3e3;
}
.sum{
    display: inline-block;
}
.box{
    margin: 1rem 0;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-bottom: 1rem;
}
.sum_box{
    display: flex;
    margin-left: 1rem;
}
.sum_box > div{
    line-height: 2rem;
}
.sum_box > div:nth-child(1){
    margin-right: 1rem;
}
.payButton {
    border: none;
    padding: 0;
}
</style>
