<template>
  <div class="mobile-fix-content mobile-centerfix-content mobile-cart" :class="{'empty-mobile-cart': !cartList.length}" id="mobileFixContent">
    <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">{{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">
              <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>品牌：</span>{{goods.goods.brandNameEn || '-'}}</p>
                <p class="param text-ellipse"><span>类目：</span>{{goods.kiName || '-'}}</p>
                <p class="param text-ellipse"><span>型号：</span>{{goods.code || '-'}}</p>
                <p class="param text-ellipse"><span>规格：</span>{{goods.spec || '-'}}</p>
              </div>
              <div class="fr">
                <!--<p class="goods-tag">{{goods.goods.tag || '-'}}</p>-->
                <div class="input-line">
                  <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>
                </div>
                <div class="price-line">
                  <span>{{goods.currencyName | currencyFilter}}</span>{{goods.goods.currentPrice}}
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
      <div class="buy-wrap">
        <label class="mobile-cart-check" :class="{'active': isAllChecked}">
          <input type="checkbox" @change="setActive('all')">
          <span>全选</span>
        </label>
        <div class="fr">
          <i class="fare">不含运费</i>
          <span class="title">合计:</span><span class="price"><span v-show="allCount > 0">{{allCurrency | currencyFilter}}</span>{{allPrice}}</span>
          <button class="buy-btn" @click="submit">结算({{allCount}})</button>
        </div>
      </div>
    </template>
    <template v-else>
      <empty-status :text="'购物车空空如也，快去添加商品吧！'"></empty-status>
    </template>
    <remind-box :title="remindText" :timeoutCount="timeoutCount"></remind-box>
    <pull-up :fixId="'mobileFixContent'" :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'
  export default {
    layout: 'mobile',
    middleware: 'authenticated',
    data () {
      return {
        cartList: [],
        remindText: '',
        timeoutCount: '',
        isAllChecked: false,
        page: 1,
        count: 10,
        allCurrency: 'RMB', // 选定币别
        currentStoreInfo: {},
        showLink: false
      }
    },
    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 = []
          tmpVal.content.forEach(item => {
            let current = this.cartList.find(objItem => {
              return objItem.storeUuid === item.storeUuid
            })
            item.$active = false
            // 初始化购买数量及状态
            let goodsItem = item.goods
            let pack = goodsItem.perQty || goodsItem.minPackQty
            if (goodsItem.breakUp) {
              goodsItem.purchaseNumber = goodsItem.minBuyQty
              goodsItem.canSub = false
              goodsItem.canAdd = goodsItem.purchaseNumber < goodsItem.reserve
            } else {
              if (pack >= goodsItem.minBuyQty) {
                goodsItem.purchaseNumber = pack
              } else {
                let max = Math.max(pack, goodsItem.minBuyQty)
                goodsItem.purchaseNumber = max + max % pack
              }
              goodsItem.canSub = false
              goodsItem.canAdd = goodsItem.purchaseNumber + goodsItem.minPackQty <= goodsItem.reserve
            }
            goodsItem.currentPrice = Number((this.baseUtils.getPriceByLevel(goodsItem.prices, goodsItem.purchaseNumber, goodsItem.currencyName) * goodsItem.purchaseNumber).toFixed(6))
            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: {
      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
      },
      onPurchaseNumberInput: function (goods) {
        let showPrice = this.baseUtils.getPriceByLevel(goods.goods.prices, goods.goods.purchaseNumber, goods.goods.currencyName)
        goods.goods.currentPrice = Number(((showPrice || goods.goods.currentPrice) * goods.goods.purchaseNumber).toFixed(6))
//        console.log(goods.goods.currentPrice)
      },
      checkPurchaseNumber: function (goods) {
        if ((/^[\d]*$/).test(goods.goods.purchaseNumber)) {
          this.changeNum(goods.goods.purchaseNumber, goods)
        } else {
          this.setRemindText('请输入整数')
          goods.goods.purchaseNumber = goods.goods.minBuyQty
        }
      },
      setGoods: function (type, goods) {
        if (type === 'set') {
          this.checkPurchaseNumber(goods)
        } else {
          let isAdd = type === 'add'
          let pack = goods.goods.perQty || goods.goods.minPackQty
          let newNum = 0
          if (goods.goods.breakUp) {
            newNum = isAdd ? goods.goods.purchaseNumber + 1 : goods.goods.purchaseNumber - 1
          } else {
            newNum = isAdd ? goods.goods.purchaseNumber + pack : goods.goods.purchaseNumber - pack
          }
          this.changeNum(newNum, goods)
        }
      },
      changeNum: function (newNum, goods) {
        let pack = goods.goods.perQty || goods.goods.minPackQty
        let buy = goods.goods.minBuyQty
        let reserve = goods.goods.reserve
        let breakUp = goods.goods.breakUp
        if (!newNum && newNum !== 0) {
          goods.goods.purchaseNumber = buy
        } else {
          newNum = parseInt(newNum)
          if (breakUp) {
            if (newNum < buy) {
              this.setRemindText('最小起订量为' + buy)
              goods.goods.purchaseNumber = buy
              goods.goods.canSub = false
              goods.goods.canAdd = true
            } else if (newNum > reserve) {
              this.setRemindText('库存不足')
              goods.goods.purchaseNumber = reserve
              goods.goods.canAdd = false
              goods.goods.canSub = true
            } else {
              goods.goods.canSub = true
              goods.goods.canAdd = true
              goods.goods.purchaseNumber = newNum
              newNum === buy && (goods.goods.canSub = false)
              newNum === reserve && (goods.goods.canAdd = false)
            }
          } else {
            if (newNum < buy) {
              this.setRemindText('最小起订量为' + buy)
              goods.goods.purchaseNumber = buy
              goods.goods.canSub = false
              if (newNum > reserve) {
                this.setRemindText('库存不足')
                goods.goods.purchaseNumber = reserve - (reserve % pack)
                goods.goods.canAdd = false
              }
            } else if (newNum > reserve) {
              goods.goods.canSub = true
              goods.goods.canAdd = false
              this.setRemindText('库存不足')
              goods.goods.purchaseNumber = reserve - (reserve % pack)
            } else {
              goods.goods.canSub = true
              goods.goods.canAdd = true
              let remainder = newNum % pack
              if (remainder !== 0) {
//                console.log(this.fragment.num)
                this.setRemindText('不支持拆包且包装量为' + pack)
                // 这个直接赋值的，应该给这个值进行判断(Math.floor(newNum / pack) + 1) * pack
                let res = (Math.floor(newNum / pack) + 1) * pack
                goods.goods.purchaseNumber = res > reserve ? Math.floor(newNum / pack) * pack : res
              } else {
                goods.goods.purchaseNumber = newNum
              }
              newNum === buy && (goods.goods.canSub = false)
              newNum === reserve && (goods.goods.canAdd = false)
            }
          }
        }
        this.onPurchaseNumberInput(goods)
      },
      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.data || '系统错误')
          this.setRemindText(err.response.data.data || '系统错误')
        })
      },
      linkSaler (item) {
        this.currentStoreInfo = item.enterprise
        this.showLink = true
      }
    }
  }
