<template>
    <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="商品名称" prop="GOODS_NAME">
                    </el-table-column>

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

                    <el-table-column label="会员价格" prop="member_price">
                    </el-table-column>
                    <el-table-column label="会员PV" prop="member_pv">
                    </el-table-column>
                    <el-table-column label="数量" prop="chose_num">

                    </el-table-column>
                    <el-table-column label="合计金额" prop="member_price_plus">

                    </el-table-column>
                    <el-table-column label="合计PV" prop="member_pv_plus"></el-table-column>
                </el-table>
            </div>

            <div class="box address_box">
                <div style="min-width: 65px;">收件人：</div>
                <div class="sum" style="margin-top: 5px; margin-bottom: 5px;">
                  <div class="sum_box">
                    <div style="min-width: 70px; font-size: 14px; margin-right: 0;">真实姓名<span style="color: red;">*</span></div>
                    <div><el-input size="small" v-model="consigneeRealName" style="min-width: 150px;"></el-input></div>
                  </div>
                  <div class="sum_box" style="margin-top: 5px;">
                    <div style="min-width: 70px; font-size: 14px; margin-right: 0;">身份证号<span style="color: red;">*</span></div>
                    <div><el-input size="small" v-model="consigneeIdNo" style="min-width: 150px;"></el-input></div>
                  </div>
                </div>
            </div>
            <div class="address_box">
                请选择收货地址：
                <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" >
                            {{item.PROVINCE_NAME}}省{{item.CITY_NAME}}市{{item.COUNTY_NAME}}县&nbsp;&nbsp;&nbsp;&nbsp;
                            详细地址：{{item.ADDRESS}}
<!--                            邮编：{{item.ZIP_CODE}}-->
                            手机号码：{{item.MOBILE}}
                        </el-radio>
                    </div>
                </el-radio-group>
            </div>
            <div class="address_box">
                请选择支付方式：
                <el-radio-group v-model="payType" @change='chosePayType'>
                    <div v-for="(item , index) in payList" :key='index' class="address">
                        <el-radio :label="item.type" >
                            {{item.name}}
                        </el-radio>
                    </div>
                </el-radio-group>
            </div>
            <div class="box address_box">
                合计：
                <div class="sum">
                    <div class="sum_box">
                        <div>实付金额</div>
                        <div>￥{{ cashSum }}元</div>
                    </div>
                </div>
            </div>
            <div>
                <el-button @click="goToAccounts()" :loading="submitButtonStat">去结算</el-button>
            </div>
        </div>

      <el-dialog title="支付" v-if="visible" :visible.sync="visible" width="450px" :before-close="handleClose">
        <div class="app-container">
          <div v-loading="loading" class="white-box">
            <form method="post" name="ePayment" :action="actionUrl">
              <input type="hidden" name="MerchantCode" v-bind:value="form.MerchantCode"></input>
              <input type="hidden" name="PaymentId" v-bind:value="form.PaymentId"></input>
              <input type="hidden" name="RefNo" v-bind:value="form.RefNo"></input>
              <input type="hidden" name="Amount"  v-bind:value="form.Amount"></input>
              <input type="hidden" name="Currency"  v-bind:value="form.Currency"></input>
              <input type="hidden" name="ProdDesc"  v-bind:value="form.ProdDesc"></input>
              <input type="hidden" name="UserName"  v-bind:value="form.UserName"></input>
              <input type="hidden" name="UserEmail" v-bind:value="form.UserEmail"></input>
              <input type="hidden" name="UserContact" v-bind:value="form.UserContact"></input>
              <!-- <input type="hidden" name="Remark"  value="gfdfgd"></input> -->
              <input type="hidden" name="Lang"  v-bind:value="form.Lang"></input>
              <input type="hidden" name="SignatureType" value="SHA256"></input>
              <input type="hidden" name="Signature" v-bind:value="form.Signature"></input>
              <input type="hidden" name="ResponseURL" v-bind:value="form.ResponseURL"></input>
              <input type="hidden" name="BackendURL" v-bind:value="form.BackendURL"></input>
              <span style="display: inline-block; margin: 0 auto;">因汇率波动，实际支付金额可能会有浮动</span><br /><br />
              <input type="submit" value="支 付" name="Submit" class="payBtn"></input>
            </form>
          </div>
        </div>
      </el-dialog>

      <el-dialog title="支付成功" :visible.sync="payDialog" :show-close="false" width="320px" :close="handleOrderList">
        <el-result icon="success" title="支付成功">
          <template slot="extra">
            <span style="color: #008efa; font-size: 30px;">{{ countdown }}</span>
          </template>
        </el-result>
      </el-dialog>

      <el-dialog title="提示" :visible.sync="IDCardDialog" width="350px">
        <el-result icon="warning" title="">
          <template slot="extra">
            <span style="font-size: 15px;">购买跨境商品必须上传<span style="color: red;">收件人身份信息</span>，如已上传请忽略</span><br /><br />
            <el-button type="primary" size="medium" @click="uploadIDCard">去上传</el-button>
          </template>
        </el-result>
      </el-dialog>
    </div>
