<template>
  <view class="page">
    <cu-custom :isBack="true"></cu-custom>
    <view class="header" :style="[{ top: topHeader + 'px' }]">
      <view class="header-title">
        <view class="header-title-main">
          <view class="margin-bottom-xs">{{ title }}</view>
          <view class="point"></view>
        </view>
      </view>
    </view>
    <scroll-view scroll-y="true" :style="[{ height: 'calc(100vh - 64px - 70px - ' + topHeader + 'px)' }]" class="scroll-main">
      <view class="list">
        <checkbox-group @change="checkChange">
          <view class="cu-card margin-bottom shadow" v-for="(item, index) in list" :key="index">
            <label class="cu-item">
              <view class="card-header flex justify-between solid-bottom">
                <view>
                  <checkbox style="transform: scale(0.8);" class="round" :value="item.shopping_id" :checked="checkedIds.includes(item.shopping_id)"></checkbox>
                  {{ item.student_name }}
                </view>
                <view @tap.stop="">
                  <text class="cuIcon-delete text-red" @tap="del(item, index)"></text>
                </view>
              </view>
              <view class="card flex">
                <view class="card-left">
                  <img mode="scaleToFill" :src="item.image" alt="" class="card-image" />
                </view>
                <view class="card-right flex-sub margin-left-sm text-sm">
                  <view class="card-title">{{ item.class_attend_name }}</view>
                  <view class="text-price text-student text-xl margin-top-xs">{{ item.price }}</view>
                  <view class="card-item">
                    <text class="card-label">机构：</text>
                    <text class="card-text">{{ item.agency_name || '-' }}</text>
                  </view>
                  <view class="card-item margin-top-xs" v-if="item.cate_type === 0">
                    <text class="card-label">老师：</text>
                    <text class="card-text">{{ item.teacher_name || '-' }}</text>
                  </view>
                  <view class="card-item margin-top-xs">
                    <text class="card-label">总共：</text>
                    <text class="card-text">{{ item.class_total || '-' }}</text>
                  </view>
                  <view class="card-item margin-top-xs">
                    <text class="card-label">时间：</text>
                    <text class="card-text">{{ item.week_limit || '-' }}</text>
                  </view>
                </view>
              </view>
              <view class="card-footer margin-top-xs" v-if="item.prop">
                <view v-for="(tag, index) in item.prop" :key="index" class="cu-tag line-red">{{ tag }}</view>
              </view>
              <view class="card-bottom margin-top-xs">
                <!-- <button @tap="pay(item)" class="cu-btn round bg-student text-white">立即下单</button> -->
              </view>
            </label>
          </view>
        </checkbox-group>
      </view>
    </scroll-view>
    <view class="static flex shadow">
      <view class="static-price">
        <checkbox-group @change="chooseAll">
          <label class="padding-tb-sm"> <checkbox class="round" :checked="checkAll" style="transform: scale(0.8);" />全选 </label>
        </checkbox-group>
      </view>
      <view class="static-choose text-center" v-if="checkedIds.length > 0">
        <text>已选：</text><text class="margin-right-xs">{{ checkedIds.length }}</text> <text>总价：</text><text class="text-price text-red">{{ sum }}</text>
      </view>
      <view class="static-order flex align-center">
        <button class="cu-btn round bg-student text-white margin-left-xs" @tap="pay">立即下单</button>
      </view>
    </view>
  </view>
</template>

