<template>
  <div class="mobile-content mobile-content-long mobile-pay">
    <!--<div class="pay-head" @click="openAddrModal">
      <template v-if="selectedAddress && selectedAddress.name">
        <p class="info">
          {{selectedAddress.name}}&nbsp;&nbsp;&nbsp;{{selectedAddress.tel}}
        </p>
        <div class="addr">
          <img src="/images/mobile/center/user/addr-flag.png" alt="">
          <span>{{selectedAddress.area + selectedAddress.detailAddress}}</span>
        </div>
        <i class="iconfont icon-xiangyou fr"></i>
      </template>
      <template v-else>
        <div class="no-addr">暂无收货地址信息</div>
      </template>
    </div>-->
    <ul class="pay-store-list">
      <li class="ps-item" v-for="item in orderData">
        <p class="ps-store-name">
          <nuxt-link tag="span" :to="`/mobile/shop/${item.storeid}`" class="inline-block text-ellipse seller-name"><span>卖&nbsp;&nbsp;家：</span>{{item.storeName}}&nbsp;<i class="iconfont icon-arrow-right"></i></nuxt-link>
          <a class="com-mobile-link" @click.stop="linkSaler(item)"><i class="iconfont icon-kefu1"></i>联系卖家</a>
        </p>
        <div class="ps-goods-info"  @click="showDetailList(item.goods)">
          <ul class="ps-goods-list">
            <li class="inline-block" v-for="goods in (item.$expand ? item.goods : item.goods.slice(0, 3))">
              <div class="clearfix" style="padding: .31rem .25rem;">
                <div class="fl">
                  <div class="ps-goods-item text-ellipse"><span>品牌：</span>{{goods.brName || '-'}}</div>
                  <div class="ps-goods-item text-ellipse"><span>物料名称(类目)：</span>{{goods.kiName || '-'}}</div>
                  <div class="ps-goods-item text-ellipse"><span>型号：</span>{{goods.cmpCode || '-'}}</div>
                  <div class="ps-goods-item text-ellipse"><span>规格：</span>{{goods.spec || '-'}}</div>
                </div>
                <div class="fr">
                  <div class="ps-goods-item text-ellipse"><span>交期(天)：</span>{{goods.goodsHistory.b2cMinDelivery + '-' +  goods.goodsHistory.b2cMaxDelivery}}</div>
                  <div class="ps-goods-item text-ellipse"><span>单价：</span>{{baseUtils.getPriceByLevel(goods.goods.prices, goods.goods.purchaseNumber, goods.currencyName)}}</div>
                  <div class="ps-goods-item text-ellipse"><span>起拍：</span>{{goods.minBuyQty}}</div>
                  <div class="ps-goods-item"><span>数量(PCS)：</span>
                    <span class="input-line inline-block">
                    <span class="inline-block" @click="setGoods('sub', goods)" :class="{disab: !goods.goods.canSub}">-</span>
                    <input type="number" v-model="goods.goods.purchaseNumber" @blur="setGoods('set', goods)">
                    <span class="inline-block" @click="setGoods('add', goods)" :class="{disab: !goods.goods.canAdd}">+</span>
                  </span>
                  </div>
                </div>
              </div>
              <div class="single-count text-ellipse"><span class="pay-price-title inline-block">小计：</span><span class="ol-price"><span>{{goods.currencyName | currencyFilter}}</span>{{goods.goods.currentPrice | priceFilter}}</span></div>
            </li>
          </ul>
          <div class="show-more-psgoods" v-if="item.goods.length > 3" @click="item.$expand = !item.$expand">
            {{item.$expand ? '收起' : '查看更多'}}
            <i v-show="!item.$expand" class="iconfont icon-arrow-down"></i>
            <i v-show="item.$expand" class="iconfont icon-arrow-up"></i>
          </div>
        </div>
       <!-- <div class="ps-operate-line" @click="showRuleSet(item.storeid)">
          <span class="title">配送方式</span>
          <div class="fr">
            <div class="inline-block">
              <span v-if="fareRule[item.storeid] && fareRule[item.storeid][0]">{{fareRule[item.storeid][0].method | deliveryRuleFilter}}</span>
              <span v-if="fareRule[item.storeid] && fareRule[item.storeid][0]">{{fareRule[item.storeid][0].ruleName}}</span>
              <span v-if="!(fareRule[item.storeid] && fareRule[item.storeid][0])" class="red">当前地址不支持配送，请与卖家协商处理</span>
            </div>
            <i class="iconfont icon-xiangyou" v-if="fareRule[item.storeid] && fareRule[item.storeid][0]"></i>
          </div>
        </div>-->
     <!--   <div class="ps-operate-line">
          <span class="title">物流选择</span>
          <div class="fr">
            <div class="delivery-select active inline-block">最省钱</div>
            <div class="delivery-select inline-block">最快</div>
          </div>
        </div>-->
        <!--<div class="ps-operate-line ps-operate-takeself" v-if="checkShowTakeSelf(item)" @click="showTakeSelfSet(item.storeid)">
          <span class="title">自提点</span>
          <div class="fr">
            <div class="inline-block">
              <template v-if="takeSelfData[item.storeid] && takeSelfData[item.storeid]">
                <span>{{takeSelfData[item.storeid][0].takename}}</span>
                <span>地址：{{takeSelfData[item.storeid][0].area + takeSelfData[item.storeid][0].detailAddress}}</span>
                <span>营业时间：{{takeSelfData[item.storeid][0].businesstime}}</span>
              </template>
              <template v-else>暂无自提点信息</template>
            </div>
          </div>
        </div>
        <div class="ps-operate-line">
          <span class="title">订单备注</span>
          <input type="text" v-model="item.remark" placeholder="选填：填写内容需和卖家协商确认">
        </div>-->
        <div class="ps-operate-line ps-fare">
          <div class="text-ellipse">
            <span class="pay-price-title inline-block">运费：</span><span class="ol-price" v-if="item.fare"><span v-if="item.fare.fare > 0">{{item.fare.currencyName | currencyFilter}}</span>{{item.fare.fare}}</span>
            <span class="ol-price" v-else>0</span>
          </div>
          <div class="text-ellipse">
             <span class="pay-price-title inline-block">手续费：</span><span class="ol-price"><span>{{payData.currency | currencyFilter}}</span>0.00</span>
            <!--（<span class="ol-price fare"><span>{{payData.currency | currencyFilter}}</span>{{getPoundage(item)}}</span>）-->
            <span class="inline-block tag" @click="showRemindStr = true">减免</span>
            <i class="fa fa-exclamation-circle"></i>
          </div>
        </div>
        <div class="ps-operate-line ps-price">
          <span class="pay-price-title inline-block">合计：</span>
          <span class="ol-price"><span>{{payData.currency | currencyFilter}}</span>
          {{(item.goodsFarePrice || 0) | priceFilter}}</span>
        </div>
      </li>
    </ul>
    <div class="ps-operate-line ps-address" @click="openAddrModal">
      <div class="inline-block">
        <template v-if="selectedAddress && selectedAddress.name">
          <p class="addr">
            <span class="addr-title inline-block">收货地址：</span>
            <span class="inline-block area">{{selectedAddress.area + selectedAddress.detailAddress}}</span>
          </p>
          <p class="text-ellipse info">
            <span class="info-name">收货人：</span>{{selectedAddress.name}}
            <span class="info-phone">电话：</span>{{selectedAddress.tel}}
          </p>
        </template>
        <template v-else>
          <p class="no-addr">请维护收货地址信息</p>
        </template>
      </div>
      <i class="iconfont icon-xiangyou inline-block"></i>
    </div>
    <div class="ps-operate-line pay-invoice" @click="openInvoiceModal">
      <span class="title">发票信息：</span>
      <div class="fr">
        <p class="inline-block text-ellipse">
          <template v-if="selectedInvoice">
            <span class="inv-head inline-block text-ellipse">{{selectedInvoice.head}}</span>
            <span class="inv-type inline-block">({{selectedInvoice.kind === 1205 ? '专用发票' : '普通发票'}})</span>
          </template>
          <template v-else>
            <span>暂不开具发票</span>
          </template>
        </p>
        <i class="iconfont icon-xiangyou"></i>
      </div>
    </div>
    <div class="ps-operate-line pay-operate">
      <span class="title">支付方式</span>
      <div class="fr">
        <span>线下支付</span>
        <!--<i class="iconfont icon-xiangyou"></i>-->
      </div>
    </div>
    <div class="buy-wrap">
      <div class="fr">
        <span class="title">总计：</span><span class="ol-price price inline-block text-ellipse"><span>{{payData.currency | currencyFilter}}</span>
        {{allPriceNew | priceFilter}}</span>
        <button class="buy-btn" @click="confirmOrder">提交订单</button>
      </div>
    </div>

    <!-- 联系卖家弹框start -->
    <link-user :infoObj="currentStoreInfo"
               :showLink="showLink"
               @closeAction="showLink = false">

    </link-user>
    <!-- 联系卖家弹框end -->

    <!-- 产品清单弹框start -->
    <!--<modal-wrapper :showModal="showModal"
                   :title="'产品清单'"
                   @closeAction="showModal = false">
      <ul class="cGoods-list">
        <li v-for="cGoods in currentGoods" class="clearfix">
          <div class="fl">
            <div class="cg-param-line text-ellipse">
              <span>品牌：</span>{{cGoods.brName}}
            </div>
            <div class="cg-param-line text-ellipse">
              <span>物料名称(类目)：</span>{{cGoods.kiName}}
            </div>
            <div class="cg-param-line text-ellipse">
              <span>型号：</span>{{cGoods.cmpCode}}
            </div>
            <div class="cg-param-line text-ellipse">
              <span>规格：</span>{{cGoods.spec}}
            </div>
          </div>
          <div class="fr">
            <p class="ol-price text-ellipse"><span>{{cGoods.currencyName | currencyFilter}}</span>{{cGoods.taxUnitprice}}</p>
            <p class="count text-ellipse">x&nbsp;{{cGoods.number}}</p>
          </div>
        </li>
      </ul>
    </modal-wrapper>-->
    <!-- 产品清单弹框end -->

    <!-- 选择配送方式弹框start -->
    <bottom-modal-wrapper :showModal="showDeliveryModal"
                          :title="'选择配送方式'"
                          @closeAction="onDeliveryModalClose">
      <ul class="delivery-rule-list">
        <li v-for="cdr in fareRule[currentDeliveryStoreId]" @click="checkDelivery(cdr)">
          <label class="bottom-modal-check mobile-cart-check" :class="{'active': cdr.$checked}">
            <input type="checkbox">
            <span>{{cdr.method | deliveryRuleFilter}}</span>
          </label>
          <div class="fr" v-if="cdr.fare && cdr.fare > 0">运费：<span class="ol-price"><span>{{cdr.currencyName | currencyFilter}}</span>{{cdr.fare || 0}}</span></div>
        </li>
      </ul>
    </bottom-modal-wrapper>
    <!-- 选择配送方式弹框end -->

    <!-- 选择发票弹框start -->
    <modal-wrapper :showModal="showInvoiceModal"
                   :title="'选择发票'"
                   @closeAction="showInvoiceModal = false">
      <ul class="invoice-list">
        <li @click="setInvoiceCheck(-1)">
          <label class="bottom-modal-check mobile-cart-check" :class="{active: selectedInvoiceIndex === -1}">
            <input type="checkbox">
          </label>
          <span class="inv-head">暂不开票</span>
        </li>
        <li v-for="(inv, index) in invoiceData" @click="setInvoiceCheck(index)">
          <label class="bottom-modal-check mobile-cart-check" :class="{'active': selectedInvoiceIndex === index}">
            <input type="checkbox">
          </label>
          <span class="inv-head inline-block text-ellipse">{{inv.head}}</span>
          <img class="inv-type" :src="`/images/mobile/center/user/${inv.kind === 1205 ? 'invoice-spec' : 'invoice-nor'}.png`" alt="">
          <div class="content-line" v-if="inv.kind === 1205">
            <div class="title inline-block">单位地址：</div>
            <div class="content inline-block">{{inv.companyAddress || '-'}}</div>
          </div>
          <div class="content-line" v-if="inv.kind === 1205">
            <div class="title inline-block">单位电话：</div>
            <div class="content inline-block">{{inv.companyPhone || '-'}}</div>
          </div>
          <div class="content-line" v-if="inv.kind === 1205">
            <div class="title inline-block">税务登记号：</div>
            <div class="content inline-block">{{inv.companyTaxNumber || '-'}}</div>
          </div>
          <div class="content-line" v-if="inv.kind === 1205">
            <div class="title inline-block">开户银行：</div>
            <div class="content inline-block">{{inv.bankName || '-'}}</div>
          </div>
          <div class="content-line" v-if="inv.kind === 1205">
            <div class="title inline-block">开户银行账户：</div>
            <div class="content inline-block">{{inv.bankAccount || '-'}}</div>
          </div>
          <div class="content-line">
            <div class="title inline-block">收票人：</div>
            <div class="content inline-block">{{inv.name || '-'}}</div>
          </div>
          <div class="content-line">
            <div class="title inline-block">联系电话：</div>
            <div class="content inline-block">{{inv.telephone || '-'}}</div>
          </div>
          <div class="content-line">
            <div class="title inline-block">详细地址：</div>
            <div class="content inline-block">{{inv.area + inv.detailAddress}}</div>
          </div>
        </li>
      </ul>
    </modal-wrapper>
    <!-- 选择发票弹框end -->

    <!-- 选择地址弹框start -->
   <!-- <modal-wrapper :showModal="showAddrModal"
                   :title="'收货地址'"
                   @closeAction="showAddrModal = false">
      <template v-if="!editAddr">
        <div class="addr-list-wrap">
          <ul class="addr-list">
            <li v-for="(addr, index) in addressData" :class="{active: selectedAddressIndex === index}" @click="setAddressCheck(index)">
              <div class="info-wrap">
                <div class="info-line">
                  <label class="mobile-cart-check" :class="{active: selectedAddressIndex === index}">
                    <input type="checkbox">
                  </label>
                  <span class="name inline-block text-ellipse">{{addr.name}}</span>
                  <span class="tel inline-block text-ellipse">{{addr.tel}}</span>
                  <i class="inline-block" v-if="addr.num === 1">默认地址</i>
                </div>
                <p>{{addr.area + addr.detailAddress}}</p>
              </div>
              <div class="edit-addr-area">
                <a class="inline-block addr-btn" @click.stop="addAddress(addr)"><i class="iconfont icon-xinzeng"></i>编辑</a>
                <a class="inline-block addr-btn" @click.stop="deleteAddress(addr)"><i class="iconfont icon-lajitong"></i>删除</a>
              </div>
            </li>
          </ul>
          <button class="add-addr-btn" @click="addAddress()"><i class="iconfont icon-add"></i>添加新地址</button>
        </div>
      </template>
      <address-edit v-else="editAddr" :inFix="true" :data="currentAddress" :isPersonal="true" :isSend="false" @isEditEvent="editClick"></address-edit>
    </modal-wrapper>-->
    <div class="mobile-modal addr-modal" v-if="showAddrModal" @click="showAddrModal = false">
      <div class="mobile-modal-box addr-modal-wrapper" @click="stopPropagation($event)">
        <div class="mobile-modal-header">收货地址<i @click="showAddrModal = false" class="icon-guanbi iconfont"></i></div>
        <div style="height: 100%;overflow-y: auto;background: #fff;padding-bottom: .3rem;">
          <template v-if="!editAddr">
            <div class="addr-list-wrap">
              <ul class="addr-list">
                <li v-for="(addr, index) in addressData" :class="{active: selectedAddressIndex === index}" @click="setAddressCheck(index)">
                  <div class="info-wrap">
                    <div class="info-line">
                      <label class="mobile-cart-check" :class="{active: selectedAddressIndex === index}">
                        <input type="checkbox">
                      </label>
                      <span class="name inline-block text-ellipse">{{addr.name}}</span>
                      <span class="tel inline-block text-ellipse">{{addr.tel}}</span>
                      <i class="inline-block" v-if="addr.num === 1">默认地址</i>
                    </div>
                    <p>{{addr.area + addr.detailAddress}}</p>
                  </div>
                  <div class="edit-addr-area">
                    <a class="inline-block addr-btn" @click.stop="addAddress(addr)"><i class="iconfont icon-xinzeng"></i>编辑</a>
                    <a class="inline-block addr-btn" @click.stop="deleteAddress(addr)"><i class="iconfont icon-lajitong"></i>删除</a>
                  </div>
                </li>
              </ul>
              <button class="add-addr-btn" @click="addAddress()"><i class="iconfont icon-add"></i>添加新地址</button>
            </div>
          </template>
          <address-edit v-else="editAddr" :inFix="false" :data="currentAddress" :isPersonal="true" :isSend="false" @isEditEvent="editClick"></address-edit>
        </div>
      </div>
    </div>
   <!-- <div v-if="showAddrModal" class="mobile-hover-pager">
      <template v-if="!editAddr">
        <div class="addr-list-wrap">
          <ul class="addr-list">
            <li v-for="(addr, index) in addressData" :class="{active: selectedAddressIndex === index}" @click="setAddressCheck(index)">
              <div class="info-wrap">
                <div class="info-line">
                  <label class="mobile-cart-check" :class="{active: selectedAddressIndex === index}">
                    <input type="checkbox">
                  </label>
                  <span class="name inline-block text-ellipse">{{addr.name}}</span>
                  <span class="tel inline-block text-ellipse">{{addr.tel}}</span>
                  <i class="inline-block" v-if="addr.num === 1">默认地址</i>
                </div>
                <p>{{addr.area + addr.detailAddress}}</p>
              </div>
              <div class="edit-addr-area">
                <a class="inline-block addr-btn" @click.stop="addAddress(addr)"><i class="iconfont icon-xinzeng"></i>编辑</a>
                <a class="inline-block addr-btn" @click.stop="deleteAddress(addr)"><i class="iconfont icon-lajitong"></i>删除</a>
              </div>
            </li>
          </ul>
          <button class="add-addr-btn" @click="addAddress()"><i class="iconfont icon-add"></i>添加新地址</button>
        </div>
      </template>
      <address-edit v-else="editAddr" :inFix="false" :data="currentAddress" :isPersonal="true" :isSend="false" @isEditEvent="editClick"></address-edit>
    </div>-->
    <!-- 选择地址弹框end -->

    <!-- 选择自提点弹框start -->
    <modal-wrapper :showModal="showTakeSelfModal"
                   :title="'选择自提点'"
                   @closeAction="showTakeSelfModal = false">
      <ul class="addr-list takeself-list">
        <li v-for="(takeself, index) in takeSelfData[currentTakeSelfStoreId]" @click="checkTakeSelf(index)" :class="{active: index === 0}">
          <div class="info-wrap">
            <div class="info-line">
              <label class="mobile-cart-check" :class="{active: index === 0}">
                <input type="checkbox">
              </label>
              <span class="name inline-block text-ellipse">{{takeself.takename}}</span>
            </div>
            <p><span>地址：</span>{{takeself.area + takeself.detailAddress}}</p>
            <p><span>营业时间：</span>{{takeself.businesstime}}</p>
          </div>
        </li>
      </ul>
    </modal-wrapper>
    <!-- 选择自提点弹框end -->

    <remind-box :title="remindText" :timeoutCount="timeoutCount"></remind-box>
    <remind-str :showRemind="showRemindStr"
                :text="'手续费：是指第三方支付机构在交易过程中，按照一定的百分比进行收取的费用。手续费金额=订单金额 * 0.45%'"
                @closeAction="showRemindStr = false"
    ></remind-str>
  </div>