</template>

<script>
 import network from '@/utils/network'
 import tool from '@/utils/tool'
 import QRCode from 'qrcode'
  export default{
      name: 'order-overseas',
      data() {
          return {
              loading: true,
              tool: tool,
              goods:[],
              payList:[],
              all_address:[],
              balance:{},
              addressId:'',
              payType:'',
              pointsSum:'',
              cashSum:'',
              freight:'',
              pointFreight:'',
              goodsId:'',
              goodsNum:'',
              payPassword:'',
              submitButtonStat: false,
              visible: false,
              payLoading: false,
              payDialog: false,
              countdown: 5,
              actionUrl: '',
              ePaymentShow: false,
              form: {
                MerchantCode: '',
                PaymentId: 2,
                RefNo: '',
                Amount: '',
                Currency: '',
                ProdDesc: '',
                UserName: '',
                UserEmail: '',
                UserContact: '',
                Remark: '',
                Lang: 'UTF-8',
                SignatureType: 'SHA256',
                Signature: '',
                ResponseURL: '',
                BackendURL: '',
              },
              consigneeRealName: '',
              consigneeIdNo: '',
              IDCardDialog: false,
              IDCardWebsite: 'http://t.taoplus.com.my/Home/UploadIDCard',
              flag:this.isPC(),
          }
      },
      created() {
          this.getShowCart();
          let option= sessionStorage.getItem('order_goods');
          if(option){
              let pageGoodsList = JSON.parse(option);
              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;

                        this.goods.push(pageData)
                      }
                  })
              }

              this.getSumMoney();
          }
          // 展示上传身份证页面
          this.IDCardDialog  = true
      },
      methods:{
        async pay(info) {
          if (this.flag === 'website') {
            //pc
            if (this.payType === 'WAPWECHAT') {
              //微信
              let payTypeText = this.payType === 'WECHAT' ? '微信' : '支付宝'
              let url = await QRCode.toDataURL(info.qrCode);
              await this.$alert(`<img src=${url}  alt="" >`, `请使用${payTypeText}扫码支付`, {
                showClose: false,
                showCancelButton: true,
                showConfirmButton: true,
                confirmButtonText: '支付成功',
                cancelButtonText: '取消支付',
                dangerouslyUseHTMLString: true,
                center: true,
                callback: action => {
                  if(action === 'confirm'){
                    this.$router.push({path: `/shop/order-list`})
                  }else{
                    this.$router.push({path: `/shop/index`})
                  }
                }
              });
            } else {
             //支付宝
            }
          } else {
            //移动端
            if (this.payType === 'WAPWECHAT') {
              //微信
              window.location.replace("https://fele.ncshop.elken.com/wechat.html?mweb_url=" + info.mweb_url)
            } else {

            }
          }
        },
         is_weixn(){
           const ua = navigator.userAgent.toLowerCase();
           return ua.indexOf('micromessenger') !== -1;
         },
          getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
              if (index === 0) {
                sums[index] = '合计';
                return;
              }
              const values = data.map(item => Number(item[column.property]));
              if ((!values.every(value => isNaN(value))) && [4, 5, 6].includes(index)) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                    return prev + curr;
                  } else {
                    return prev;
                  }
                }, 0);
              }
            });

            return sums;
          },
          goToAccounts(){
              // 海外商品收货地址中必须包含邮编(20240409前端不处理邮编)
              let address = ''
              this.all_address.map(item => {
                if (item.ID === this.addressId) {
                  address = item
                }
              })
              // if (address.ZIP_CODE.length < 1) {
              //   this.$message({
              //     message: '收货地址中没有邮政编码',
              //     type: 'error'
              //   })
              //   return false
              // }

              // 必须填写真实姓名和身份证号码
              if (((this.consigneeIdNo.trim()).length <= 0) || ((this.consigneeRealName.trim()).length <= 0)) {
                  this.$message({
                    message: '收件人真实姓名和身份证号码必须填写',
                    type: 'error'
                  })
                  return false
              }

              this.submitButtonStat = true
              const data = {
                addressId: this.addressId,
                payType: this.payType,
                goodsId: this.goodsId,
                goodsNum: this.goodsNum,
                consigneeIdNo: this.consigneeIdNo,
                consigneeRealName: this.consigneeRealName,
              }
              network.postData(`shop/sure-approach-order`, data).then(async response => {
                await this.pay(response)
                this.submitButtonStat = false
                // 跳转到中转页面
                // 'http://nc-fele-mips.elken.com:8016' // test
                // 'http://fele.ncshop.elken.com' // prod
                // location.href = 'https://fele.ncshop.elken.com/pay.html?RefNo=' + response.SN

                // 唤起支付页面
                // network.postData(`shop/i-pay88`, { Amount: response.ORDER_AMOUNT, RefNo: response.SN }).then(payment => {
                //   this.actionUrl = payment.transactionUrl
                //   this.form = payment.paymentFields
                //
                //   this.visible = true
                //   this.payLoading = false
                // }).catch(err => {
                //   this.$message({
                //     message: err,
                //     type: 'error'
                //   })
                //   this.submitButtonStat = false
                // })
              })
              // this.$confirm(`确定要购买商品吗？`, '提示', {
              //   confirmButtonText: '确定',
              //   cancelButtonText: '取消',
              //   type: 'warning',
              //   customClass: 'msgbox',
              // }).then(() => {
              //
              // }).catch(err => {
              //   this.$message({
              //     message: err,
              //     type: 'error'
              //   })
              //   this.submitButtonStat = false
              // })
          },
          getSumMoney(){
              let cash_plus_sum=[];
              let goodsId=[];
              let goodsNum=[];
              let choseNum = 0;
              this.goods.map((item,index)=>{
                  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;
              //增加运费03-12yuan
              let payAmount = tool.sum(cash_plus_sum);
              this.pointFreight = 0
              // if(payAmount>=300){
              //   this.pointFreight = this.freight = 0;
              // }else{
              //   this.pointFreight = this.freight = 15;
              // }

            this.pointsSum = this.cashSum = tool.formatPrice(tool.sum(cash_plus_sum) + this.freight) ;
          },
          getShowCart(){
              network.getData(`shop/show-cart?device=${this.flag}`)
              .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
                      }
                  })
                  // 如果没有默认收货地址,则第一个地址默认选中
                  if (this.all_address.length > 0 && this.addressId.length < 1) {
                      this.addressId = this.all_address[0].ID
                  }

                  for(let key in response.onlinePayList){
                    // 如果是海外商品,则只有在线支付
                    this.payList.push({type:key, name:response.onlinePayList[key].name})
                  }

                //默认设置为第一项付款方式
                  this.payType=this.payList[0].type;
              })
          },
          chosePayType(type){
            console.log(type)
          },
          choseAddress(addressId){
          },
          // 关闭支付回调
          handleClose () {
           let _this = this
           _this.$confirm('确认关闭?').then(() => {
             return network.postData('shop/delete-approach-order', {orderSn: this.form.RefNo}).then(() => {
               // 关闭支付模态框
               _this.visible = false
               // 关闭购物车页面,返回到订单列表页
               sessionStorage.setItem('order_goods', null)
               this.$router.push({path: `/shop/index`})
             })
           }).catch(() => {
             // 关闭支付模态框
             _this.visible = false
             // 关闭购物车页面,返回到订单列表页
             sessionStorage.setItem('order_goods', null)
             this.$router.push({path: `/shop/index`})
           })
          },
          // 关闭支付回调
          processClose () {
           // 关闭支付模态框
           this.visible = false
           // 关闭购物车页面,返回到订单列表页
           sessionStorage.removeItem('order_goods')
           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)
          },
          // 上传身份证
          uploadIDCard() {
            // window.location.href = this.IDCardWebsite
            window.open(this.IDCardWebsite, '_blank')
          },
          isPC() {
            let flag = window.navigator.userAgent.match(
              /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
            );
            return flag ? 'mobile' :'website'

          },
      }
  }
</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;
}
.payBtn {
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  text-align: center;
  padding: 10px 10px;
  font-size: 14px;
  border-radius: 4px;
  color: #fff;
  background-color: #409eff;
  border: 1px solid #DCDFE6;
  -webkit-appearance: none;
  box-sizing: border-box;
  margin-left: 150px;
}
@media (max-width: 720px) {
  .msgbox{
    width: 320px !important;
    margin-top: 15px;
  }
}
</style>
<style>
.myclass {
    width:260px;
}
</style>
