<template>
    <div v-loading="loading">
        <div class="white-box">
            <el-form :model="form" ref="form"  label-width="250px" class="form-page">
                <div class="hr-tip"><span>Member information<!-- 会员信息 --></span></div>
                <el-form-item label="Member code" prop="insertUserName"><!-- 会员编号 -->
                    <el-input v-model="form.insertUserName"
                    placeholder="Please enter member code."
                    :rules="{ required: true, message: 'Please enter member code.', trigger: 'blur' }"
                    @blur="upgradeInfo()"
                    ><!-- 请输入升级的会员编号 -->
                    </el-input>
                </el-form-item>
                <el-form-item label="Member level"><!-- 会员级别 -->
                    <el-input v-model="form.userDecName"
                    disabled
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="Member name"><!-- 会员姓名 -->
                    <el-input v-model="form.userRealName"
                    disabled
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="Joining date"><!-- 加入日期 -->
                    <el-input v-model="form.addAt"
                    disabled
                    >
                    </el-input>
                </el-form-item>
                <el-form-item v-if="!isMax" label="Upgrade way"><!-- 升级方式 -->
                    <el-input v-model="form.upgradeFunc"
                    disabled
                    >
                    </el-input>
                </el-form-item>
                <el-form-item v-if="!isMax" label="To upgrade level  " prop="upgradeValue"><!-- 升级级别 -->
                    <el-select v-model="form.upgradeValue" placeholder="Please select a level" @change="changeLevel"><!-- 请选择级别 -->
                        <el-option
                        v-for="item in upgradeOption"
                        :key="item.ID"
                        :label="item.LEVEL_NAME"
                        :value="{value:item.ID, diffPv:item.REPAIR_PV}">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="!isMax" label="Top Up(BV)"><!-- 升级补差业绩 -->
                    <el-input v-model="needDiffPv"
                    disabled
                    >
                    </el-input>
                </el-form-item>
                <el-form-item v-if="!isMax">
                    <template slot="label">
                        Upgrade purchase product<!-- 升级购买商品 -->
                    </template>
                    <el-tabs type="border-card" v-model="decWay" style="position: relative;width: 100%;">
                        <!--<el-tab-pane name="1">
                            <span slot="label">套餐</span>
                            <el-table class="table-box" :data="_tableData" stripe style="width: 100%;" highlight-current-row @current-change="handleCurrentChange">
                                <el-table-column
                                        type="index"
                                        width="50">
                                </el-table-column>
                            <el-table-column label=" " width="50">
                                <template slot-scope="scope">
                                    <span class="el-checkbox__input" :class="{'is-checked':scope && scope.row && currentRow && scope.row.ID==currentRow.ID}">
                                    <span class="el-checkbox__inner">
                                    </span>
                                    <input type="checkbox" aria-hidden="false" class="el-checkbox__original" value="">
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column label="套餐名称" prop="PACKAGE_NAME">
                            </el-table-column>
                            <el-table-column label="套餐金额" prop="AMOUNT">
                            </el-table-column>
                            <el-table-column label="套餐PV" prop="PV">
                                <template>
                                </template>
                            </el-table-column>
                            <el-table-column label="所属报单级别" prop="LEVEL_NAME">
                                <template>
                                </template>
                            </el-table-column>
                            <el-table-column label="套餐内容" prop="PACKAGE_CONTENT">
                                <template >
                                </template>
                            </el-table-column>
                        </el-table>
                        </el-tab-pane> -->
                        <el-tab-pane label="product" name="2"><!-- 商品 -->
                            <el-table class="table-box" v-if="numList.length > 0" :data="tableDatas" stripe style="width: 100%;" highlight-current-row  @selection-change="handleSelectionChange">
                                <el-table-column
                                        type="selection"
                                        width="55">
                                </el-table-column>

                                <el-table-column label="product Name" prop="GOODS_NAME"><!-- 商品名称 -->

                                </el-table-column>
                                <el-table-column label="product Code" prop="GOODS_NO"><!-- 商品编号 -->

                                </el-table-column>
                                <el-table-column label="product Price" prop="SELL_PRICE"><!-- 产品价格 -->

                                </el-table-column>
                                <el-table-column label="product BV" prop="PRICE_PV"><!-- BV价格 -->

                                </el-table-column>
                                <el-table-column label="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"><!--税额-->
                                    <template slot-scope="scope">
                                        <span>{{ Math.round(scope.row.TAX * 100) / 100 }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="Qty" width="150"><!-- 数量 -->
                                    <template slot-scope="scope">
                                        <el-input-number size="mini" v-model="numList[scope.$index]"  :min="0" :max="Number(scope.row.STORE_NUMS)" @change="value=>{handleChange(value,scope.row.ID)}"></el-input-number>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="white-box-footer flex">
                                <el-button @click="getSum()">Total calculation<!-- 计算合计 --></el-button>
                                <div class='flex data' style="flex:1;justify-content: flex-end;">
                                    <div style="margin-right:2rem"><!-- 商品价格 -->product price：₦ {{sell_price_sum}}</div>
                                    <div><!-- 商品PV -->product BV：{{price_pv_sum}}</div>
                                </div>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </el-form-item>
                <el-form-item v-if="!isMax">
                    <template slot="label">
                        Recipient name<!-- 收货人 -->
                    </template>
                    <el-input v-model="form.consignee"></el-input>
                </el-form-item>
                <el-form-item v-if="!isMax">
                    <template slot="label">
                         Phone Number<!-- 收货人手机 -->
                    </template>
                    <el-input v-model="form.acceptMobile"></el-input>
                </el-form-item>
                <el-form-item v-if="!isMax" prop="areaSelected">
                    <template slot="label">
                        State<!-- 地区 -->
                    </template>
                    <el-cascader
                            size="large"
                            :options="regionData"
                            v-model="form.areaSelected">
                    </el-cascader>
                </el-form-item>
                <el-form-item v-if="!isMax">
                  <template slot="label">
                    Local Government Area
                  </template>
                  <el-input v-model="form.lgaName"></el-input>
                </el-form-item>
                <el-form-item v-if="!isMax">
                  <template slot="label">
                    City
                  </template>
                  <el-input v-model="form.cityName"></el-input>
                </el-form-item>
                <el-form-item v-if="!isMax">
                    <template slot="label">
                        Detailed address<!-- 详细地址 -->
                    </template>
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
                <el-form-item v-if="!isMax" label="note"><!-- 备注 -->
                    <el-input type="textarea" v-model="form.remark"></el-input>
                </el-form-item>

                <el-form-item v-if="!isMax" label="Payment method" required><!-- 支付方式 -->
                  <el-radio-group v-model="form.payType" @change="payMethodChange">
                    <el-radio v-for="(item, index) in payList" :key='index' :label="item.label">{{ item.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item v-if="!isMax">
                    <el-button type="primary" @click="onSubmit" :loading="submitButtonStat">SAVE<!-- 保存 --></el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-dialog title="Pay" v-if="visible" :visible.sync="visible" width="30%" v-loading="payStackLoading" :before-close="handleClose">
          <section>
            <div class="formcontainer">
              <el-divider></el-divider>
              <div class="container">
                <el-form :model="PayStackForm">
                  <el-form-item label="Email" label-width="100px" required>
                    <el-input v-model="PayStackForm.email" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="Amount" label-width="100px" required>
                    <el-input v-model="PayStackForm.amount" autocomplete="off" readonly></el-input>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </section>

          <paystack
            :firstname="PayStackForm.firstname"
            :lastname="PayStackForm.lastname"
            :amount="PayStackForm.amount * 100"
            :email="PayStackForm.email"
            :metadata="PayStackForm.metadata"
            :currency="PayStackForm.currency"
            :paystackkey="PayStackForm.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 Vue from 'vue'
import network from '@/utils/network'
import baseInfo from '@/utils/baseInfo'
import store from '@/utils/vuexStore'
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: 'user_upgrade',
  mounted () {
    this.getData()
  },
  computed: {
    _tableData () {
      if (this.tableData == null) {
        return [];
      }
      if (this.form.decLv === '') {
        return this.tableData;
      }
      return this.tableData.filter(item => {
        return item.LEVEL_ID === this.form.decLv
      })
    },
    reference() {
      let text = '';
      let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      for (let i = 0; i < 10; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      return text;
    }
  },

  data () {
    return {
      nowPerf: '',
      nextPerf: '',
      decUserName: '',
      needDiffPv: '',
      isMax: true,
      upgradeOption: [],
      toLevel: '',
      currentRow: null,
      decWay: '2',
      regionData: store.state.regionInfo.regionData,
      form: {
        address: '',
        areaSelected:[],
        consignee: '',
        upgradeFunc: '',
        upgradeValue: '',
        addAt: '',
        userRealName: '',
        userDecName: '',
        remark: '',
        realName: '',
        decLv: '',
        insertUserName: '',
        decUserName: '',
        recUserName: '',
        conUserName: '',
        insertUserIdCard: '',
        packageId: '',
        goodsId:[],
        goodsNum:[],
        province: '',
        // city: '',
        // county: '',
        lgaName: '',
        cityName: '',
        acceptMobile: '',
        payType: '',
      },
      num: 1,
      tableData: null,
      tableDatas: null,
      allDecPackage: {},
      loading: false,
      submitButtonStat: false,
      submitButton: false,
      allGoods: [],
      multipleSelection: [],
      goodsNums: [],
      numList: [],
      sell_price_sum: 0.00,
      price_pv_sum: 0.00,
      payList: [],
      sn: '',
      payDialog: false,
      countdown: 5,
      visible: false,
      payStackLoading: false,
      channels: ['card', 'bank', 'ussd', 'qr'], // eft(南非)  mobile_money(加纳)
      PayStackForm: {
        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
            },
            {
              display_name: 'orderType',
              variable_name: 'orderType',
              value: 'userUpgrade'
            },
          ]
        },
      },
    }
  },
  components: {
    paystack
  },
  methods: {
    // 获取要升级的会员信息
    upgradeInfo () {
      if (this.form.insertUserName) {
        network.postData(`user/upgrade-info`,{userName:this.form.insertUserName}).then(response => {
          this.form.addAt=response.baseInfo.ADD_AT
          this.form.userRealName=response.baseInfo.REAL_NAME
          this.form.userDecName=response.baseInfo.DEC_NAME
          this.isMax = response.baseInfo.IS_MAX
          this.upgradeOption = response.baseInfo.LEVEL_LIST
          this.form.upgradeFunc = response.baseInfo.UPGRADE_FUNC //upgradeFunc升级方式
          this.nowPerf = response.baseInfo.NOW_PERF // 用户当前业绩
          this.nextPerf = response.baseInfo.NEXT_PERF
        })
      }
    },
    changeLevel (data) {
      let { value,diffPv } = data
      this.needDiffPv = diffPv
      this.toLevel = value
    },
    getSum () {
      let sell_price_sum=0, price_pv_sum=0;
      this.multipleSelection.map((item,index) => {
        sell_price_sum += Number(item.SELL_PRICE) * item.goodsNum;
        price_pv_sum += Number(item.PRICE_PV) * item.goodsNum;
      })
      this.sell_price_sum = tool.formatPrice(sell_price_sum);
      this.price_pv_sum = tool.formatPrice(price_pv_sum);
    },
    getData () {
      network.getData(`user/upgrade`).then(response => {
        this.decUserName = response.decUserName
        this.loading = false;
        this.allDecPackage = response.allDecPackage;
        this.allGoods = response.allGoods;
        let settingObj = this.allDecPackage;
        let settingArr = Object.keys(settingObj).map(key => {
          // console.log(key); //为每个键名
          return settingObj[key];  // 把每个对象返回出去生成一个新的数组中相当于0:{id:1}
        });
        this.tableData = settingArr;
        let settingObj1 = this.allGoods;
        for (let i in settingObj1) {
          this.numList[i] = 1;
          settingObj1[i].goodsNum= 1 ;
        }
        this.tableDatas=settingObj1;

        // 支付方式
        this.payList = response.sellType[0]['sell_type']
        // 支付方式的第一项默认选中
        this.form.payType = Object.values(this.payList)[1]['label']
      }).catch(() => {
      });
    },
    handleCurrentChange (val) {
      console.log(val)
      if (!val) { return }
      this.currentRow = val;
      this.form.packageId = this.currentRow.ID;

      console.log(this.form.packageId)
    },
    handleSelectionChange (val) {
      let idx = -1, num;
      for (let i in this.tableDatas) {
        for (let v in val) {
          if (val[v].ID === this.tableDatas[i].ID) {
            idx = i;
            num = this.numList[idx];
            val[v]['goodsNum'] = num;
            break;
          }
        }
      }
      console.log(val)
      this.multipleSelection = val;

    },
    handleChange (value,ID) {
      for (let i in this.multipleSelection) {
        if (this.multipleSelection[i]['ID'] === ID) {
          this.multipleSelection[i]['goodsNum'] = value;
        }
      }
    },
    getGoods () {
      this.form.goodsId = [];
      this.form.goodsNum = [];
      this.multipleSelection.map((item,index) => {
        console.log(item);
        console.log('==');
        this.form.goodsId.push(item.ID)
        this.form.goodsNum.push(item.goodsNum)
      })
    },
    onSubmit () {
      if (!this.form.insertUserName) {
        this.$message({
          message: 'Please enter the member code',//请输入会员编号
          type: 'error'
        })
        return false;
      }
      if (!this.toLevel) {
        this.$message({
          message: 'Please select a level',//请选择级别
          type: 'error'
        })
        return false
      }

      this.getGoods();
      this.submitButtonStat = true
      let path = 'user/upgrade'
      let postData = {
        decUserName: this.decUserName,
        packageId: this.form.packageId,
        goodsId: this.form.goodsId,
        goodsNum: this.form.goodsNum,
        location: this.form.location,
        decWay: this.decWay,
        decLv: this.toLevel, // 用户想升级到什么级别
        insertUserName: this.form.insertUserName, // 要升级的用户的编号
        remark: this.form.remark,
        address: this.form.address,
        consignee: this.form.consignee,
        acceptMobile: this.form.acceptMobile,
        province: this.form.areaSelected[0] ? this.form.areaSelected[0] : '',
        // city: this.form.areaSelected[1] ? this.form.areaSelected[1] : '',
        // county: this.form.areaSelected[2] ? this.form.areaSelected[2] : '',
        lgaName: this.form.lgaName,
        cityName: this.form.cityName,
        nowPerf: this.nowPerf,
        nextPerf: this.nextPerf,
        payType: this.form.payType,
      }

      return network.postData(path, postData).then(response => {
        // 非PayStack支付
        if (this.form.payType !== 'pay_stack') {
          this.$message({
            message: response,
            type: 'success'
          })
          this.submitButtonStat = false
          this.$router.push({path: `/shop/order-list`})
        } else {
          // PayStack支付
          this.submitButtonStat = false
          this.PayStackForm.orderSn = response.SN
          this.PayStackForm.amount = response.ORDER_AMOUNT
          this.PayStackForm.metadata.custom_fields[0].value = response.SN
          this.visible = true
        }
      }).catch(() => {
        this.submitButtonStat = false
      })
    },

    selectOne (event, item) {
      network.getData(`user/upgrade`).then(response => {
      })
    },

    handleChkConUser () {
      if (this.form.conUserName) {
        this.loading = true
        network.getData('user/full-info', {userName: this.form.conUserName}).then(response => {
          this.conRealName = response.REAL_NAME + response.isLocation
          this.loading = false
        }).catch(response => {
          this.conRealName = '-'
          this.loading = false
        })
      }
    },

    handleChkRecUser () {
      if (this.form.recUserName) {
        this.loading = true
        network.getData('user/full-info', {userName: this.form.recUserName}).then(response => {
          this.recRealName = response.REAL_NAME
          this.loading = false
        }).catch(response => {
          this.recRealName = '-'
          this.loading = false
        })
      }
    },
    // 切换支付方式
    payMethodChange (type) {
      this.form.payType = type
    },
    // 关闭支付回调
    handleClose () {
      let _this = this
      _this.$confirm('Confirm to close?').then(() => {
        return network.postData('shop/delete-approach-order', {orderSn: this.PayStackForm.orderSn}).then(() => {
          // 关闭支付模态框
          _this.visible = false
        })
      }).catch(() => {
        // 关闭支付模态框
        _this.visible = false
      })
    },
    // 支付成功回调
    processPayment (response) {
      // 关闭支付页面
      this.visible = false
      this.payStackLoading = false

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

<style>
    .hr-tip {
        font-size: 12px;
        position: relative;
        text-align: center;
        height: 30px;
        line-height: 30px;
        color: #999;
        margin-bottom: 20px;
    }

    .hr-tip:before {
        content: '';
        display: block;
        position: absolute;
        left: 0;
        right: 0;
        top: 14px;
        border-bottom: 1px dashed #ddd;
        height: 1px;
    }

    .hr-tip span {
        display: inline-block;
        background: #fff;
        position: relative;
        padding: 0 10px;
    }
    .el-input-number--mini .el-input-number__decrease, .el-input-number--mini .el-input-number__increase{width: 22px!important}
    .el-input-number.is-controls-right .el-input__inner{padding-left: 10px;
        padding-right: 30px;}
    .el-tabs--border-card{
        position: relative;
      width: 100%;
    /*width: 600px;*/
    }
    .flex{
        display: flex;
    }
    .form-page{
        width:100% !important;
    }
    .payButton {
      border: none;
      padding: 0;
    }
</style>