<script>
import { _shopList, _delShop, _createOrder } from '@/api/course'
import { mapGetters } from 'vuex'
import { deepClone } from '@/common/utils'
import NP from 'number-precision'
import socket from '@/common/webSocket'
export default {
  data() {
    return {
      title: '购物车',
      topHeader: this.globalCustomBarHeight,
      list: [],
      checkedIds: [], // 已选择
      shoppingList: [], // 购物车列表
      sum: 0,
      all: [], // 全部
      payable: false, //控制重复点击
      checkAll: false
    }
  },
  computed: {
    ...mapGetters(['carts', 'phone', 'ifConnectOrder'])
  },
  onShow() {
    this.get_list()
  },
  onLoad(options) {
    socket.initSocket()
  },
  methods: {
    subscribeMsg() {
      return new Promise((resolve, reject) => {
        uni.requestSubscribeMessage({
          tmplIds: ['tfuaGZ8IOk0-JDKMcr5bVhUiiqvIORJHR_74VoPuWH4'],
          success(res) {},
          fail(res) {},
          complete(res) {
            resolve(true)
          }
        })
      })
    },
    checkChange(e) {
      this.checkedIds = e.detail.value.map(x => Number(x))
      this.shoppingList = this.list.filter(item => this.checkedIds.includes(item.shopping_id))
      this.sum_money()
    },
    chooseAll() {
      this.checkAll = !this.checkAll
      this.checkedIds = this.checkAll ? this.all : []
      this.shoppingList = this.checkAll ? deepClone(this.list) : []
      this.sum_money()
    },
    sum_money() {
      const arr = this.shoppingList.map(item => item.price)
      this.sum = arr.reduce((x, y) => NP.plus(x, y), 0)
    },
    get_list() {
      _shopList().then(res => {
        this.list = res.data
        this.all = this.list.map(item => item.shopping_id) // 统计全部
        const carts = this.list.map(item => item.class_attend_id)
        this.$store.dispatch('setCarts', carts) // 刷新购物车
      })
    },
    del(item, index) {
      const _self = this
      uni.showModal({
        title: '提示',
        content: '确定要删除？',
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            _delShop({ shopping_id: item.shopping_id, student_id: item.student_id }).then(res => {
              _self.get_list()
            })
          }
        }
      })
    },
    pay() {
      if (this.payable) return false
      this.payable = true
      if (!this.phone) {
        return this.globalNavigateTo('bindPhone')
      }
      if (this.checkedIds.length < 1) {
        this.payable = false
        uni.showToast({ title: '请先选择课程', icon: 'none', duration: 1000 })
        return false
      }
      //订阅消息
      this.subscribeMsg().then(res => {
        this.placeOrder() //下单
      })
    },
    placeOrder() {
      uni.showLoading({
        mask: true,
        title: '加载中...'
      })
      const order = JSON.stringify(this.shoppingList)
      let carts = deepClone(this.carts)
      const shoppingCarts = this.shoppingList.map(item => item.class_attend_id)
      carts = carts.filter(item => !shoppingCarts.includes(item)) //购物车存储
      _createOrder({ result: order, notShowLoading: true }).then(res => {
        this.$store.dispatch('setCarts', carts)
        setTimeout(() => {
          if (!this.ifConnectOrder) {
            // socket非正常状态
            uni.hideLoading()
            this.globalNavigateTo('order', { type: 1 })
          }
          this.payable = false
          this.$store.dispatch('setConnect', false)
        }, 3000)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/common/css/mixin.scss';
.scroll-main {
  margin-top: 64px;
  padding: 20rpx;
}
.cu-card {
  .cu-item {
    margin-top: 10rpx;
    padding: 20rpx;
    margin: 0;
  }
}
.card-header {
  padding-bottom: 10px;
  @include title(10px, 18px);
}
.card {
  &-title {
    font-size: 16px;
  }
  &-image {
    width: 35vw;
    height: 35vw;
    border-radius: 10rpx;
  }
  &-label {
    color: #999;
  }
  &-text {
    color: #333;
  }
}
.card-bottom {
  text-align: right;
}
.static {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  background: #fff;
  height: 70px;
  align-items: center;
  padding: 0 0.8rem;
  justify-content: space-between;
  &-price {
    font-size: 14px;
  }
  &-choose {
    color: #666;
    width: calc(100vw - 200px);
  }
}
</style>