</script>
<style lang="scss" scoped>
  .mobile-cart {
    bottom: 2rem;
    &.empty-mobile-cart {
      bottom: .98rem;
    }
    .store-list {
      .store-item {
        padding: 0 .25rem;
        background: #fff;
        margin: .19rem 0;
        .store-info {
          height: .9rem;
          line-height: .9rem;
          .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 {
            padding: .3rem 0;
            border-top: 1px solid #e4e4e4;
            .params {
              margin-left: .17rem;
              .param {
                width: 3.65rem;
                margin-top: .22rem;
                &:first-child {
                  margin-top: 0;
                }
                span {
                  color: #666;
                }
              }
            }
            .fr {
              width: 2.6rem;
              text-align: center;
              .input-line {
                $group-height: .4rem;
                margin-top: .52rem;
                input {
                  width: 1.31rem;
                  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: .5rem;
                  height: $group-height;
                  line-height: $group-height;
                  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;
      height: 1.02rem;
      line-height: 1.02rem;
      padding-left: .27rem;
      background: #fff;
      width: 100%;
      border-top: .02rem solid #ccc;
      .fr {
        .fare {
          font-size: .24rem;
          color: #999;
          margin-right: .15rem;
          font-style: normal;
          display: inline-block;
          vertical-align: middle;
        }
        .title {
          font-size: .28rem;
          margin-right: .1rem;
          vertical-align: middle;
        }
        .price {
          font-size: .28rem;
          color: #fc2706;
          display: inline-block;
          max-width: 1.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.02rem;
          line-height: 1.02rem;
          text-align: center;
          font-size: .28rem;
          color: #fff;
          background: #fc2706;
        }
      }
    }
  }
</style>
