<template>
  <div class="mobile-cart" :class="{'empty-mobile-cart': !cartList.length}" id="mobileFixContent" @touchmove="blurEvent()">
    <template v-if="cartList.length">
      <ul class="store-list">
        <li class="store-item" v-for="(item, storeIndex) in cartList">
          <div class="store-info">
            <label class="mobile-cart-check" :class="{'active': item.$active}">
              <input type="checkbox" @change="setActive('store', storeIndex)">
            </label>
            <span class="store-tag inline-block" :style="getStoreTypeColor(item.storeType)">{{item.storeType | storeTypeFilter}}</span>
            <p class="store-name inline-block text-ellipse">卖&nbsp;&nbsp;家：{{item.storeName}}</p>
            <a class="com-mobile-link" @click="linkSaler(item)"><i class="iconfont icon-kefu1"></i>联系卖家</a>
          </div>
          <ul class="goods-list">
            <li class="goods-item" v-for="(goods, goodsIndex) in item.goods">
              <div style="padding: .3rem .25rem">
                <label class="mobile-cart-check" :class="{'active': goods.$active}">
                  <input type="checkbox" @change="setActive('goods', storeIndex, goodsIndex)">
                </label>
                <div class="params inline-block">
                  <p class="param text-ellipse"><span class="title">品牌：</span>{{goods.goods.brandNameEn || '-'}}</p>
                  <p class="param text-ellipse"><span class="title">物料名称(类目)：</span>{{goods.kiName || '-'}}</p>
                  <p class="param text-ellipse"><span class="title">型号：</span>{{goods.code || '-'}}</p>
                  <p class="param text-ellipse"><span class="title">规格：</span>{{goods.spec || '-'}}</p>
                </div>
                <div class="inline-block params param-operate">
                  <p class="param text-ellipse"><span class="title">交期(天)：</span>{{goods.goods.b2cMinDelivery + '-' + goods.goods.b2cMaxDelivery}}</p>
                  <p class="param text-ellipse"><span class="title">单价：</span>{{goods.currencyName | currencyFilter}}{{baseUtils.getPriceByLevel(goods.goods.prices, goods.number, goods.currencyName) | priceFilter}}</p>
                  <p class="param text-ellipse"><span class="title">起拍：</span>{{goods.goods.minBuyQty}}</p>
                  <p class="param"><span class="title">数量(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" ref="numberInput" v-model="goods.goods.purchaseNumber" @blur="blurEvent('set', goods)" @focus="focusEvent()">
                    <span class="inline-block" @click="setGoods('add', goods)" :class="{disab: !goods.goods.canAdd}">+</span>
                  </span>
                  </p>
                  <!--<div class="price-line">
                    <span>{{goods.currencyName | currencyFilter}}</span>{{goods.goods.currentPrice}}
                  </div>-->
                </div>
              </div>
              <div class="single-count text-ellipse"><span class="title">小计：</span><span class="ol-price"><span>{{goods.currencyName | currencyFilter}}</span>{{goods.goods.currentPrice | priceFilter}}</span></div>
            </li>
          </ul>
        </li>
      </ul>
      <div class="buy-wrap" ref="buyWrap">
        <div class="wrap-select line">
          <label class="mobile-cart-check" :class="{'active': isAllChecked}">
            <input type="checkbox" @change="setActive('all')">
            <span>全选</span>
          </label>
          <a class="operate-btn fr" @click="removeInvalidGoods">清空失效产品</a>
          <a class="operate-btn fr" @click="batchDelete">批量删除</a>
        </div>
        <div class="wrap-count line">
          <!--<i class="fare">不含运费</i>-->
          <span class="title">合计:</span><span class="price"><span v-show="allCount > 0">{{allCurrency | currencyFilter}}</span>{{allPrice | priceFilter}}</span>
          <button class="buy-btn" @click="submit">去结算</button>
        </div>
      </div>
    </template>
    <template v-else>
      <empty-status :text="'购物车空空如也，快去添加商品吧！'"></empty-status>
    </template>
    <remind-box :title="remindText" :timeoutCount="timeoutCount"></remind-box>
    <pull-up :searchMore="fetching" :allPage="allPage" :page="page" @pullUpAction="onPullUpAction"></pull-up>
    <link-user :infoObj="currentStoreInfo"
               :showLink="showLink"
               @closeAction="showLink = false"></link-user>
  </div>
</template>
<script>
  import {RemindBox, PullUp, EmptyStatus} from '~components/mobile/common'
  import {LinkUser} from '~components/mobile/base'
  import { goodsPurchaseOperate } from '~utils/mixin'
  export default {
    layout: 'mobile',
    middleware: 'authenticated',
    data () {
      return {
        cartList: [],
        remindText: '',
        timeoutCount: '',
        isAllChecked: false,
        page: 1,
        count: 10,
        allCurrency: 'RMB', // 选定币别
        currentStoreInfo: {},
        showLink: false,
        isChange: false
      }
    },
    mixins: [goodsPurchaseOperate],
    components: {
      RemindBox,
      PullUp,
      LinkUser,
      EmptyStatus
    },
    fetch ({ store }) {
      return Promise.all([
        store.dispatch('userCenter/loadCartList', {page: 1, count: 10})
      ])
    },
    watch: {
      '$store.state.userCenter.list.cart.data': {
        handler: function (val) {
          let tmpVal = this.baseUtils.deepCopy(val)
//          this.cartList = []
          if (this.isChange) {
            this.cartList = []
          }
          tmpVal.content.forEach(item => {
            let current = this.cartList.find(objItem => {
              return objItem.storeUuid === item.storeUuid
            })
            item.$active = false
            // 初始化购买数量及状态
            this.initGoodsStatus(item.goods)
            if (!current) {
              this.cartList.push({
                storeName: item.storeName,
                storeType: item.storeType,
                storeUuid: item.storeUuid,
                enterprise: item.storeEnterprise.enterpriseInfo,
                goods: [item],
                $active: false
              })
            } else {
              current.goods.push(item)
            }
          })
          this.checkAll()
        },
        immediate: true
      }
    },
    computed: {
      cartData () {
        return this.$store.state.userCenter.list.cart.data
      },
      fetching () {
        return this.$store.state.userCenter.list.cart.fetching
      },
      allPage () {
        return this.cartData.totalPages
      },
      // 已选goods
      allActiveObj () {
        let arr = []
        this.cartList.forEach(item => {
          item.goods.forEach(goodsItem => {
            if (goodsItem.$active) {
              arr.push(goodsItem)
            }
          })
        })
        return arr
      },
      // 统计价格
      allPrice () {
        let price = 0
        this.allActiveObj.forEach(item => {
          price += Number(item.goods.currentPrice)
        })
        return this.baseUtils.priceFixed(price)
      },
      // 统计数量
      allCount () {
        return this.allActiveObj.length
      }
    },
    methods: {
      // 失去焦点事件
      blurEvent (type, obj) {
        this.$refs.buyWrap.hidden = false
        this.$store.commit('option/SET_SHOW_MOBILE_FOOTER', true)
        this.$refs.numberInput.forEach((value) => {
          value.blur()
        })
        if (type && obj) {
          this.setGoods(type, obj)
        }
      },
      // 获得焦点事件
      focusEvent () {
        this.$refs.buyWrap.hidden = true
        this.$store.commit('option/SET_SHOW_MOBILE_FOOTER', false)
      },
      getStoreTypeColor: function (type) {
        let tmp = null
        switch (type) {
          case 'CONSIGNMENT':
            tmp = '#f3393a'
            break
          case 'DISTRIBUTION':
            tmp = '#4083f6'
            break
          case 'AGENCY':
            tmp = '#15b262'
            break
          case 'ORIGINAL_FACTORY':
            tmp = '#ff6300'
            break
        }
        if (tmp) {
          return `background: ${tmp};`
        } else {
          return ''
        }
      },
      setRemindText: function (str) {
        this.remindText = str
        this.timeoutCount++
      },
      checkCurrency: function (currency, callback) {
        if (currency === this.allCurrency) {
          callback.call()
        } else {
          this.setRemindText('所选产品币别与已选产品不是同一币别')
        }
      },
      setActive (type, storeIndex, goodsIndex, goodsCheckFlag) {
        if (type === 'store') {
          let storeActive = this.cartList[storeIndex].$active
          for (let i = 0; i < this.cartList[storeIndex].goods.length; i++) {
            this.setActive('goods', storeIndex, i, !storeActive)
          }
//          this.cartList[storeIndex].goods.forEach(item => {
//            this.checkCurrency(item.goods.currencyName, () => {
//              item.$active = !this.cartList[storeIndex].$active
//            })
//          })
          this.checkAll()
        } else if (type === 'goods') {
          if (!this.allActiveObj[0]) {
            this.allCurrency = this.cartList[storeIndex].goods[goodsIndex].currencyName
          }
          this.checkCurrency(this.cartList[storeIndex].goods[goodsIndex].currencyName, () => {
            this.cartList[storeIndex].goods[goodsIndex].$active = typeof goodsCheckFlag === 'undefined' ? !this.cartList[storeIndex].goods[goodsIndex].$active : goodsCheckFlag
//            this.cartList[storeIndex].$active = !this.cartList[storeIndex].goods.find(item => {
//              return !item.$active
//            })
            this.checkAll()
          })
        } else if (type === 'all') {
          let activeFlag = true
          this.cartList.forEach(item => {
            item.goods.forEach(goodsItem => {
              if (!goodsItem.$active) {
                activeFlag = false
              }
            })
          })
          for (let i = 0; i < this.cartList.length; i++) {
            this.cartList[i].$active = activeFlag
            this.setActive('store', i)
          }
          this.checkAll()
        }
      },
      // 总勾选校验
      checkAll: function () {
        let activeFlag = true
        this.cartList.forEach(item => {
          let itemActive = true
          item.goods.forEach(goodsItem => {
            if (!goodsItem.$active) {
              activeFlag = false
              itemActive = false
            }
          })
          item.$active = itemActive
        })
        this.isAllChecked = activeFlag
      },
      onPullUpAction: function () {
        this.page++
        this.reloadList()
      },
      reloadList: function () {
        this.$store.dispatch('userCenter/loadCartList', {page: this.page, count: this.count})
      },
      submit: function () {
        if (!this.allCount) {
          this.setRemindText('请勾选要生成订单的批次')
          return
        }
        let arrOD = []
        this.allActiveObj.forEach(item => {
          arrOD.push({
            batchCode: item.goods.batchCode,
            minPackQty: item.goods.minPackQty,
            number: item.goods.purchaseNumber,
            storeid: item.storeUuid
          })
        })
        console.log(arrOD)
        this.$http.post('/trade/order/saveByGroup', {
          arrOD: arrOD,
          currency: this.allCurrency
        }).then(res => {
          console.log(res.data)
          if (res.data.code === 1) {
            if (res.data.message) {
              this.setRemindText(res.data.message)
            }
            this.$router.push(`/mobile/center/user/pay/${this.baseUtils.enidfilter(res.data.data.orderid)}`)
          } else if (res.data.code === 7) {
            this.setRemindText('选中的购物车信息已经失效，将为您刷新界面之后重新操作')
            setTimeout(() => {
              this.page = 1
              this.cartList = []
              this.reloadList()
            }, 1500)
          } else {
            this.setRemindText(res.data.message)
          }
        }, err => {
          console.log(err.response.data || '系统错误')
          this.setRemindText(err.response.data || '系统错误')
        })
      },
      linkSaler (item) {
        this.currentStoreInfo = item.enterprise
        this.showLink = true
      },
      removeInvalidGoods () {
        let arr = []
        this.allActiveObj.forEach(item => {
          if (item.status === 1) {
            arr.push(item.id)
          }
        })
        if (!arr.length) {
          this.setRemindText('购物车内目前没有失效的产品')
        } else {
          this.doDelete(arr, '成功清除购物车内的无效产品')
        }
      },
      batchDelete () {
        if (!this.allActiveObj.length) {
          this.setRemindText('请选择要删除的商品')
        } else {
          let arr = []
          this.allActiveObj.forEach(item => {
            arr.push(item.id)
          })
          this.doDelete(arr, '删除成功')
        }
      },
      doDelete (idArr, successStr) {
        this.$http.delete(`/trade/cart/deleteById?ids=${JSON.stringify(idArr)}`).then(res => {
          this.isChange = true
          this.page = 1
          this.reloadList()
          this.setRemindText(successStr)
        }, err => {
          this.setRemindText(err.response.data || '系统错误')
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .mobile-cart {
    margin-bottom: 3rem;
    padding-top:1.26rem;
    &.empty-mobile-cart {
      bottom: .98rem;
    }
    .store-list {
      .store-item {
        background: #fff;
        margin: .19rem 0;
        .store-info {
          height: .9rem;
          line-height: .9rem;
          padding: 0 .25rem;
          .store-tag {
            width: .54rem;
            height: .3rem;
            line-height: .3rem;
            text-align: center;
            font-size: .24rem;
            color: #fff;
            background: #15b262;
            border-radius: .04rem;
            margin-left: .18rem;
          }
          .store-name {
            font-size: .28rem;
            margin-left: .08rem;
            max-width: 4rem;
          }
        }
        .goods-list {
          .goods-item {
            border-top: 1px solid #e4e4e4;
            .single-count {
              height: .61rem;
              line-height: .61rem;
              background: #ebebeb;
              font-size: .28rem;
              color: #666;
              text-align: right;
              padding: 0 .21rem 0 .72rem;
              .ol-price {
                font-size: .26rem;
              }
              .title {
                float: left;
                font-size: .3rem;
              }
            }
            .params {
              margin-left: .17rem;
              width: 3.03rem;
              .param {
                margin-top: .22rem;
                &:first-child {
                  margin-top: 0;
                }
                .title {
                  color: #666;
                }
              }
            }
            .param-operate {
              width: 3.23rem;
              .input-line {
                $group-height: .5rem;
                input {
                  width: .98rem;
                  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: .48rem;
                  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;
                  }
                }
              }
              /*.price-line {
                font-size: .32rem;
                color: #f43938;
                margin-top: .2rem;
                span {
                  margin-right: .06rem;
                  font-size: .24rem;
                }
              }*/
            }
          }
        }
      }
    }
    .buy-wrap {
      position: fixed;
      bottom: .98rem;
      background: #fff;
      width: 100%;
      .line {
        border-top: .02rem solid #ccc;
        height: 1.02rem;
        line-height: 1.02rem;
        padding-left: .27rem;
      }
      .wrap-count {
       /* .fare {
          font-size: .24rem;
          color: #999;
          margin-right: .15rem;
          font-style: normal;
          display: inline-block;
          vertical-align: middle;
        }*/
        text-align: right;
        .title {
          font-size: .28rem;
          margin-right: .1rem;
          vertical-align: middle;
        }
        .price {
          font-size: .28rem;
          color: #fc2706;
          display: inline-block;
          max-width: 3.6rem;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          vertical-align: middle;
          span {
            font-size: .24rem;
            margin-right: .08rem;
          }
          margin-right: .25rem;
        }
        .buy-btn {
          width: 2.08rem;
          height: 1.04rem;
          line-height: 1.04rem;
          text-align: center;
          font-size: .28rem;
          color: #fff;
          background: #3f84f6;
          vertical-align: middle;
        }
      }
      .wrap-select {
        padding-right: .15rem;
        .operate-btn {
          display: inline-block;
          font-size: .26rem;
          padding: .16rem .12rem;
          color: #3f84f6;
          border: 1px solid #3f84f6;
          margin-left: .28rem;
          border-radius: .04rem;
          line-height: normal;
          margin-top: .16rem;
        }
      }
    }
    .ol-price {
      font-size: .28rem;
      color: #f43938 !important;
      span {
        color: #f43938 !important;
        font-size: .24rem;
      }
    }
  }
</style>
