<template>
  <div class="submit-order">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img"></span>
          <span class="text">{{$t('submitOrder.submitOrder')}}</span>
        </div>
        <div class="steps">
          <div class="item">
            <div class="number">step 01.</div>
            <div class="text">{{$t('submitOrder.selectProductToBuy')}}</div>
          </div>
          <div class="item active">
            <div class="number">step 02.</div>
            <div class="text">{{$t('submitOrder.confirmOrderInformation')}}</div>
          </div>
          <div class="item">
            <div class="number">step 03.</div>
            <div class="text">{{$t('submitOrder.payToCompleteTheOrder')}}</div>
          </div>
        </div>
      </div>
      <div class="submit-con">
        <!-- 收货地址 (mold=1虚拟商品不展示收货地址) -->
        <div v-if="mold !== 1" class="submit-box submit-box-border">
          <div class="tit">
            <span class="text">{{$t('address.receivingAddress')}}</span>
            <!-- <span class="action">显示全部地址</span> -->
          </div>
          <div class="con address-box">
            <div
              :class="[
                'item',
                address.commonAddr ? 'default-address' : '',
                selectedAddrId == address.addrId ? 'active' : ''
              ]"
              v-for="address in addressList"
              :key="address.addrId"
              @click="changeAddress(address.addrId)"
            >
              <div class="name-phone">
                <span class="name">{{ address.receiver }}</span>
                <span class="phone">{{ address.mobile }}</span>
                <span
                  class="set-default"
                  v-if="!address.commonAddr"
                  @click="setDefaultAddr(address.addrId)"
                  >{{$t('address.setDefault')}}</span
                >
                <span class="default-tag" v-if="address.commonAddr">{{$t('address.default')}}</span>
              </div>
              <div class="address-detail">
                {{
                  address.province + address.city + address.area + address.addr
                }}
              </div>
              <div class="del-edit">
                <span
                  class="edit"
                  @click.stop="editAddr(address.addrId)"
                ></span>
                <span
                  class="del"
                  @click.stop="toggleDelAddr(true, address.addrId)"
                ></span>
              </div>
            </div>
            <div class="item add-address" @click="toggleAddrPop(true)" v-if="addressList.length<10">
              <div class="add-box">
                <div class="img">+</div>
                <div class="text">{{$t('address.addAddress')}}</div>
              </div>
            </div>
          </div>
          <div class="popup-mask" v-if="showDelAddr"></div>
          <div class="fix-transform-blur">
            <div class="popup-box" v-if="showDelAddr">
              <div class="tit" style="padding:10px;">
                <div class="text">{{$t('tips')}}</div>
                <div class="close" @click="toggleDelAddr(false)"></div>
              </div>
              <div class="con">
                <div class="tip">
                  <div class="tip-icon warning"></div>
                  <div class="tip-info">
                    <div class="result">{{$t('address.deleteShippingAddress')}}</div>
                    <div class="date">{{$t('address.deleteShippingTips')}}</div>
                    <div class="btns">
                      <a
                        href="javascript:void(0);"
                        @click="delAddr()"
                        class="btn-r"
                        >{{$t('delete')}}</a
                      >
                      <a
                        href="javascript:void(0);"
                        @click="toggleDelAddr(flase)"
                        class="btn-g"
                        >{{$t('cancel')}}</a
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 收货地址 -->
        <!-- 支付方式 -->
        <div class="submit-box submit-box-border">
          <div class="tit">
            <span class="text">{{$t('commonFoot.paymentMethod')}}</span>
          </div>
          <div class="con pay-way">
            <div class="item active">{{$t('submitOrder.payOnline')}}</div>
            <!-- <div class="item">货到付款</div>
            <div class="item">线下支付</div>-->
          </div>
        </div>
        <!-- 支付方式 -->
        <!-- 积分抵扣 -->
        <div
          class="submit-box integral-box submit-box-border"
          v-if="orderInfo.maxUsableScore > 0"
        >
          <div class="tit">
            <span class="text">{{$t('submitOrder.pointsCredit')}}</span>
          </div>
          <!-- 积分抵现 -->
          <div class="integral-item">
            <label class="text">
              <el-checkbox
                v-model="checked"
                :disabled="isProhibit"
                class="item-group"
                @change="useMemberPoints"
              ></el-checkbox
              >{{$t('submitOrder.usePointsForCrediting')}}
            </label>
            <div class="con"></div>
          </div>
          <!-- 积分抵现 -->
          <div class="integral-item integral-input-box" v-if="isScorePay == 1">
            {{$t('submitOrder.accountTotal')}} {{ accountCanUseScore }}{{$t('submitOrder.pointThisUse')}}
            <input
              type="number"
              v-model="userUseScore"
              class="text"
              @input="inputComplete()"
            />
              <!-- @input="inputComplete()" -->
            {{$t('submitOrder.pcsCredit')}}
            <span class="integral-money">
              ￥{{
                userUseScore
                  ? Number(orderInfo.totalScoreAmount).toFixed(2)
                  : '0.00'
              }}
            </span>
            <span>
              （{{$t('submitOrder.theOrderIsAvailableUpTo')}} {{ orderInfo.maxUsableScore }} {{$t('submitOrder.points')}}）
              <span v-if="shopUseScore > 100">{{($t('submitOrder.pleaseEnterAMultipleOf10'))}}</span>
            </span>
          </div>
          <div class="integral-item integral-text" v-if="isScorePay == 1">
            <span class="font-bold">
              {{$t('submitOrder.amountCredit')}}
              <span class="integral-money">
                ￥{{
                  userUseScore
                    ? Number(orderInfo.totalScoreAmount).toFixed(2)
                    : '0.00'
                }}
              </span>
            </span>
            <span class="text-item font-bright">
              {{$t('submitOrder.use')}}￥
              {{
                userUseScore
                  ? Number(orderInfo.totalScoreAmount).toFixed(2)
                  : '0.00'
              }}
            </span>
          </div>
        </div>
        <!-- 积分抵扣 -->
        <!-- 全部留言（虚拟商品） -->
        <!-- <div v-if="mold === 1 && virtualRemarkList.length" class="submit-box all-msg-row">
          <div class="tit">
            <span class="text">{{$t('submitOrder.allMessages')}}</span>
          </div>
          <div class="con">
            <div v-for="(item,index) in virtualRemarkList" :key="index" class="msg-item">
              <span v-if="item.isRequired" class="red-stress">*</span>
              <input
                v-model="item.value"
                class="msg-int-item"
                type="text"
                :placeholder="$t('submitOrder.pleaseEnter') + `${item.name}`"
                @blur="handleInputBlur(item.value, index)"
                 maxlength="20"
              >
            </div>
          </div>
        </div> -->
        <!-- 全部留言（虚拟商品）/ -->
        <!-- 配送方式 -->
        <div v-if="mold !== 1" class="submit-box submit-box-border">
          <div class="tit">
            <span class="text">{{$t('submitOrder.deliveryMethod')}}</span>
          </div>
          <div class="con delivery-way">
            <div class="item active">{{$t('submitOrder.courierDelivery')}}</div>
            <!-- <div class="item">到店自提</div> -->
            <!-- <div class="description">（该商品不支持自提）</div> -->
          </div>
        </div>
        <!-- /配送方式 -->
        <!-- 商品信息 -->
        <div class="submit-box goods-info" :class="{'last-box': !(platformCoupons && platformCoupons.canUseCoupons.length > 0) }">
          <div class="tit">
            <span class="text">{{$t('applyReturn.productInformation')}}</span>
          </div>
          <div class="goods-msg">
            <div class="msg-tab">
              <div class="img">&nbsp;</div>
              <div class="info">{{$t('products')}}</div>
              <div class="unit-price">{{$t('priceOne')}}</div>
              <div class="number">{{$t('quantity')}}</div>
              <div class="total">{{$t('subtotal')}}</div>
            </div>
            <div
              class="msg-con"
              :class="{'last-box': (platformCoupons && platformCoupons.canUseCoupons.length > 0) }"
              v-for="(shopCart, shopIndex) in shopCartOrders"
              :key="shopCart.shopId"
            >
              <!-- 店铺 -->
              <div class="shop-msg">
                <span class="shop-name">{{$t('index.shop')}}：</span>
                <nuxt-link
                  :to="'/shopIndex?sid=' + shopCart.shopId"
                  class="shop-name"
                  >{{ shopCart.shopName }}</nuxt-link
                >
                <span class="self" v-if="shopCart.shopId == 1">{{$t('prodDetail.selfEmployed')}}</span>
              </div>
              <!-- 店铺中的商品 -->
              <div
                class
                v-for="(shopCartItemDiscount,
                discIndex) in shopCart.shopCartItemDiscounts"
                :key="discIndex"
              >
                <div
                  class="goods-box"
                  v-for="(prod,
                  prodIndex) in shopCartItemDiscount.shopCartItems"
                  :key="prodIndex"
                >
                  <div class="prod-row">
                    <div class="img">
                      <nuxt-link :to="'/detail/' + prod.prodId" class="img-box">
                        <img v-if="prod.pic" :src="prod.pic" alt />
                        <img v-else src="~/assets/img/def.png" alt />
                      </nuxt-link>
                    </div>
                    <div class="info">
                      <nuxt-link :to="'/detail/' + prod.prodId" class="name">{{
                        prod.prodName
                      }}</nuxt-link>
                      <span class="sku">{{ prod.skuName }}</span>
                    </div>
                    <div class="unit-price">
                      ￥{{ parsePrice(prod.price)[0] }}.{{
                        parsePrice(prod.price)[1]
                      }}
                    </div>
                    <div class="number">×{{ prod.prodCount }}</div>
                    <div class="total">
                      ￥{{ parsePrice(prod.productTotalAmount)[0] }}.{{
                        parsePrice(prod.productTotalAmount)[1]
                      }}
                    </div>
                  </div>
                   <!-- 赠品展示 -->
                  <div v-if="prod.giveaway" class="gift-con">
                    <div v-for="(giveawayItem, giveawayIndex) in prod.giveaway.giveawayProds" :key="giveawayIndex" class="gift-item">
                      <nuxt-link class="gift-item-name" :to="'/detail/' + giveawayItem.prodId">
                        {{$t('cart.giveaways')}} {{giveawayItem.prodName}}
                        <span class="gift-item-sku-name">{{giveawayItem.skuName}} x{{giveawayItem.giveawayNum}}</span>
                        </nuxt-link>
                    </div>
                  </div>
                  <!-- 虚拟商品留言 start -->
                  <div
                    v-if="prod.virtualRemarkList && prod.virtualRemarkList.length"
                    class="virtual-goods-msg"
                  >
                    <div :class="['msg-tit',$t('language')=='en' ? 'msg-tit-en' : '']">
                      <span class="text">{{ $t('submitOrder.userMessage') }}：</span>
                    </div>
                    <div>
                      <div v-for="(msgItem,msgIndex) in prod.virtualRemarkList" :key="msgIndex" class="msg-item">
                        <span v-if="msgItem.isRequired" class="red-stress">*</span>
                        <input
                          v-model="msgItem.value"
                          class="msg-int-item"
                          type="text"
                          :placeholder="$t('submitOrder.pleaseEnter') + `${msgItem.name}`"
                          @blur="handleInputBlur(msgItem.value, msgIndex, prodIndex, discIndex, shopIndex)"
                          maxlength="20"
                        >
                      </div>
                    </div>
                  </div>
                  <!-- 虚拟商品留言 end -->
                </div>

              </div>

              <!-- 留言 -->
              <div class="remake-box">
                {{$t('orderDetails.orderRemarks')}}：
                <input
                  type="text"
                  class="text"
                  v-model="shopCart.remarks"
                  maxlength="100"
                  :data-shopinde="shopIndex"
                  :data-shopitem="shopCart"
                  :placeholder="$t('submitOrder.numberLength100')"
                />
                <!-- 发票 -->
                <div class="invoice-title">{{ $t('invoice.invoiceInfo') }}</div>
                <div v-if="shopCart.invoiceDataFrom" class="invoice-box">
                  <div v-if="shopCart.invoiceDataFrom.invoiceType === 1" class="invoice-box-item invoice-type">{{ $t('invoice.generalInvoice') }}</div>
                  <div v-if="shopCart.invoiceDataFrom.invoiceType === 2 || !shopCart.invoiceDataFrom" class="invoice-box-item invoice-type">{{ $t('invoice.noInvoice') }}</div>
                  <div v-if="shopCart.invoiceDataFrom.invoiceType === 1" class="invoice-box-item invoice-unit">{{ shopCart.invoiceDataFrom.headerName || $t('invoice.personal') }}</div>
                  <div v-if="shopCart.invoiceDataFrom.invoiceType === 1" class="invoice-box-item invoice-contents">{{ $t('invoice.productDetails') }}</div>
                  <div class="invoice-box-item invoice-operation" @click="showAddOrUpdateDialog(0,shopCart,shopCart.shopId)">{{ $t('invoice.update') }}</div>
                </div>
                <div v-else class="invoice-box">
                  <div class="invoice-box-item invoice-type">{{ $t('invoice.noInvoice') }}</div>
                  <div class="invoice-box-item invoice-operation" @click="showAddOrUpdateDialog(0,shopCart,shopCart.shopId)">{{ $t('invoice.update') }}</div>
                </div>
                <!-- 发票 -->
              </div>
              <!-- /留言 -->

              <!-- 优惠券选择框 -->
              <coupon-select
                :coupons="shopCart.shopCoupons"
                @checkCoupon="checkCoupon"
                v-if="
                  shopCart.shopCoupons &&
                    (shopCart.shopCoupons.canUseCoupons.length > 0 || shopCart.shopCoupons.unCanUseCoupons.length > 0)
                "
              ></coupon-select>
              <!-- 优惠券选择框 -->
            </div>
          </div>
        </div>
        <!-- 商品信息 -->
        <!-- 发票信息 -->
        <!-- <div class="submit-box">
          <div class="tit">
            <span class="text">发票信息</span>
          </div>
          <div class="con invoice-msg">
            <div class="invoice-text">电子普通发票</div>
            <div class="invoice-text">个人</div>
            <div class="invoice-text">商品明细</div>
            <a href=""
               class="invoice-btn">修改</a>
          </div>
        </div>-->
        <!-- /发票信息 -->
        <!-- 优惠券选择框 -->
        <div
          class="submit-box submit-box-border"
          v-if="platformCoupons && (platformCoupons.unCanUseCoupons.length > 0 || platformCoupons.canUseCoupons.length > 0)"
        >
          <div class="tit">
            <span class="text">{{$t('submitOrder.platformCoupons')}}</span>
          </div>
          <coupon-select
            :coupons="platformCoupons"
            :platform="true"
            :is-show-uncan="platformCoupons && platformCoupons.unCanUseCoupons.length > 0 && platformCoupons.canUseCoupons.length === 0 "
            @checkCoupon="checkCoupon"
          ></coupon-select>
        </div>
      </div>

      <!-- 金额明细 -->
      <div class="submit-bottom">
        <!-- 优惠明细 -->
        <div class="statistic-box">
          <!-- 商品总价 -->
          <div class="item">
            <div class="tit">
              <span class="number">{{ orderInfo.totalCount }}</span
              >{{$t('submitOrder.totalItems')}}：
            </div>
            <div class="con">
              ￥{{ parsePrice(orderInfo.total)[0] }}.{{
                parsePrice(orderInfo.total)[1]
              }}
            </div>
          </div>
          <!-- 应付运费 -->
          <div v-if="orderInfo.mold !== 1" class="item">
            <div class="tit">{{$t('submitOrder.freightPayable')}}：</div>
            <div class="con">
              <p>
              ￥{{ parsePrice(transfee)[0] }}.{{
                parsePrice(transfee)[1]
              }}
              </p>
            </div>
          </div>
          <!-- 平台开启会员包邮(运费减免) -->
          <div v-if="orderInfo.freeTransfee" class="item">
            <div class="tit">{{$t('submitOrder.memberPackage')}}：</div>
            <div class="con bright">
              <p>
              -￥{{ parsePrice(orderInfo.freeTransfee)[0] }}.{{
                parsePrice(orderInfo.freeTransfee)[1]
              }}
              </p>
            </div>
          </div>
          <!-- 积分抵扣 -->
          <div class="item" v-if="isScorePay == 1">
            <div class="tit red-font">{{$t('submitOrder.pointsCredit')}}：</div>
            <div class="con bright">
              -￥{{ parsePrice(orderInfo.totalScoreAmount)[0] }}.{{
                parsePrice(orderInfo.totalScoreAmount)[1]
              }}
            </div>
          </div>
          <!-- 平台优惠券 -->
          <div class="item" v-if="platformCoupons && platformCoupons.couponAmount">
            <div class="tit red-font">{{$t('submitOrder.platformCoupons')}}：</div>
            <div class="con bright">
              -￥{{ parsePrice(platformCoupons.couponAmount)[0] }}.{{
                parsePrice(platformCoupons.couponAmount)[1]
              }}
            </div>
          </div>
          <!-- 会员折扣 -->
          <div class="item" v-if="orderInfo.totalLevelAmount">
            <div class="tit">{{$t('submitOrder.memberDiscount')}}：</div>
            <div class="con bright">
              -￥{{ parsePrice(orderInfo.totalLevelAmount)[0] }}.{{
                parsePrice(orderInfo.totalLevelAmount)[1]
              }}
            </div>
          </div>
          <!-- 店铺优惠 -->
          <div class="item" v-if="orderInfo.orderShopReduce">
            <div class="tit red-font">{{$t('submitOrder.storeDiscount')}}：</div>
            <div class="con bright">
              -￥{{ parsePrice(orderInfo.orderShopReduce)[0] }}.{{
                parsePrice(orderInfo.orderShopReduce)[1]
              }}
            </div>
          </div>

        </div>
        <!-- 应付总额 -->
        <div class="detail-box">
          <div class="item">
            <div class="tit">{{$t('submitOrder.totalPayable')}}：</div>
            <div class="con">
              ￥{{ parsePrice(orderInfo.actualTotal)[0] }}.{{
                parsePrice(orderInfo.actualTotal)[1]
              }}
            </div>
          </div>
          <div class="item" v-if="currentAddr.addrId && mold !== 1">
            <span class="text">
              {{$t('submitOrder.sendTo')}}：{{
                currentAddr.province +
                  ' ' +
                  currentAddr.city +
                  ' ' +
                  currentAddr.area +
                  ' ' +
                  currentAddr.addr
              }}
            </span>
            <span class="text"
              >{{$t('submitOrder.consignee')}}：{{ currentAddr.receiver }} {{ currentAddr.mobile }}</span
            >
          </div>
        </div>
        <div class="btn-box">
          <a href="javascript:void(0)" class="btn" @click="submitOrder"
            >{{$t('submitOrder.submitOrder')}}</a
          >
        </div>
      </div>
      <!-- 金额明细 end -->
    </div>
    <!-- 地址弹窗 -->
    <AddressPop
      :editAddrId="editAddrId"
      v-if="showAddrPop"
      @getAddrList="getAddrList"
      @reloadOrderInfo="loadOrderInfo"
      @toggleAddrPop="toggleAddrPop"
    />
    <!-- /地址弹窗 -->
    <!-- 发票弹窗 -->
    <addOrEditInvoice
      v-if="showInvoiceAdd"
      ref="invoiceAddOrUpdate"
      @toggleAddrPop="refreshChange"
      @getInvoiceData="getInvoiceData"
      @hidePop="hideInvoicePop"
    />
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import bus from '~/plugins/bus'
import AddressPop from '~/components/add-or-edit-address'
import CouponSelect from '~/components/coupon-select'
import { _debounce, accuracyCount } from "~/plugins/util";   //防抖
import addOrEditInvoice from '~/components/add-or-edit-invoice'
export default {
  components: {
    AddressPop,
    CouponSelect,
    addOrEditInvoice
  },
  data () {
    return {
      addressList: [],
      selectedAddrId: 0,
      orderInfo: {},
      shopCartOrders: [],
      currentAddr: {}, // 当前选择的地址
      couponIds: [],
      couponUserIds: [],
      userChangeCoupon: 0, // 用户有没有对优惠券进行改变
      coupons: {
        totalLength: 0,
        canUseCoupons: [],
        unCanUseCoupons: []
      },
      totalScoreAmount: 0, // 积分抵扣金额
      totalUsableScore: 0, // 整个订单可以使用的积分数
      isScorePay: 0, // 用户是否选择积分抵现(0不使用 1使用 默认不使用)
      isChecked: true, // 是否选择会员积分抵现
      isProhibit: false, // （积分抵现）checkbox是否禁止
      showAddrPop: false, // 地址弹窗显隐

      // 地址数据
      editAddrId: 0, // 要修改的地址id
      showDelAddr: false,

      // 券
      showCanUse: true,
      orderEntry: 0, //订单入口 0购物车 1立即购买
      platformCoupons: {
        canUseCoupons: [],
        unCanUseCoupons: []
      },
      uuid: '',
      checked: false, //积分抵现选框
      userUseScore: '', // 使用多少积分抵扣
      accountCanUseScore: 0, // 账号可用积分
      maxUsableScore: 0,
      shopUseScore: '', // 积分抵扣比例

      // 发票弹窗
      showInvoiceAdd: false,
      invoiceId: '',
      invoiceDataFrom: '',

      // 应付运费
      transfee: 0,
      // 是否可提交订单
      canSubmitOrder: true,

      // 商品类型（1虚拟商品）
      mold: 0,
      // 全部留言列表
      // virtualRemarkList: [],
      allVirtualMsg: [],
      // 全部留言列表输入数据
      backupsVirtualRemarks: null
    }
  },
  mounted () {
    document.title = this.$t('submitOrder.submitOrder')
    //获取当前账号可用积分
    this.$axios.get('/p/score/scoreLevel/page?levelType=' + 0).then(({ data }) => {
      this.accountCanUseScore = data.score
    })
    if (this.$route.query.orderEntry) {
      this.orderEntry = this.$route.query.orderEntry
    }
    this.uuid = this.genUUID()
    this.getAddrList()
    this.loadOrderInfo(true)
  },
  beforeDestroy() {
    this.$store.commit('handleChangeErrMsg', '')
  },
  watch: {
    maxUsableScore (nv) {
      if (this.userUseScore > nv) {
        this.userUseScore = nv
      }
    }
  },
  methods: {
    showAddOrUpdateDialog(st, shopCart, shopId) {
      this.showInvoiceAdd = true
      const param = shopCart.invoiceDataFrom ? shopCart.invoiceDataFrom : ''
      this.$nextTick(() => {
        this.$refs.invoiceAddOrUpdate.init(st, param, '', shopId)
      })
    },
    /**
     * 刷新回调
     */
    refreshChange(visible) {
      this.showInvoiceAdd = visible
      // this.getUserAddr()
    },
    /**
     * 发票信息
     */
    getInvoiceData(invoiceDataFrom) {
      if(invoiceDataFrom.headerType === 2) {
        delete invoiceDataFrom.invoiceTaxNumber
      }
      this.shopCartOrders.forEach((item) => {
        if (item.shopId === invoiceDataFrom.shopId) {
          item.invoiceDataFrom = invoiceDataFrom
        }
      })
      this.showInvoiceAdd = false
    },
    hideInvoicePop(visible) {
      this.showInvoiceAdd = visible
    },
    /**
     * 积分输入
     */
    inputComplete: _debounce(function () {
      var userUseScore = this.userUseScore;
      userUseScore = userUseScore.replace(/[^\d]/g, ''); // 清除“数字”和“.”以外的字符
      if (userUseScore.indexOf('.') < 0 && userUseScore != '') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        userUseScore = parseInt(userUseScore);
      }
      this.userUseScore = userUseScore;
      if (this.shopUseScore > 100) {
        this.userUseScore = this.userUseScore - this.userUseScore % 10
      }
      if (this.userUseScore > this.maxUsableScore) {
        this.userUseScore = this.maxUsableScore
      }
      this.loadOrderInfo()
    },500),

    /**
     * 获取地址列表
     */
    getAddrList () {
      this.$axios.get('/p/address/list').then(({ data }) => {
        this.addressList = data
      })
    },

    /**
     * 选择地址
     */
    changeAddress (addrId) {
      this.addressList.forEach(element => {
        if (element.addrId == addrId) {
          this.currentAddr = element
        }
      })
      this.selectedAddrId = addrId
      this.loadOrderInfo()
    },

    /**
     * 改变优惠券选择
     */
    checkCoupon () {
      var couponIds = []
      var couponUserIds = []
      var shopCartOrders = this.shopCartOrders
      shopCartOrders.forEach(shopCart => {
        if (shopCart.shopCoupons) {
          shopCart.shopCoupons.canUseCoupons.forEach(coupon => {
            if (coupon.choose) {
              couponIds.push(coupon.couponId) // couponUserId
              couponUserIds.push(coupon.couponUserId)
            }
          })
        }
      })
      if (this.platformCoupons && this.platformCoupons.canUseCoupons.length) {
        this.platformCoupons.canUseCoupons.forEach(coupon => {
          if (coupon.choose) {
            couponIds.push(coupon.couponId)
            couponUserIds.push(coupon.couponUserId)
          }
        })
      }
      this.couponIds = couponIds
      this.couponUserIds = couponUserIds
      this.userChangeCoupon = 1
      this.loadOrderInfo()
    },

    /**
     * 设置为默认地址
     */
    setDefaultAddr (addrId) {
      this.$axios.put('/p/address/defaultAddr/' + addrId).then(({ data }) => {
        this.$message({
          message: data,
          type: 'success',
          duration: 1000
        })
        this.getAddrList()
      })
    },
    /**
     * 显示/隐藏确认删除弹窗
     */
    toggleDelAddr (sts, addrId) {
      this.showDelAddr = sts
      this.editAddrId = addrId
    },
    /**
     * 显示/隐藏地址弹窗
     */
    toggleAddrPop (sts) {
      if (Cookie.get('token')) {
        this.showAddrPop = sts
        this.editAddrId = 0
      } else {
        bus.$emit("showLogin", true)
        this.showAddrPop = false
      }
    },

    /**
     * 修改地址 (弹窗传地址id)
     */
    editAddr (addrId) {
      if (Cookie.get('token')) {
        this.showAddrPop = true
        this.editAddrId = addrId
      } else {
        bus.$emit("showLogin", true)
        this.showAddrPop = false
      }
    },
    /**
     * 删除地址
     */
    delAddr () {
      let reload = false
      if (this.selectedAddrId == this.editAddrId) {
        this.selectedAddrId = 0
        reload = true
      }
      this.$axios
        .delete('/p/address/deleteAddr/' + this.editAddrId)
        .then(({ data }) => {
          this.$message({
            message: data,
            type: 'success',
            duration: 1000
          })
          this.toggleDelAddr(false)
          this.getAddrList()
          if (reload) {
            this.loadOrderInfo()
          }
        })
    },
    /**
     * 价格处理
     */
    parsePrice: value => {
      var val = Number(value)
      if (!val) {
        val = 0
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split('.')
    },

    /**
     * 积分抵现选择
     */
    useMemberPoints() {
      this.userUseScore = ''
      var checked = !this.checked
      this.checked = !checked
      if (this.orderInfo.maxUsableScore > 0) {
        //maxUsableScore 整个订单可以使用的积分数
        this.isProhibit = false //（积分抵现）checkbox是否禁止
        // 如果积分可抵扣
        if (this.checked) {
          this.isScorePay = 1 //用户是否选择积分抵现(0不使用 1使用 默认不使用)
        } else if (!this.checked) {
          this.isScorePay = 0 //用户是否选择积分抵现(0不使用 1使用 默认不使用)
        }
        setTimeout(() => {
          this.loadOrderInfo() //加载订单数据
        },800)
      } else if (this.orderInfo.maxUsableScore <= 0) {
        this.isProhibit = true //（积分抵现）checkbox是否禁止
      }
    },

    /**
     * 加载订单数据
     */
    loadOrderInfo (isFirst) {
      // const loading = this.$loading({
      //   lock: true,
      //   text: '加载中...',
      //   background: 'rgba(255, 255, 255, 0.8)
      // });
      var orderParam = {
        addrId: this.selectedAddrId,
        orderItem:
          this.orderEntry == 1
            ? JSON.parse(sessionStorage.getItem('orderItem'))
            : undefined,
        basketIds:
          this.orderEntry == 0
            ? JSON.parse(sessionStorage.getItem('basketIds'))
            : undefined,
        couponIds: this.couponIds,
        couponUserIds: this.couponUserIds,
        isScorePay: this.isScorePay,
        userChangeCoupon: this.userChangeCoupon,
        userUseScore: Number(this.userUseScore),
        uuid: this.uuid
      }
      this.$axios
        .post('/p/order/confirm', orderParam)
        .then(({ data }) => {
          var remarksList = []
          if (!isFirst) {
            this.shopCartOrders.forEach(el => {
              remarksList.push(el.remarks)
            })
          }
          var couponIds = []
          this.orderInfo = data
          this.maxUsableScore = data.maxUsableScore  // 订单最大可用积分数量
          if (data.userAddr) {
            this.currentAddr = data.userAddr
            this.selectedAddrId = data.userAddr.addrId
          }
          this.platformCoupons = this.splitCouponAndPushCouponIds(
            data.coupons,
            couponIds
          ) //平台优惠券
          var shopCartOrders = data.shopCartOrders
          shopCartOrders.forEach((shopCart, index) => {
            if (isFirst) {
              shopCart.remarks = ''
            } else {
              shopCart.remarks = remarksList[index]
            }
            shopCart.shopCoupons = this.splitCouponAndPushCouponIds(
              shopCart.coupons,
              couponIds
            )
          })
          if(this.shopCartOrders.length === 0) {
            this.shopCartOrders = shopCartOrders
          }
          
          this.couponIds = couponIds
          this.shopUseScore = data.shopUseScore // 积分抵扣比例
          // 应付运费 = 商品总运费 - 会员包邮减免运费
          if (data.totalTransfee && data.freeTransfee) {
            this.transfee = accuracyCount(data.totalTransfee, data.freeTransfee, 1)
          } else {
            this.transfee = data.totalTransfee
          }

          // 商品类型（4虚拟商品）
          this.mold = data.mold || 0
          // 留言列表
          // if (this.backupsVirtualRemarks && this.backupsVirtualRemarks.length) {
          //   this.virtualRemarkList = this.backupsVirtualRemarks
          // } else {
          //   this.virtualRemarkList = data.virtualRemarkList
          // }
          this.handleAllVirtualMsg()
          
        })
        .catch((error) => {
          this.canSubmitOrder = false
          this.$router.push({path:'/cart'})
        })
    },
    /**
     * 分割优惠券成
     * 1. canUseCoupons 可使用优惠券列表
     * 2. unCanUseCoupons 不可使用优惠券列表
     * 3. couponAmount 选中的优惠券可优惠金额
     * 4. 将选中的优惠券ids保存起来
     * @param {*} coupons 优惠券列表
     * @param {*} couponIds 选中的优惠券id
     */
    splitCouponAndPushCouponIds (coupons, couponIds) {
      if (!coupons || !coupons.length) {
        return
      }
      let canUseCoupons = []
      let unCanUseCoupons = []
      let couponAmount = 0
      coupons.forEach(coupon => {
        if (coupon.canUse) {
          canUseCoupons.push(coupon)
        } else {
          unCanUseCoupons.push(coupon)
        }
        if (coupon.choose) {
          couponIds.push(coupon.couponId)
          couponAmount = coupon.reduceAmount
        }
      })
      return {
        canUseLength: canUseCoupons.length,
        couponAmount: couponAmount,
        canUseCoupons: canUseCoupons,
        unCanUseCoupons: unCanUseCoupons
      }
    },

    /**
     * 虚拟商品留言
     */
    handleAllVirtualMsg() {
      this.allVirtualMsg = this.getValueOfArr(this.shopCartOrders)
    },
    getValueOfArr(data) {
      const layers = ['shopCartItemDiscounts', 'shopCartItems', 'virtualRemarkList']
      const deepGet = (item, index) => {
        return item.map(la => {
          const children = la[layers[index]];
          if (Array.isArray(children)) {
            if (layers.length === index + 1) {
              return children.map((ch, idx) => {
                ch.id = la.prodId + '_' + idx
                return ch
              })
            }
            return deepGet(children, index + 1)
          }
          return []
        }).flat(Infinity)
      }
      return deepGet(data, 0)
    },

    /**
     * 虚拟商品留言输入框失焦
     */
    handleInputBlur (value, msgIndex, prodIndex, discIndex, shopIndex) {
      if (!value) {
        return
      }
      if (!value.trim()) {
        this.shopCartOrders[shopIndex].shopCartItemDiscounts[discIndex].shopCartItems[prodIndex].virtualRemarkList[msgIndex].value = value.trim()
        // this.virtualRemarkList[msgIndex].value = value.trim()
        return
      }
      const currentItem = this.shopCartOrders[shopIndex].shopCartItemDiscounts[discIndex].shopCartItems[prodIndex].virtualRemarkList[msgIndex]
      this.allVirtualMsg.forEach(msgItem => {
        if (currentItem.id === msgItem.id) {
          msgItem.value = value
        }
      })
      // this.backupsVirtualRemarks = this.virtualRemarkList
    },

    /**
     * 提交订单
     */
    submitOrder () {
      var shopCartOrders = this.shopCartOrders
      var orderShopParam = []
      var reg = /^\s+$/g
      shopCartOrders.forEach(shopCart => {
        orderShopParam.push({
          remarks: shopCart.remarks,
          shopId: shopCart.shopId
        })
      })
      let remarksFlag = orderShopParam.some(item=>{
        return reg.test(item.remarks)
      })

      if (remarksFlag) {
        this.$message({
          message: this.$t('inputAllSpace'),
          type: 'error',
          duration: 1000
        })
        return;
      }
      let orderInvoiceList = [] // invoiceDataFrom
      shopCartOrders.forEach((item) => {
        if (item.invoiceDataFrom && item.invoiceDataFrom.invoiceType === 1) {
          orderInvoiceList.push(item.invoiceDataFrom)
        }
      })
      if (orderInvoiceList.length === 0) {
        orderInvoiceList = null
      }
      if (this.mold !== 1 && !this.addressList.length) {
        if (Cookie.get('token')) {
          this.$message({
            message: this.$t('submitOrder.pleaseAddTheAddressFirst'),
            type: 'warning',
            duration: 1000
          })
          this.showAddrPop = true
        } else {
          bus.$emit("showLogin", true)
          this.showAddrPop = false
        }
        return
      }
      // if (!this.canSubmitOrder) {
      //   this.$message.warning(this.$store.state.errMsg)
      //   return
      // }
      if (this.mold !== 1 && this.selectedAddrId == 0) {
        this.$message({
          message: this.$t('submitOrder.pleaseSelectTheAddressFirst'),
          type: 'warning',
          duration: 1000
        })
        document.body.scrollTop = document.documentElement.scrollTop = 0
        return
      }
      if (this.checked && !this.userUseScore) {
        this.$message({
          message: this.$t('submitOrder.pleaseEnterTheNumberOfPoints'),
          type: 'warning',
          duration: 1000
        })
        return
      }
      // 全部留言必填项空校验(虚拟商品)
      // if (
      //   this.mold === 1 &&
      //   this.virtualRemarkList.length &&
      //   this.virtualRemarkList.find(el => el.isRequired && !el.value)
      // ) {
      //   this.$message({
      //     message: this.$t('submitOrder.messageCannotBeEmpty'),
      //     type: 'warning',
      //     duration: 1000
      //   })
      //   return
      // }
      if (this.allVirtualMsg.length && this.allVirtualMsg.find(el => el.isRequired && !el.value)) {
        this.$message({
          message: this.$t('submitOrder.messageCannotBeEmpty'),
          type: 'warning',
          duration: 2000
        })
        return
      }
      this.allVirtualMsg.forEach(el => {
        el.id = undefined
      })
      this.$axios
        .post('/p/order/submit', {
          orderShopParam: orderShopParam,
          uuid: this.uuid,
          orderInvoiceList: orderInvoiceList,
          virtualRemarkList: this.allVirtualMsg
        })
        .then(({ data }) => {
          console.log(data)
          if (data.duplicateError === 1) {
            // this.canSubmitOrder = false
            this.$store.commit('handleChangeErrMsg', this.$t('submitOrder.duplicateErrorTips'))
            return this.$message.warning(this.$t('submitOrder.duplicateErrorTips'))
          }
          sessionStorage.setItem('pay_total', this.orderInfo.actualTotal)
          sessionStorage.setItem('pay_orderNumber', data.orderNumbers)
          sessionStorage.setItem('pay_mold', this.mold)
          this.$router.push({
            path: '/payment'
          })
          this.getCartCount()
        })
        .catch(() => {
          // this.canSubmitOrder = false
        })

    },

    /**
     * 获取购物车商品总数
     */
    getCartCount () {
      this.$axios.get('/p/shopCart/prodCount').then(({ data }) => {
        this.$store.commit('cartNumber/changeCartNumber', data)
      })
    },

    /**
     * 生成uuid
     */
    genUUID () {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = '-'

      var uuid = s.join('')
      return uuid
    }
  }
}
</script>

<style scoped src="~/assets/css/submit-order.css"></style>
<style scoped>
.fix-transform-blur {
  z-index: 10000;
  position: fixed;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -40%);
}

.submit-order .statistic-box .item .tit {
  display: flex;
  justify-content: flex-end;
}

.submit-order .statistic-box .item .tit .text {
  margin-left: 5px;
}
</style>
