<template>
  <div class="app-container">
    <el-table :key="tableKey" ref="multipleTable" v-loading="listLoading" :data="tableData" :show-header="false" fit @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <!--    <el-table-column align="center" type="index" width="50"></el-table-column>-->
      <el-table-column align="center">
        <template slot-scope="{row, $index}">
          <el-container>
            <el-aside width="80px" style="background-color: #ffffff; padding: 0; margin-bottom: 0;">
              <el-image style="width: 80px; height: 80px" :src="tool.getArImage(row.COVER, '/files/')" @click="handleProduct(row)" />
            </el-aside>
            <el-main style="padding: 5px 5px; text-align: left;">
              <el-row :gutter="10">
                <el-col :xs="24" :sm="24" :lg="6">
                  <span style="cursor: pointer;" @click="handleProduct(row)">{{ row.GOODS_NAME }}</span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="3">
                  <span style="color: #9c9c9c; cursor: pointer;">{{ row.GOODS_NO }}</span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="4">
                  <span style="font-size: 13px;">
                    <span style="font-weight: bold; color: tomato;">
                       DP：{{row.COIN}} {{ row.SELL_PRICE | toThousandFilter }}
                      <span style="font-weight:normal; color: #606266;">({{ row.PRICE_PV | toThousandFilter }}{{ $t('shop.productBV') }})</span>
                    </span>
                  </span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="3">
                  <span style="font-size: 13px;">RP：{{row.COIN}} {{ row.MARKET_PRICE }}</span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="3">
                  <span style="font-size: 13px;">{{ $t('shop.inventory') }}：{{ row.STORE_NUMS }}</span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="5">
                  <el-input-number v-model="storeNums[$index]" size="mini" :min="1" :max="Number(row.STORE_NUMS)" @change="handleInputNumber($event, row)" />
                </el-col>
              </el-row>
            </el-main>
          </el-container>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <div v-show="total>0" class="white-box-footer" style="margin-top: 15px;">
      <div class="flex data" style="float: left; display: inline-block; margin-top: 20px;">
        <el-button type="primary" size="small" style="float: left;" @click="settlement()">{{ $t('shop.checkOut') }}</el-button>
      </div>
      <div class="flex data" style="float: right; display: inline-block; line-height: 28px; font-size: 14px; margin-top: 10px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 0 5px;">
        <div style="margin-right: 2rem; display: inline-block;">{{ $t('shop.productPrice') }}： {{currencyUnitCode}} {{ sellPriceSum | toThousandFilter }}</div>
        <div style="margin-right: 2rem; display: inline-block;">{{ $t('shop.productBV') }}：{{ pricePvSum | toThousandFilter }}</div>
        <div style="display: inline-block;">{{ $t('shop.taxAmount') }}：{{currencyUnitCode}}  {{ taxSum | toThousandFilter }}</div>
      </div>
    </div>

    <!-- 购物车  -->
    <el-dialog v-loading="shoppingCartLoading" :title="$t('shop.productsSettlement')" :visible.sync="visibleShoppingCart" :width="screenWidth" style="margin-top: -95px;" :close="cleanShowCart" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <div v-loading="loading">
        <div class="white-box">
          <el-table :data="goods" :show-header="false">
            <el-table-column align="center">
              <template slot-scope="{row}">
                <el-container>
                  <el-aside width="100px" style="background-color: #ffffff; padding: 0; margin-bottom: 0;">
                    <el-image style="width: 100px; height: 100px" :src="tool.getArImage(row.COVER, '/files/')" @click="handleProduct(row)" />
                  </el-aside>
                  <el-main style="padding: 10px 5px; text-align: left;">
                    <el-row :gutter="10">
                      <el-col :xs="24" :sm="8" :lg="8">
                        <span style="cursor: pointer;" @click="handleProduct(row)">{{ row.GOODS_NAME }}</span>
                      </el-col>
                      <el-col :xs="24" :sm="4" :lg="4">
                        <span style="color: #9c9c9c; cursor: pointer;">{{ row.GOODS_NO }}</span>
                      </el-col>
                      <el-col :xs="16" :sm="4" :lg="4">
                        <span style="font-weight: bold;"> {{currencyUnitCode}} {{ row.member_price | toThousandFilter }}</span>
                        <span>({{ row.PRICE_PV | toThousandFilter }}{{ $t('shop.productBV') }})</span><br>
                      </el-col>
                      <el-col :xs="8" :sm="3" :lg="3">
                        <span style="">x {{ row.chose_num }}</span>
                      </el-col>
                      <el-col :xs="24" :sm="5" :lg="5">
                        <span style="color: tomato; font-weight: bold;">{{currencyUnitCode}} {{ row.member_price_plus | toThousandFilter }}</span>
                        <span style="color: tomato;">({{ row.PRICE_PV | toThousandFilter }}{{ $t('shop.productBV') }})</span><br>
                      </el-col>
                    </el-row>
                  </el-main>
                </el-container>
              </template>
            </el-table-column>
          </el-table>

          <div class="white-box-footer">
            <!-- 订单合计 -->
            <div class="" style="margin: 15px 0;">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :lg="3">
                  <span style="font-weight: bold; word-break: normal; white-space: normal; line-height: 28px;">{{ $t('shop.totalOrders') }}：</span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="21" style="word-break: normal; white-space: nowrap; line-height: 28px;">
                  <span>{{ $t('shop.total') }}：{{currencyUnitCode}} {{ parseFloat(cashSum) | toThousandFilter }}({{ pricePvSum | toThousandFilter }}{{ $t('shop.productBV') }})</span><br>
                  <span>{{ $t('shop.freight') }}：{{currencyUnitCode}} {{ pointFreight }}</span>
                </el-col>
              </el-row>
            </div>
            <el-divider />
            <el-form :rules="rules" ref="payForm" :model="payForm">
              <el-form-item :label="$t('shop.declarationCenterNumber')" prop="recUserName">
                <el-input v-model="payForm.recUserName" :disabled="isDec == '1'" />
              </el-form-item>
            </el-form>

            <!-- 支付方式/账户余额 {{ cashCurrency }}:  -->
            <div class="" style="margin: 15px 0;">
              <el-row :gutter="20" type="flex" style="flex-wrap: wrap;">
                <el-col :xs="24" :sm="24" :lg="3">
                  <span style="font-weight: bold; word-break: normal; white-space: normal; line-height: 28px;">{{ $t('shop.selectPayment') }}：</span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="21" style="word-break: normal; white-space: nowrap;">
                  <el-radio-group v-model="payType" @change="chosePayType">
                    <div v-for="(item, index) in payList" :key="index" class="address">
                      <el-radio :label="item.label" border>
                        {{ item.name }}<span v-if="item.label === 'cash'" style="color: tomato;">( {{currencyUnitCode}} {{ userBalance.cash | toThousandFilter }})</span>
                          <span v-if="item.label === 'prp'" style="color: tomato;">( {{currencyUnitCode}} {{ userBalance.prp | toThousandFilter }})</span>
                      </el-radio>
                    </div>
                  </el-radio-group>
                </el-col>
              </el-row>
            </div>
            <el-divider />
            <!-- 收货地址 -->
            <div class="" style="margin: 15px 0;">
              <el-row :gutter="10" type="flex" style="flex-wrap: wrap;">
                <el-col :xs="24" :sm="24" :lg="3">
                  <span style="font-weight: bold; word-break: normal; white-space: normal; line-height: 28px;">{{ $t('shop.selectAddress') }}：</span>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="21" style="word-break: normal; white-space: nowrap;">
                  <el-radio-group v-model="addressId" @change="choseAddress">
                    <div class="address">
                      <el-radio :label="selfPickUpAddressId">{{ $t('shop.selfPickUp') }}</el-radio>
                    </div>
                    <div v-for="(item, index) in shippingAddressList" :key="index" class="address">
                      <el-radio :label="item.ID" style="word-break: break-all; white-space: normal;">
                        <span>{{ item.ADDRESS }}, {{ item.LGA_NAME }}, {{ item.PROVINCE_NAME }}</span>
                        <el-divider direction="vertical" />
                        <span>{{ item.MOBILE }}</span>
                        <el-divider direction="vertical" />
                        <span>{{ item.CONSIGNEE }}</span>
                      </el-radio>
                    </div>
                  </el-radio-group>
                </el-col>
              </el-row>
            </div>
          </div>

          <div class="white-box-footer">
            <el-row :gutter="40">
              <el-col :xs="24" :sm="24" :lg="24" align="left">
                <el-button type="warning" size="small" @click="cleanShowCart">{{ $t('shop.goBack') }}</el-button>
                <el-button type="primary" size="small" :loading="submitButtonStat" @click="orderSubmit">{{ $t('shop.goPay') }}</el-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- payStack模态框 -->
    <el-dialog v-loading="payStackLoading" :title="$t('shop.goPay')" :visible.sync="visible" :width="payStackScreenWidth" :before-close="handleClose">
      <section>
        <el-form :model="form">
          <el-form-item :label="$t('user.email')" label-width="100px" required>
            <el-input v-model="form.email" autocomplete="off" />
          </el-form-item>
          <el-form-item :label="$t('shop.amount')" label-width="100px" required>
            <el-input v-model="form.amount" autocomplete="off" readonly />
          </el-form-item>
        </el-form>
      </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="handleClose"
      >
        <el-button type="primary" size="small">{{ $t('shop.goPay') }}</el-button>
      </paystack>
      <el-button type="danger" size="small" class="cancelButton" style="margin-left: 10px;" @click="handleClose">{{ $t('common.cancel') }}</el-button>
    </el-dialog>

    <!-- 倒计时页面 -->
    <el-dialog :title="$t('common.hint')" :visible.sync="payDialog" :width="payStackScreenWidth" :show-close="false" :close="handleOrderList">
      <el-card shadow="always">
        <el-result icon="success" :title="$t('common.successfully')" :sub-title="$t('shop.successOrderTips')">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="handleOrderList">{{ $t('shop.goBack') }}({{ countdown }})</el-button>
          </template>
        </el-result>
      </el-card>
    </el-dialog>

    <!-- 商品详情 -->
    <el-dialog :title="product.GOODS_NO" :visible.sync="visibleProduct" :width="screenWidth" style="margin-top: -95px;">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="12">
          <el-image style="width: 100%; height: 100%" :style="imageStyle" :src="tool.getArImage(product.COVER, '/files/')" />
        </el-col>
        <el-col :xs="24" :sm="12" :lg="12">
          <div style="text-align: left; line-height: 50px; font-size: 16px;">
            <span style="font-weight: bold; font-size: 20px;">{{ product.GOODS_NAME }}</span><br>
            <span style="font-weight: bold; font-size: 15px;">{{ $t('shop.productCode') }}：{{ product.GOODS_NO }}</span><br>
            <span style="color: tomato;">{{ $t('shop.salesPrice') }}：{{currencyUnitCode}} {{ product.SELL_PRICE }}</span><br>
            <span>{{ $t('shop.marketPrice') }}：{{currencyUnitCode}} {{ product.MARKET_PRICE }}</span><br>
            <span>{{ $t('shop.productBV') }}：{{ product.PRICE_PV | toThousandFilter }}</span><br>
            <span>{{ $t('shop.taxRate') }}：{{ product.TAX_RATE / 100 }}</span><br>
            <span>{{ $t('shop.taxAmount') }}：{{ product.taxAmount | toThousandFilter }}</span><br>
            <span>{{ $t('shop.inventory') }}：{{ product.STORE_NUMS }}</span>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { createApproachOrder, createOrder, deleteApproachOrder, fetchProductList, fetchShoppingCart } from '@/api/shop'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import { getScreenWidth } from '@/utils'