</template>
<script>
  import { LinkUser, ModalWrapper, BottomModalWrapper, AddressEdit, RemindStr } from '~components/mobile/base'
  import { RemindBox } from '~components/mobile/common'
  import { goodsPurchaseOperate } from '~utils/mixin'
  export default {
    layout: 'mobile',
    middleware: 'authenticated',
    data () {
      return {
        orderData: [],
        // 联系卖家店铺信息
        currentStoreInfo: {},
        showLink: false,
        showModal: false,
        showDeliveryModal: false,
        showInvoiceModal: false,
        showAddrModal: false,
        showTakeSelfModal: false,
        currentGoods: [],
        remindText: '',
        timeoutCount: '',
        // 配送规则
        fareRule: {},
        // 自提点
        takeSelfData: {},
        // 正在修改配送方式的店铺id
        currentDeliveryStoreId: '',
        // 订单总价
        allOrderPrice: 0,
        // 选中的发票
        selectedInvoiceIndex: -1,
        // 选中的地址
        selectedAddressIndex: 0,
        // 正在修改自提点的店铺id
        currentTakeSelfStoreId: '',
        editAddr: false,
        currentAddress: {},
        showRemindStr: false
      }
    },
    mixins: [goodsPurchaseOperate],
    components: {
      LinkUser,
      ModalWrapper,
      RemindBox,
      BottomModalWrapper,
      AddressEdit,
      RemindStr
    },
    fetch ({ store, params }) {
      return Promise.all([
        store.dispatch('userCenter/loadPayInfo', {enOrderid: params.orderId}),
        store.dispatch('userCenter/loadAcceptAddress', {send: false}),
        store.dispatch('userCenter/loadPayInvoice')
      ])
    },
//    watch: {
//      '$store.state.userCenter.list.invoice.data': {
//        handler: function (val) {
//          this.invoiceData = this.baseUtils.deepCopy(val)
//          if (this.invoiceData && this.invoiceData.length) {
//            this.invoiceData.forEach(item => {
//              this.$set(item, '$checked', false)
//            })
//          }
//        },
//        immediate: true
//      }
//    },
    computed: {
      payData () {
        //        // 人民币为专用增值税发票，美元不开发票    --1205专用增值税发票   --1206普通发票  --1207不开发票
//        let invoices = this.baseUtils.deepCopy(this.$store.state.userCenter.list.pay.data)
//        if (invoices.currency === 'USD') {
//          invoices.invoicetype = 1207
//          invoices.paytype = '1103'
//        } else {
//          invoices.invoicetype = 1205
//          invoices.paytype = '1102'
//        }
//        // 默认选择第三方配送  --1301第三方配送 --卖家配送  --1303上门自提
//        invoices.deliverytype = 1301
//        return invoices
        return this.baseUtils.deepCopy(this.$store.state.userCenter.list.pay.data)
      },
      addressData () {
        return this.$store.state.userCenter.list.address.data
      },
      invoiceData () {
        return this.$store.state.userCenter.list.invoice.data
      },
      // 已选择完的发票
      selectedInvoice () {
        return this.selectedInvoiceIndex > -1 ? this.invoiceData[this.selectedInvoiceIndex] : null
      },
//      // 选择中选中的发票
//      checkedInvoiceObj () {
//        return this.invoiceData.find(item => {
//          return item.$checked
//        })
//      },
      selectedAddress () {
//        console.log(this.addressData[this.selectedAddressIndex])
        return this.addressData[this.selectedAddressIndex] || {}
      },
      ruleParamsArr () {
        let arr = []
        this.orderData.forEach(item => {
          item.goodsPrice = this.getTotalPrice(item)
          arr.push({
            uuid: item.storeid,
            fare: this.getTotalPrice(item)
          })
        })
        return arr
      },
      allPriceNew () {
        let allOrderPrice = 0
        this.orderData.forEach((item, index) => {
          item.goodsPrice = this.baseUtils.priceFixed(this.getTotalPrice(item)) // 总价
          // 包含运费的价格
//          item.goodsFarePrice = this.baseUtils.priceFixed(item.goodsPrice + (item.fare && item.fare.fare ? item.fare.fare : 0))
          item.goodsFarePrice = item.goodsPrice
//          this.$set(item, 'goodsFarePrice', item.goodsPrice)
          allOrderPrice += item.goodsPrice
        })
        return allOrderPrice
      }
//      // 选择自提点的列表统计
//      showTakeSelfList () {
//        let arr = {}
//        if (!this.showDeliveryModal || !this.showTakeSelfModal) { // 为了触发更新
//          for (let attr in this.fareRule) {
//            arr[attr] = this.fareRule[attr][0] && this.fareRule[attr][0].method === 1303
//          }
//        }
//        return arr
//      }
//      defaultAddress () {
//        return this.addressData.find(item => {
//          return item.num === 1
//        })
//      }
    },
    created () {
      this.initOrderData()
    },
    methods: {
      initOrderData () {
        this.payData.orderDetails.forEach(item => {
          item.goods = item.goodsHistory
          this.initGoodsStatus(item.goods, item.number)
          let current = this.orderData.find(objItem => {
            return objItem.storeid === item.storeid
          })
          if (!current) {
            this.orderData.push({
              storeName: item.storeName,
              storeid: item.storeid,
              supEnUU: item.supEnUU,
              goods: [item],
              $expand: false,
              goodsFarePrice: 0,
              goodsPrice: 0
            })
          } else {
            current.goods.push(item)
          }
        })
        this.getDeliveryRule()
        this.getTakeSelfInfo()
      },
      getDeliveryRule () {
        return this.$http.post(`/trade/distributionRule/usable/rule?area=${this.selectedAddress.area}`, this.ruleParamsArr)
          .then(res => {
//            this.fareRule = res.data || {}
            this.orderData.forEach(item => {
              this.fareRule[item.storeid] = [{
                fare: 0,
                uuid: item.storeid,
                ruleName: '卖家配送，全国包邮',
                method: 1302,
                currencyName: this.payData.currencyName
              }]
            })
            this.initFare()
          }, err => {
            this.setRemindText(err.response.data || '系统错误')
          })
      },
      getTakeSelfInfo () {
        return this.$http.post(`/trade/takeSelf/store/takeSelf`, this.ruleParamsArr)
            .then(res => {
              this.takeSelfData = res.data || {}
            }, err => {
              this.setRemindText(err.response.data || '系统错误')
            })
      },
      initFare () {
        this.allOrderPrice = 0
        this.orderData.forEach(item => {
          item.fare = this.fareRule[item.storeid] && this.fareRule[item.storeid].length ? this.fareRule[item.storeid][0] : {}
          item.goodsPrice = this.baseUtils.priceFixed(this.getTotalPrice(item)) // 总价
          // 包含运费的价格
//          item.goodsFarePrice = this.baseUtils.priceFixed(item.goodsPrice + (item.fare && item.fare.fare ? item.fare.fare : 0))
          item.goodsFarePrice = item.goodsPrice
          this.allOrderPrice += item.goodsFarePrice
        })
      },
      getTotalPrice (storeItem) {
        let price = 0
        storeItem.goods.forEach(item => {
          price += item.goods.currentPrice
        })
        return Number(price.toFixed(6))
      },
      getPoundage (item) {
        return this.baseUtils.priceFixed((item.goodsFarePrice || item.goodsPrice) * 0.00453)
      },
      linkSaler (item) {
        this.$http.get(`/basic/enterprise/${item.supEnUU}/info`).then(res => {
          this.currentStoreInfo = res.data
          this.showLink = true
        }, err => {
          this.setRemindText(err.response.data || '系统错误')
          console.log(err)
        })
      },
      showDetailList (goods) {
        this.currentGoods = goods
        this.showModal = true
      },
      goodsScroll (type) {
        console.log(type)
      },
      setRemindText: function (str) {
        this.remindText = str
        this.timeoutCount++
      },
      checkShowTakeSelf (item) {
        return item.fare && item.fare.method === 1303
      },
      // 显示配送规则弹框
      showRuleSet: function (storeid) {
        if (this.fareRule[storeid] && this.fareRule[storeid].length) {
          this.currentDeliveryStoreId = storeid
          this.clearCurrentDeliveryCheck()
          this.fareRule[this.currentDeliveryStoreId][0].$checked = true
          this.showDeliveryModal = true
        }
//        console.log(storeid)
      },
      clearCurrentDeliveryCheck () {
        this.fareRule[this.currentDeliveryStoreId].forEach(item => {
          if (!item.hasOwnProperty('$checked')) {
            this.$set(item, '$checked', false)
          } else {
            item.$checked = false
          }
        })
      },
      checkDelivery (cdr) {
        if (!cdr.$checked) {
          this.clearCurrentDeliveryCheck()
          cdr.$checked = true
        }
      },
      onDeliveryModalClose (isSubmit) {
        if (!isSubmit) {
          this.showDeliveryModal = false
//          this.currentDeliveryRule = {}
        } else {
          let currentDi = this.fareRule[this.currentDeliveryStoreId]
          for (let i = 0; i < currentDi.length; i++) {
            if (currentDi[i].$checked) {
              this.baseUtils.exchangeArr(currentDi, i, 0)
              break
            }
          }
          this.initFare()
          this.showDeliveryModal = false
        }
      },
      // 显示自提点弹框
      showTakeSelfSet (storeid) {
        if (this.takeSelfData[storeid] && this.takeSelfData[storeid].length) {
          this.currentTakeSelfStoreId = storeid
          this.showTakeSelfModal = true
        }
      },
      checkTakeSelf (index) {
//        for (let i = 0; i < this.takeSelfData[this.currentTakeSelfStoreId].length; i++) {
//          if (item.id === this.takeSelfData[this.currentTakeSelfStoreId][i].id) {
//
//            break
//          }
//        }
        if (index > 0) {
          this.baseUtils.exchangeArr(this.takeSelfData[this.currentTakeSelfStoreId], index, 0)
        }
        this.showTakeSelfModal = false
      },
      setInvoiceCheck (index) {
        if (this.selectedInvoiceIndex === index) {
          return
        }
        this.selectedInvoiceIndex = index
        this.showInvoiceModal = false
      },
      openInvoiceModal () {
        if (this.invoiceData && this.invoiceData.length) {
          this.showInvoiceModal = true
        } else {
          this.setRemindText('暂无发票信息，请前往pc端维护')
        }
      },
      setAddressCheck (index) {
        if (this.selectedAddressIndex === index) {
          this.showAddrModal = false
          return
        }
        this.selectedAddressIndex = index
        this.showAddrModal = false
        this.getDeliveryRule()
      },
      openAddrModal () {
        this.showAddrModal = true
        if (!this.selectedAddress.id) {
          this.editAddr = true
        }
      },
      // 配送规则校验
      checkRule () {
        let flag = true
        for (let attr in this.fareRule) {
          if (!this.fareRule[attr].length) {
            flag = false
          }
        }
        return flag
      },
      // 收货地址校验
      checkAddress () {
        if (!this.selectedAddress || !this.selectedAddress.id) {
          this.setRemindText('请选择收货地址')
          return false
        } else if (this.selectedAddress.area.indexOf('香港') > -1) {
          if (this.payData.currency === 'RMB') {
            this.setRemindText('当前选择的币别是RMB，地址却是香港')
            return false
          }
        } else {
          if (this.payData.currency === 'USD') {
            this.setRemindText('当前选择的币别是USD，地址却是内陆')
            return false
          }
        }
        return true
      },
      // 提交订单流程
      confirmOrder () {
        if (this.accountInvalid) {
          this.setRemindText('您的账户安全等级较低，请先在pc端进行信息完善')
        } else {
          if (this.payData.status === 502 || this.payData.status === 503) {
            this.underLinePaySubmitted()
          } else {
            if (!this.checkRule()) {
              this.setRemindText('当前地址部分卖家无法配送，请重新选择地址或与卖家协商处理')
            } else {
              let infos = []
              let info = this.generateOrderInfo()
              if (info) {
                infos.push(info)
                this.doSubmit(infos)
              }
            }
          }
        }
      },
      // 待付款订单-线下付款
      underLinePaySubmitted () {
        let arr = []
        if (this.payData.orderids) {
          arr = this.payData.orderids.split(',')
        } else {
          arr.push(this.payData.orderid)
        }
        let param = {
          orderid: this.baseUtils.enidfilter(arr.join('-'))
        }
        // 跳转至付款页面
        console.log('订单已存在，直接跳转至付款页面')
        this.$router.push(`/mobile/center/user/doPay/${encodeURIComponent(param.orderid)}`)
        return param
      },
      // 处理订单数据
      generateOrderInfo () {
        let orderInfo = {
          id: this.payData.id,
          orderid: this.payData.orderid
        }
        if (this.payData.currency === 'USD' && this.selectedInvoiceIndex !== -1) {
          this.setRemindText('美元请选择暂不开票')
          return false
        }
        if (this.checkAddress()) {
          orderInfo.add_id = this.selectedAddress.id
        } else {
          return false
        }
        let submitParam = this.orderSubmitParams()
        // 发票信息
        if (this.selectedInvoice) {
          if (this.selectedInvoice.kind === 1205) {
            orderInfo.invoicetype = '1205'
          } else if (this.selectedInvoice.kind === 1206) {
            if (submitParam.includeConsignment) {
              this.setRemindText('订单中包含寄售类型商品，请选择专票')
              return false
            }
            orderInfo.invoicetype = '1206'
          }
          if (this.selectedInvoice.id) {
            orderInfo.invoiceid = this.selectedInvoice.id
          } else {
            this.setRemindText('请添加发票信息')
            return false
          }
        } else {
          orderInfo.invoicetype = '1207'
        }
        orderInfo.totalprice = submitParam.goodsPrice
        orderInfo.currency = this.payData.currency
        orderInfo.orderRemark = JSON.stringify(submitParam.remarkObj)
        // 1103线下 1102线上
        orderInfo.paytype = '1103'
        orderInfo.splitInfo = {
          ruleList: JSON.stringify(submitParam.ruleList)
//          takeList: JSON.stringify(submitParam.takeList)
        }
        orderInfo.orderDetails = this.convertOrderDetailParams()
//        console.log(orderInfo)
        return orderInfo

        // 人民币为专用增值税发票，美元不开发票    --1205专用增值税发票   --1206普通发票  --1207不开发票
        // 默认选择第三方配送  --1301第三方配送 --卖家配送  --1303上门自提
      },
      // 订单提交的参数整合
      orderSubmitParams () {
        let params = {
          // 不包含运费的价格
          goodsPrice: 0,
          // 备注
          remarkObj: {},
          // 配送方式
          ruleList: {},
//          // 自提点
//          takeList: {},
          // 是否包含寄售商品
          includeConsignment: false
        }
        this.orderData.forEach(item => {
          params.goodsPrice += item.goodsPrice
          params.remarkObj[item.storeid] = item.remark
          params.ruleList[item.storeid] = item.fare
//          params.takeList[item.storeid] = this.checkShowTakeSelf(item) && this.takeSelfData[item.storeid] ? [0] : null
          if (item.storeid === '33069557578d44e69bd91ad12d28a8d4') {
            params.includeConsignment = true
          }
        })
        return params
      },
      // 提取要提交到服务器的订单明细goods数据
      convertOrderDetailParams () {
        let orderDetails = []
        this.payData.orderDetails.forEach(item => {
          orderDetails.push({
            id: item.id,
            number: item.goods.purchaseNumber,
            taxUnitprice: item.taxUnitprice,
            remark: item.remark,
            goodsnumber: item.goodsnumber,
            storeid: item.storeid
          })
        })
        return orderDetails
      },
      // 提交订单请求
      doSubmit (orders) {
        this.$http.put(`/trade/order/${this.baseUtils.enidfilter(this.payData.orderid)}/ensure`, orders)
          .then(res => {
            console.log(res)
            if (res.data.code === 1) {
              if (res.data.data && res.data.data[0]) {
                let orderids = []
                let batchCodes = []
                for (let i = 0; i < res.data.data.length; i++) {
                  orderids.push(res.data.data[i].orderid)
                  for (let j = 0; j < res.data.data[i].orderDetails.length; j++) {
                    batchCodes.push(res.data.data[i].orderDetails[j].batchCode)
                  }
                }
                // 如果不是立即购买，删除购物车里的对应信息
                if (!this.payData.buyNow) {
                  this.$http.put('/trade/cart/delete', batchCodes)
                }
                // 跳转至订单提交完成页面
                console.log('订单提交完成，跳转至结果页')
                this.$router.push(`/mobile/center/user/doPay/${encodeURIComponent(this.baseUtils.enidfilter(orderids.join('-')))}`)
              }
            } else {
              if (res.data.data.code === 6) {
                this.setRemindText(res.data.message + ',请刷新界面之后重新操作')
              } else if (res.data.data.code === 7) {
                this.setRemindText(res.data.message + ',将为您跳转到购物车界面')
                setTimeout(() => {
                  this.$router.push('/mobile/center/user/cart')
                }, 1500)
              } else {
                this.setRemindText(res.data.message)
              }
            }
          }, err => {
            console.log(err)
            this.setRemindText(err.response.data || '提交订单失败')
          })
      },
      reloadAddress () {
        this.$store.dispatch('userCenter/loadAcceptAddress', {send: false})
      },
      editClick (obj) {
        if (obj.id) {
          this.reloadAddress()
        }
        this.editAddr = false
      },
      addAddress (item) {
        if (!item) {
          this.currentAddress = {}
        } else {
          this.currentAddress = item
        }
        this.editAddr = true
      },
      deleteAddress (item) {
        this.$http.put(`/trade/address/delete/${item.id}`).then(res => {
          this.setRemindText('删除成功')
          this.reloadAddress()
        }, err => {
          this.setRemindText(err.response.data || '删除失败，系统错误')
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  $red-text: #f43938;
  .mobile-pay {
    margin-bottom: 2.02rem;
    .pay-head {
      height: 1.3rem;
      padding: .25rem 0 0 .21rem;
      position: relative;
      border-bottom: .18rem solid #f1f3f7;
      background: url('/images/mobile/center/user/addr-border.png') no-repeat;
      background-size: contain;
      background-position: bottom;
      .info {
        padding-left: .43rem;
        font-size: .3rem;
        font-weight: bold;
      }
      .addr {
        width: 6.5rem;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        img {
          height: .29rem;
          margin-right: .16rem;
        }
        span {
          font-size: .26rem;
        }
      }
      .icon-xiangyou {
        position: absolute;
        right: .21rem;
        top: .52rem;
        color: #bebebe;
      }
      .no-addr {
        margin-top: .15rem;
        text-align: center;
        padding-right: .21rem;
      }
    }
    .pay-store-list {
      .ps-item {
        border-bottom: .18rem solid #f1f3f7;
        .ps-store-name {
          height: .89rem;
          line-height: .89rem;
          padding: 0 .25rem;
          font-size: .28rem;
          text-align: left;
          .seller-name {
            max-width: 5rem;
            position: relative;
            padding-right: .2rem;
            span {
              color: #666;
            }
            i {
              position: absolute;
              right: 0;
              font-size: .32rem;
              color: #bebebe;
            }
          }
        }
        .ps-goods-info {
          border-top: 1px solid #e4e4e4;
          border-bottom: 1px solid #e4e4e4;
          .ps-goods-list {
            background: #f9f9f8;
            height: 100%;
            li {
              border-bottom: 1px solid #e4e4e4;
              width: 100%;
              .fl {
                margin-right: .23rem;
                width: 3.49rem;
              }
              .fr {
                width: 3.2rem;
                .ol-price {
                  font-size: .26rem;
                }
              }
              .ps-goods-item {
                font-size: .28rem;
                > span {
                  color: #666;
                }
              }
              .single-count {
                height: .61rem;
                line-height: .61rem;
                background: #ebebeb;
                font-size: .28rem;
                color: #666;
                text-align: right;
                padding: 0 .21rem 0 .25rem;
                .ol-price {
                  font-size: .26rem;
                }
              }
            }
          }
          .show-more-psgoods {
            height: .67rem;
            line-height: .67rem;
            font-size: .24rem;
            color: #999;
            text-align: center;
            i {
              font-size: .24rem;
              color: #999;
            }
          }
        }
      }
    }
    .pay-price-title {
      float: left;
      font-size: .3rem;
    }
    .ps-operate-line {
      height: .89rem;
      line-height: .89rem;
      padding: 0 .21rem 0 .25rem;
      border-bottom: 1px solid #e4e4e4;
      font-size: .28rem;
      .fr {
        height: 100%;
        .inline-block {
          line-height: normal;
          text-align: right;
          span {
            color: #666;
           /* &:first-child {
              color: #333;
              font-weight: bold;
              display: block;
            }*/
            &.red {
              color: $red-text;
            }
          }
        }
        .delivery-select {
          width: 1.54rem;
          height: .5rem;
          line-height: .5rem;
          text-align: center;
          border: 1px solid #a1a1a1;
          color: #999;
          background: url('/images/mobile/center/user/delivery.png') no-repeat;
          background-size: .2rem .2rem;
          background-position: 1.3rem .25rem;
          border-radius: .03rem;
          margin-left: .56rem;
          &:first-child {
            margin-left: 0;
          }
          &.active {
            background: url('/images/mobile/center/user/delivery-active.png') no-repeat;
            background-size: .2rem .2rem;
            background-position: 1.3rem .25rem;
            color: #3e85f7;
            border-color: #3e85f7;
          }
        }
        i {
          color: #bebebe;
          margin-left: .14rem;
        }
      }
      input {
        width: 4.78rem;
        margin-left: .68rem;
        padding: 0 .1rem;
        height: .45rem;
      }
      &.ps-price {
        text-align: right;
        padding-right: .31rem;
        .inline-block {
          font-size: .26rem;
        }
      }
      &.ps-fare {
        line-height: .43rem;
        font-size: .24rem;
        .text-ellipse {
          text-align: right;
          color: #333;
          .ol-price {
            font-size: .26rem;
            span {
              font-size: .26rem;
            }
          }
          .pay-price-title {
            font-size: .26rem;
          }
          .fare {
            text-decoration: line-through;
            color: #666!important;
          }
          i {
            font-size: .38rem;
            color: #adacac;
          }
          .tag {
            height: .35rem;
            line-height: .35rem;
            width: .58rem;
            font-size: .22rem;
            color: #fff;
            background: #15b262;
            border-radius: .02rem;
            text-align: center;
            margin-left: .14rem;
            margin-right: .06rem;
            position: relative;
            top: -.06rem;
          }
        }
      }
      &.ps-address {
        height: auto;
        line-height: unset;
        padding: .25rem 0;
        position: relative;
        padding-left: .21rem;
        border-bottom: .11rem solid #f1f3f7;
        > div {
          width: 6.76rem;
          padding-right: .26rem;
          p {
            font-size: .28rem;
          }
        }
        i {
          color: #bebebe;
        }
        .addr {
          margin-bottom: .33rem;
          .area {
            width: 5rem;
            word-break: break-all;
            padding-left: .2rem;
          }
        }
        .info {
          .info-name {
            margin-right: .46rem;
          }
          .info-phone {
            margin-left: .5rem;
          }
        }
        .no-addr {
          text-align: center;
        }
      }
      &.pay-operate {
        border-bottom: .11rem solid #f1f3f7;
        padding-top: 0;
        .fr {
          line-height: .78rem;
          i {
            position: static;
          }
          span {
            color: #333;
            font-size: .28rem;
          }
        }
      }
      &.pay-invoice {
        border-bottom: .11rem solid #f1f3f7;
        .fr {
          font-size: .28rem;
          i {
            float: right;
          }
          p {
            position: relative;
            bottom: 0;
          }
          .inv-head {
            max-width: 4rem;
          }
          .inv-type {
            font-size: .24rem;
            color: #999;
          }
        }
      }
      &.ps-operate-takeself {
        height: 1.35rem;
        line-height: 1.35rem;
        .fr {
          span {
            display: block;
            max-width: 5.5rem;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
    .ol-price {
      color: #f43938 !important;
      font-size: .32rem;
      span {
        font-size: .24rem;
      }
    }
    .buy-wrap {
      position: fixed;
      bottom: .98rem;
      height: 1.02rem;
      line-height: 1.02rem;
      padding-left: .27rem;
      background: #fff;
      width: 100%;
      border-top: .02rem solid #ccc;
      .fr {
        .title {
          font-size: .28rem;
          margin-right: .13rem;
        }
        .price {
          max-width: 3.6rem;
          vertical-align: top;
          span {
            margin-right: .08rem;
          }
          margin-right: .13rem;
        }
        .buy-btn {
          width: 2.08rem;
          height: 1.02rem;
          line-height: 1.02rem;
          text-align: center;
          font-size: .28rem;
          color: #fff;
          background: #3f84f6;
        }
      }
    }
    .cGoods-list {
      background: #fff;
      li {
        padding: .3rem .32rem;
        border-bottom: 1px solid #e4e4e4;
        .fl {
          .cg-param-line {
            width: 3.65rem;
            margin-bottom: .23rem;
            &:last-child {
              margin-bottom: 0;
            }
            font-size: .28rem;
            span {
              color: #666;
            }
          }
        }
        .fr {
          text-align: right;
          p {
            width: 2.3rem;
          }
          .ol-price {
            margin-top: .59rem;
          }
          .count {
            color: #999;
            font-size: .24rem;
            margin-top: .32rem;
          }
        }
      }
    }
    .delivery-rule-list {
      li {
        background: #fff;
        text-align: left;
        padding: 0 .31rem 0 .25rem;
        height: .94rem;
        line-height: .94rem;
        .fr {
          height: 100%;
          .ol-price {
            margin-left: .23rem;
          }
        }
      }
    }
    .invoice-list {
      background: #f1f3f7;
      padding: .19rem 0;
      li {
        margin-bottom: .19rem;
        position: relative;
        &:last-child {
          margin-bottom: 0;
        }
        background: #fff;
        padding: .26rem .16rem .32rem .25rem;
        .inv-head {
          margin-left: .17rem;
          max-width: 5.3rem;
        }
        .inv-type {
          position: absolute;
          right: 0;
          top: 0;
          height: .85rem;
        }
        .content-line {
          margin-top: .23rem;
          padding-left: .53rem;
          .title {
            width: 34%;
            text-align: right;
            vertical-align: top;
          }
          .content {
            width: 66%;
            word-break: break-all;
          }
        }
      }
    }
    .addr-list-wrap {
      background: #f1f3f7;
      padding: .19rem 0;
    }
    .addr-list {
      background: #f1f3f7;
      li {
        margin-bottom: .19rem;
        position: relative;
        &:last-child {
          margin-bottom: 0;
        }
        background: #fff;
        .info-wrap {
          padding: .35rem .25rem .28rem;
        }
        .info-line {
          font-size: .3rem;
          color: #666;

          .name {
            margin: 0 .27rem 0 .17rem;
            max-width: 1.5rem;
          }
          .tel {
            max-width: 2.3rem;
          }
          i {
            width: 1.08rem;
            height: .25rem;
            line-height: .25rem;
            font-size: .24rem;
            text-align: center;
            border: 1px solid #fc2706;
            border-radius: .04rem;
            color: #f43938;
            font-style: normal;
            margin-left: .48rem;
          }
        }
        p {
          margin-top: .19rem;
          word-break: break-all;
          padding-left: .54rem;
          font-size: .28rem;
          color: #999;
        }
        &.active {
          .info-line {
            color: #f43938;
          }
          p {
            color: #666;
          }
        }
        .edit-addr-area {
          border-top: 1px solid #d9d9d9;
          .addr-btn {
            width: 50%;
            height: .8rem;
            line-height: .8rem;
            color: #333;
            text-align: center;
            i {
              font-size: .34rem;
              margin-right: .1rem;
            }
            &:first-child {
              border-right: 1px solid #d9d9d9;
            }
          }
        }
      }
    }
    .add-addr-btn {
      /*position: absolute;*/
      /*bottom: .26rem;*/
      /*left: .52rem;*/
      width: 5.67rem;
      text-align: center;
      display: block;
      margin: .26rem auto .07rem;
      height: .77rem;
      line-height: .77rem;
      background: #3f84f6;
      border-radius: .08rem;
      color: #fff;
      font-size: .32rem;
      i {
        margin-right: .08rem;
      }
    }
    .takeself-list {
      li {
        .info-line {
          .name {
            max-width: 5.3rem;
          }
        }
      }
    }
    .input-line {
      $group-height: .4rem;
      input {
        width: .91rem;
        height: $group-height;
        border-top: 1px solid #ddd;
        border-bottom: 1px solid #ddd;
        vertical-align: middle;
        border-radius: 0;
        padding: 0 .05rem;
        text-align: center;
        line-height: $group-height;
        /*  position: relative;
          top: .01rem;*/
      }
      span {
        width: .35rem;
        height: $group-height;
        line-height: .38rem;
        text-align: center;
        border: 1px solid #ddd;
        font-size: .24rem;
        &:first-child {
          border-top-left-radius: .05rem;
          border-bottom-left-radius: .05rem;
        }
        &:last-child {
          border-top-right-radius: .05rem;
          border-bottom-right-radius: .05rem;
        }
        &.disab {
          background: #e8e8e8;
        }
      }
    }
  }
  .addr-modal {
    .addr-modal-wrapper {
      top: 1.5rem;
      bottom: 1.5rem;
      left: .2rem;
      right: .2rem;
      background: #fff;
    }
  }
</style>