import tool from '@/utils/tool'
import usersInfo from '@/utils/usersInfo'
import paystack from 'vue-paystack'

export default {
  name: 'StandardProducts',
  components: { Pagination, paystack },
  directives: { waves },
  filters: {
    priceFilter(price) {
      return tool.formatPrice(price)
    },
    taxAmountFilter(row) {
      return tool.calculateTax(row.SELL_PRICE, row.TAX_RATE)
    },
    statusFilter(status) {
      const statusMap = {
        Unpaid: 'info',
        Paid: 'success'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      tableData: [],
      listLoading: true,
      listQuery: {
        categoryType: 1,
        page: 1,
        limit: 50
      },
      tool: tool,
      multipleSelection: [],
      sellPriceSum: 0.00,
      pricePvSum: 0.00,
      taxSum: 0.00,
      storeNums: [],
      display: false,
      currentPage: 1,
      shoppingCartGoods: [],

      shoppingCartLoading: false,
      visibleShoppingCart: false,
      loading: false,

      goods: [],
      payList: [],
      cashCurrency: '',
      currency: {},
      pointsSum: 0,
      cashSum: 0,
      pointFreight: 0,
      freeShipping: '',
      goodsId: '',
      goodsNum: '',
      payPassword: '',
      submitButtonStat: false,
      sn: '',
      orderType: '',
      payDialog: false,
      countdown: 5,
      visible: false,
      totalAmount: 0.00,
      freight: 0.00,
      userBalance: {},

      payType: 'cash',
      payStackLoading: false,
      channels: ['card', 'bank', 'ussd', 'qr'],
      form: {
        publicKey: process.env.VUE_APP_BASE_PAY_STACK_PUBLIC_KEY,
        currency: 'NGN',
        firstname: usersInfo.userName(),
        lastname: '',
        email: usersInfo.userEmail(),
        amount: 0,
        orderSn: '',
        metadata: {
          cart_id: '',
          custom_fields: [
            {
              display_name: 'orderSn',
              variable_name: 'orderSn',
              value: this.sn
            },
            {
              display_name: 'orderType',
              variable_name: 'orderType',
              value: 'userOrder'
            }
          ]
        },

      },
      payStackScreenWidth: getScreenWidth() > 500 ? '450px' : getScreenWidth() + 'px',

      addressId: '',
      selfPickUpAddressId: '100000000000000000',
      shippingAddressList: [],

      screenWidth: getScreenWidth() > 600 ? '50%' : getScreenWidth() + 'px',
      labelPosition: getScreenWidth() > 600 ? 'right' : 'top',
      dialog: false,
      dialogLoading: false,

      visibleProduct: false,
      product: {
        GOODS_NAME: '',
        GOODS_NO: '',
        COVER: '',
        SELL_PRICE: 0,
        PRICE_PV: 0,
        TAX_RATE: 0,
        taxAmount: 0
      },
      imageStyle: 'margin-top: -50px;',
      recRealName:null,
      // recUserName:usersInfo.userName(),
      recUserName:null,
      isDec:null,
      currencyUnitCode: "",
        rules: {
            recUserName: [
                {required: true, message: this.$t('shop.declarationCenterNumberTips'), trigger: 'blur'},
            ],
        },
        payForm: {
            recUserName: null
        }
    }
  },
  computed: {
    // PayStack混淆串
    reference() {
      let text = ''
      const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      for (let i = 0; i < 10; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length))
      }
      return text
    }
  },
     watch: {
     isDec: {
       handler(newValue, old) {
         if (newValue == '1') {
            this.payForm.recUserName = usersInfo.userName();
         }
       },
     }
   },
  created() {
    this.getList()
  },
  mounted() {
    // 支付方式、账户信息、余额
    this.getShoppingCart()
  },
  methods: {
    // 商品列表
    getList() {
      this.listLoading = true
      fetchProductList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.totalCount

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)

        const settingObj = this.list
        for (const i in this.list) {
          this.storeNums[i] = 1
          settingObj[i].chose_num = 0
        }

        this.tableData = Object.values(settingObj)
        const pageList = this.multipleSelection[this.currentPage]
        this.$nextTick(function() {
          for (const i in this.tableData) {
            for (const j in pageList) {
              if (pageList[j].ID === this.tableData[i].ID) {
                this.$data.storeNums[i] = pageList[j].chose_num
                this.tableData[i].chose_num = pageList[j].chose_num
                break
              }
            }
          }
        })
      })
    },
    // 选择商品计数
    handleInputNumber(current, row) {
      const pageList = this.multipleSelection[this.listQuery.page]
      let selectStatus = false
      for (const i in pageList) {
        if (pageList[i].ID === row.ID) {
          pageList[i].chose_num = current
          selectStatus = true
          break
        }
      }
      if (selectStatus) {
        this.multipleSelection[this.listQuery.page] = pageList
        this.handleSureChange()
      }
    },
    // 统计商品
    handleSureChange() {
      if (this.multipleSelection.length > 0) {
        let accumulatorSellPrice = 0; let accumulatorPricePv = 0; let accumulatorTax = 0
        this.multipleSelection.forEach(item => {
          item.forEach(accumulator => { accumulatorSellPrice += accumulator.SELL_PRICE * accumulator.chose_num * accumulator.DISCOUNT / 100 })
          item.forEach(accumulator => { accumulatorPricePv += Number(accumulator.PRICE_PV) * Number(accumulator.chose_num) * (Number(accumulator.DISCOUNT) / 100) })
          item.forEach(accumulator => { accumulatorTax += tool.calculateTax(Number(accumulator.SELL_PRICE), Number(accumulator.TAX_RATE), Number(accumulator.chose_num)) })
        })

        this.sellPriceSum = tool.formatPrice(accumulatorSellPrice)
        this.pricePvSum = tool.formatPrice(accumulatorPricePv)
        this.taxSum = tool.formatPrice(accumulatorTax)

        this.display = true
      } else {
        this.sellPriceSum = this.pricePvSum = this.taxSum = 0.00
        this.display = true
      }
    },
    // 选择商品
    handleSelectionChange(val) {
      let idx = -1; let num
      for (const i in this.tableData) {
        for (const v in val) {
          if (val[v].ID === this.tableData[i].ID) {
            idx = i
            num = this.storeNums[idx]
            val[v]['chose_num'] = num
            break
          }
        }
      }
      this.multipleSelection[this.listQuery.page] = val
      // 计算统计
      this.handleSureChange()
    },
    // 结算商品
    settlement() {
      if (this.multipleSelection.length <= 0) {
        this.$message.error(this.$t('shop.chooseTips'))
        return false
      }
      // 弹出购物车
      this.visibleShoppingCart = true
      // 展示购物车商品数据
      this.getShowCart()
    },
    // 设置运费
    setFreight() {
      // 如果地址为自提，则运费为0
      this.pointFreight = (this.addressId === this.selfPickUpAddressId) ? Number(0) : Number(this.freight)
    },
    // 表格合并
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('shop.total')
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if ((!values.every(value => isNaN(value))) && [2, 3, 4, 6].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)
          if (index !== 2) {
            sums[index] = sums[index]
          }
        }
      })

      return sums
    },
    // 支付方式、账户信息、余额
    getShoppingCart() {
      fetchShoppingCart({ categoryType: this.listQuery.categoryType }).then(response => {
        // 收货地址
        this.shippingAddressList = response.data.allAddress
        this.shippingAddressList.map(item => {
          if (item.IS_DEFAULT === '1') {
            this.addressId = item.ID
          }
        })
        // 账户
        this.userBalance = response.data.userBalance
        // 支付方式处理
        this.currency = response.data.payList
        this.cashCurrency = response.data.payList[this.payType].name
        // 支付方式
        for (const item of response.data.sellType) {
          if (item.id === this.listQuery.categoryType) {
            this.payList = item.sell_type
            break
          }
        }
        // 支付方式的第一项默认选中
        this.payType = Object.values(this.payList)[0]['label']
        // 免运费阈值
        this.freeShipping = response.data.freeShipping
        // 运费
        this.freight = response.data.freight
        //是否是报单中心
        this.isDec = response.data.isDec
        //货币单位
        this.currencyUnitCode = response.data.coin

      })
    },
    // 支付
    orderSubmit() {
        this.$refs['payForm'].validate((valid) => {
            if (valid) {
                // 账户余额
                const amountBalance = this.userBalance[this.payType]
                // 账户类型提示信息
                let accountType = this.currency[this.payType].name
                // if (amountBalance < 0 || !accountType) {
                //   this.$message({
                //     message: this.$t('shop.paymentError'),
                //     type: 'error'
                //   })
                //   return false
                // }
                // 支付方式处理
                if (['cash', 'pay_stack'].includes(this.payType)) {
                    const payObj = this.payList.find((item) => {
                        return item.label === this.payType
                    })
                    accountType = (payObj.length <= 0) ? '' : payObj.name
                }

                // 余额是否充足
                if ((this.payType !== 'pay_stack') && ((amountBalance - this.cashSum) < 0)) {
                    this.$message({
                        message: accountType + this.$t('shop.balanceNotAllow'),
                        type: 'error'
                    })
                    this.submitButtonStat = false
                    return false
                }

                this.submitButtonStat = true
                this.$prompt(this.$t('shop.inputPasswordTips'), this.$t('common.hint'), {
                    confirmButtonText: this.$t('common.confirm'),
                    cancelButtonText: this.$t('common.cancel'),
                    customClass: 'csClass',
                    type: 'info',
                    inputType: 'password',
                    inputPattern: /\S+/,
                    inputErrorMessage: this.$t('shop.inputPasswordTips')
                }).then(({value}) => {
                    this.payPassword = value
                    const params = {
                        goodsId: this.goodsId,
                        goodsNum: this.goodsNum,
                        payPassword: this.payPassword,
                        email: this.form.email,
                        addressId: this.addressId,
                        address: this.address,
                        payType: this.payType,
                        userName: this.payForm.recUserName
                    }
                    if (this.payType === 'pay_stack') {
                        // PayStack支付
                        createApproachOrder(params).then(response => {
                            this.visibleShoppingCart = false
                            this.submitButtonStat = false
                            this.visible = true
                            this.form.orderSn = response.data.SN
                            this.form.amount = this.cashSum
                            this.form.metadata.cart_id = response.data.SN
                            this.form.metadata.custom_fields[0].value = response.data.SN
                        }).catch(err => {
                            this.$message({
                                message: err,
                                type: 'error',
                                duration: 5 * 1000
                            })
                            this.submitButtonStat = false
                        })
                    } else {
                        // 非PayStack支付
                        createOrder(params).then(() => {
                            this.submitButtonStat = false
                            this.$message({
                                message: this.$t('common.successfully'),
                                type: 'success',
                                duration: 5 * 1000
                            })
                            this.$router.push({path: `/shop/own-order`})
                        }).catch(err => {
                            this.$message({
                                message: err,
                                type: 'warning',
                                duration: 5 * 1000
                            })
                            this.submitButtonStat = false
                        })
                    }
                }).catch(() => {
                    this.submitButtonStat = false
                })
            } else {
                console.log('error submit!!');
                return false;
            }
        });
    },
    // 计算价格
    getSumMoney() {
      const cash_plus_sum = []
      const goodsId = []
      const goodsNum = []
      let choseNum = 0
      this.goods.map(item => {
        choseNum = Number(item.chose_num)
        if (choseNum > 0) {
          cash_plus_sum.push(item.SELL_PRICE * choseNum * (item.DISCOUNT / 100))
          goodsId.push(item.ID)
          goodsNum.push(choseNum)
        }
      })
      this.goodsNum = goodsNum
      this.goodsId = goodsId
      // 增加运费
      const payAmount = tool.sum(cash_plus_sum)
      // 设置运费
      this.setFreight()
      // 商品总价大于预定值,免运费
      this.pointFreight = (this.pointFreight > 0) ? ((payAmount >= this.freeShipping) ? 0 : this.freight) : 0
      // 计算总价
      this.pointsSum = this.cashSum = this.form.amount = tool.formatPrice(tool.sum(cash_plus_sum) + this.pointFreight)
    },
    // 展示购物车信息
    getShowCart() {
      const orderGoods = this.multipleSelection
      let cartGoods = []
      for (const i in orderGoods) {
        cartGoods = orderGoods[i]
        if (!cartGoods) continue

        cartGoods.map(item => {
          if (Number(item.chose_num) > 0) {
            const discount = item.DISCOUNT / 100
            item.member_price = Math.round(item.SELL_PRICE * discount * 100) / 100
            item.member_price_plus = Math.round(item.SELL_PRICE * Number(item.chose_num) * discount * 100) / 100
            item.tax_amount_plus = Math.round((item.member_price - item.member_price / (1 + item.TAX_RATE / 100)) * item.chose_num * 100) / 100
            this.goods.push(item)
            this.totalAmount += item.member_price_plus
          }
        })
      }

      this.goods = cartGoods

      // 计算价格
      this.getSumMoney()
    },
    // 关闭时清空购物车等信息
    cleanShowCart() {
      this.visibleShoppingCart = false
      this.goods = []
      this.totalAmount = 0.00
      this.goodsNum = ''
      this.goodsId = ''
      this.pointFreight = 0
      this.pointsSum = 0
    },
    // 选择收货地址
    choseAddress(addressId) {
      this.addressId = addressId
      // 设置运费
      this.setFreight()
      // 计算价格
      this.getSumMoney()
    },
    // 切换支付方式
    chosePayType(type) {
      this.payType = type
    },
    // 关闭支付回调
    handleClose() {
      this.$confirm(this.$t('shop.confirmClose')).then(_ => {
        deleteApproachOrder({ orderSn: this.form.orderSn }).then(() => {
          // 关闭支付模态框
          this.visible = false
          // 关闭购物车
          this.visibleShoppingCart = false
          this.submitButtonStat = false
        })
      })
    },
    // 支付成功回调
    processPayment() {
      // 关闭支付页面
      this.visible = false
      this.payStackLoading = false
      // 显示支付成功模态框
      this.payDialog = true
      // 启动支付成功倒计时
      this.handleCountdown()
    },
    // 倒计时结束跳转
    handleOrderList() {
      this.$router.push({ path: `/shop/own-order` })
    },
    // 启动倒计时
    handleCountdown() {
      // 创建定时器
      setInterval(() => {
        // 每隔1秒把time的值减一，赋值给span标签
        this.countdown--
        if (this.countdown === 0) {
          // 倒计时结束,跳转到订单列表
          this.$router.push({ path: `/shop/own-order` })
        }
      }, 1000)
    },
    // 商品详情
    handleProduct(row) {
      this.product = row
      this.product.taxAmount = tool.calculateTax(row.SELL_PRICE, row.TAX_RATE)
      this.visibleProduct = true
    }
  }
}
</script>

<style>
.el-table--medium .el-table__cell {
  padding: 3px 0;
}

.csClass{
  width: 360px;
}

.address{
  line-height: 2.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>
