<template>
  <view class="container">
    <!-- 购物车商品列表 -->
    <view v-if="list.length" class="cart-list">
      <view class="cart-item" v-for="(item, index) in list" :key="index">
        <view class="goods-name">
          <label class="item-radio" @click.stop="handleCheckItem(item.goods_isli)">
            <radio class="radio" color="#fa2209" :checked="inArray(item.goods_isli, checkedIds)" />
          </label>
          <view class="item-title" @click="handleGoodsList(item.username)">
            <text class="item-title-name">委托方：{{item.username}}</text>
          </view>
          <uni-icons class="item-del-inco" type="trash" size="30" @click="onClearCart(item.goods_isli)"></uni-icons>
        </view>
        <view class="item-content" @click="handleGoodsDetail(item.goods_islicode)">
          <view class="goods-image">
            <image class="image" :src="item.detail.goods_image" mode="scaleToFill"></image>
          </view>
          <view class="goods-title" @click="onTargetGoods(item.goods_id)">
            <text class="goods-title-name">{{ item.detail.goods_name }}</text>
            <text class="goods-title-content">交易方式：{{ item.detail.goods_entrust?'转让':'授权' }}</text>
            <text class="goods-title-content">购买年限：{{ item.use_years }}年</text>
            <text class="goods-title-content">单价：￥{{ item.detail.price_str }}</text>
          </view>
          <view class="item-foot">
            <view class="goods-price">
              <text>合计：</text>
              <text class="unit">￥</text>
              <text class="value">{{ item.total_money_str }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 购物车数据为空 -->
    <empty-cart v-if="!list.length" :isLoading="isLoading" :custom-style="{ padding: '180rpx 50rpx' }" tips="购物车暂无标的">
      <view slot="slot" class="empty-ipt" @click="onTargetIndex">
        <text>去首页逛逛</text>
      </view>
    </empty-cart>
    <!-- 底部操作栏 -->
    <view v-if="list.length" class="footer-fixed">
      <label class="all-radio" @click="handleCheckAll">
        <radio class="radio" color="#fa2209" :checked="checkedIds.length > 0 && checkedIds.length === list.length" />
        <text>全选</text>
      </label>
      <view class="total-info">
        <text>合计：</text>
        <view class="goods-price">
          <text class="unit">￥</text>
          <text class="value">{{ totalPrice }}</text>
        </view>
      </view>
      <view class="cart-action">
        <view class="btn-wrapper">
          <!-- dev:下面的disabled条件使用checkedIds.join方式判断 -->
          <!-- dev:通常情况下vue项目使用checkedIds.length更合理, 但是length属性在微信小程序中不起作用 -->
          <view v-if="mode == 'normal'" class="btn-item btn-main" :class="{ disabled: checkedIds.join() == '' && is_shop }" @click="handleOrder()">
            <text>去结算 {{ checkedIds.length > 0 ? `(${checkedIds.length})` : '' }}</text>
          </view>
<!--          <view v-if="mode == 'edit'" class="btn-item btn-main" :class="{ disabled: !checkedIds.length }" @click="handleDelete()">-->
<!--            <text>删除</text>-->
<!--          </view>-->
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { inArray, arrayIntersect, debounce } from '@/utils/util'
import { checkLogin, setCartTotalNum, setCartTabBadge } from '@/core/app'
import * as UserApi from '@/api/user'
import {formatAmount} from '@/api/order/comment'
import EmptyCart from '@/components/empty-cart'
import uniIcons from '../../../uni_modules/uni-icons/components/uni-icons/uni-icons'
import {createOrder, delShopCart} from "../../../api/user";

const CartIdsIndex = 'CartIds'

export default {
  components: {
    "empty-cart": EmptyCart,
    "uni-icons": uniIcons,
  },
  data() {
    return {
      inArray,
      // 正在加载
      isLoading: true,
      // 当前模式: normal正常 edit编辑
      mode: 'normal',
      // 购物车商品列表
      list: [],
      // 购物车商品总数量
      total: null,
      // 选中的商品ID记录
      checkedIds: [],
      // 选中的商品总金额
      totalPrice: '0.00',
      // 是否禁用按钮
      is_shop: false,
    }
  },
  watch: {
    // 监听选中的商品
    checkedIds: {
      handler(val) {
        // 计算合计金额
        this.onCalcTotalPrice()
        // 记录到缓存中
        uni.setStorageSync(CartIdsIndex, val)
      },
      immediate: false
    },
    // 监听购物车商品总数量
    total(val) {
      // 缓存并设置角标
      setCartTotalNum(val)
      setCartTabBadge()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(options) {
    // 获取购物车商品列表
    checkLogin() ? this.getCartList() : this.isLoading = false
    // 获取缓存中的选中记录
    this.checkedIds = uni.getStorageSync(CartIdsIndex) ? uni.getStorageSync(CartIdsIndex) : []
  },

  methods: {

    // 计算合计金额 (根据选中的商品)
    onCalcTotalPrice() {
      const app = this
      // 选中的商品记录
      const checkedList = app.list.filter(item => inArray(item.goods_isli, app.checkedIds))
      // 计算总金额
      let tempPrice = 0;
      checkedList.forEach(item => {
        // 商品单价, 为了方便计算先转换单位为分 (整数)
        const unitPrice = item.total_money * 100
        tempPrice += unitPrice
      })
      app.totalPrice = (tempPrice / 100).toFixed(2)
    },

    // 获取购物车商品列表
    getCartList() {
      const app = this
      app.isLoading = true
      let param = {
        user_isli:  uni.getStorageSync("isliCode")
      }
      UserApi.getShopCart(param)
          .then(result => {
            if (result.code == '200') {
              app.list = result.data
              app.total = result.data.length
              app.list.forEach(item => {
                item.total_money_str = formatAmount(item.total_money)
                item.detail.price_str = formatAmount(Number(item.detail.price))
              })
            }
            // 清除checkedIds中无效的ID
            app.onClearInvalidId()
          })
          .finally(() => app.isLoading = false)
    },

    // 清除checkedIds中无效的ID
    onClearInvalidId() {
      const app = this
      const listIds = app.list.map(item => item.id)
      app.checkedIds = arrayIntersect(listIds, app.checkedIds)
    },

    // 切换当前模式
    handleToggleMode() {
      this.mode = this.mode == 'normal' ? 'edit' : 'normal'
    },

    // 跳转到商品详情页
    onTargetGoods(goodsId) {
      this.$navTo('pages/goods/detail', { goodsId })
    },

    // 点击去逛逛按钮, 跳转到首页
    onTargetIndex() {
      this.$navTo('pages/index/index')
    },

    // 选中商品
    handleCheckItem(cartId) {
      const { checkedIds } = this
      const index = checkedIds.findIndex(id => id === cartId)
      index < 0 ? checkedIds.push(cartId) : checkedIds.splice(index, 1)
    },

    // 全选事件
    handleCheckAll() {
      const { checkedIds, list } = this
      this.checkedIds = checkedIds.length === list.length ? [] : list.map(item => item.goods_isli)
    },

    // 结算选中的商品
    handleOrder() {
      const app = this
      if (app.checkedIds.length) {
        let user_isli = uni.getStorageSync("isliCode")
        let userType = uni.getStorageSync("userType")
        if (user_isli) {
          if (userType === "0") {
            app.$toast('个人认证账号不能提交订单！')
          } else {

            let paramArr = {
              manyislicode: [],
              manyYears: [],
              new_shop_Name: [],
              new_userName: [],
              new_company: []
            }

            for (let attr in app.list) {
              let item = app.list[attr]
              if (inArray(item.goods_isli, app.checkedIds)) {
                paramArr.manyislicode.push(item.goods_islicode)
                paramArr.manyYears.push(item.use_years)
                //拼接撤销数据的名称
                if (item.goods_status != 1 && item.goods_status != 5) {
                  paramArr.new_shop_Name.push(item.detail.goods_name)
                }
                paramArr.new_userName.push(item.username)
                if (item.username == "北京玖扬博文文化发展有限公司" && item.detail.charges_type == "1") {
                  paramArr.new_company.push(item.username)
                }
              }
            }

            let manyislicode = paramArr.manyislicode.join(",");//购买方用户委托关联编码 用，拼接
            let manyYears = paramArr.manyYears.join(",");
            let new_shop_Name = paramArr.new_shop_Name.join(",");
            let new_userName = paramArr.new_userName.join(","); //判断是不是中国数字文化集团有限公司,国家图书馆出版社有限公司,深圳国夏文化数字科技有限公司
            let new_company = paramArr.new_company.join(","); //北京玖扬博文文化发展有限公司
            //判断是不是北京玖扬博文文化发展有限公司
            let company_Number = null;
            if (new_company.split(",").includes("北京玖扬博文文化发展有限公司")) {
              company_Number = 1;
            } else {
              company_Number = null
            }
            //判断是不是中国数字文化集团有限公司和国家图书馆出版社有限公司、深圳国夏文化数字科技有限公司
            let china_Number = null;
            if (new_userName.split(",").includes("中国数字文化集团有限公司") || new_userName.split(",").includes("国家图书馆出版社有限公司") || new_userName.split(",").includes("深圳国夏文化数字科技有限公司")) {
              china_Number = 1;
            } else {
              china_Number = null
            }
            if (company_Number == null) {
              if (china_Number == null) { //判断数据中是否有中国数字文化集团有限公司，国家图书馆出版社有限公司，深圳国夏文化数字科技有限公司 的委托数据
                if (new_shop_Name == "") {
                  app.is_shop = false
                  let data = {
                    goods_isli: manyislicode, //委托数据委托关联编码
                    is_car: 1, //1：购物车商品；2：不是购物车商品
                    use_years: manyYears, //委托数据购买使用年限
                    user_isli: user_isli //购买方用户委托关联编码
                  }
                  UserApi.createOrder(data).then(res => {
                    if (res.resultCode === "00000000") {
                      app.$success('订单提交成功')
                      // 延时2秒跳转
                      setTimeout(function () {
                        uni.navigateTo({url: "/pages/goods/payment/orderPayment?batchcode="+res.data.batchcode})
                      },1000)
                      app.getCartList();
                      app.onClearInvalidId()
                    } else {
                      app.is_shop = true
                      app.$error(res.resultMsg);
                    }
                  })
                } else {
                  app.$toast('无法购买')
                }
              } else {
                app.$toast('可议价商品暂不支持线上购买，如需议价请拨打电话:0755-88266899')
              }
            } else {
              app.$toast('如需申领使用，请拨打电话 0755-88266899')
            }
          }
        } else {
          app.$toast('账号未认证，请进行认证！')
          setTimeout(app.jumpMycertinfoUrl,3000)
        }
      } else {
        app.$toast('请选择商品！')
      }
    },

    // 跳转至认证
    jumpMycertinfoUrl () {
      uni.navigateTo({
        url:'/pages/user/mycertinfo/mycertinfo'
      })
    },

    // 标的详情
    handleGoodsDetail(gislicode) {
      // this.$toast(goodsId)
      this.$navTo('pages/goods/detail', {gislicode})
    },

    // 店铺详情
    handleGoodsList(spname) {
      // this.$toast(goodsId)
      this.$navTo("pages/goods/list?k="+spname+'&dt='+new Date().getTime())
    },

    // 删除选中的商品弹窗事件
    // 确认删除商品
    onClearCart(goods_isli) {
      const app = this
      let param = {
        user_isli: uni.getStorageSync("isliCode"),
        goods_isli: goods_isli
      }
      UserApi.delShopCart(param).then(result => {
        if (result.resultCode == '00000000') {
          app.$success("删除成功！")
          app.getCartList()
        }
      })
    }

  }
}
</script>

<style>
page {
  background: #f5f5f5;
}
</style>
<style lang="scss" scoped>

// 购物车列表
.cart-list {
  padding: 25rpx 16rpx 110rpx 16rpx;
}

.cart-item {
  background: #fff;
  border-radius: 12rpx;
  display: block;
  align-items: center;
  padding: 0rpx 16rpx 40rpx 16rpx;
  margin-bottom: 24rpx;

  .goods-name {
    width: 100%;
    height: 78rpx;
    padding: 0rpx 0rpx;

    .item-radio {
      font-size: 66rpx;

      .radio {
        transform: scale(0.76)
      }
    }

    .item-title {
      width: 80%;
      display: inline-block;
      white-space: nowrap; /* 防止文本换行 */
      overflow: hidden; /* 超出部分隐藏 */
      text-overflow: ellipsis; /* 使用省略符号 */


      .item-title-name {
        margin-left: 10rpx;
        font-size: 32rpx;
      }
    }

    .item-del-inco {
      float: right;
      margin-top: 10rpx;
    }

  }


  .item-content {
    width: 100%;
    flex: 1;
    padding-left: 24rpx;

    .goods-image {
      width: 200rpx;
      height: 200rpx;
      margin-top: 50rpx;
      display: inline-block;

      .image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
    }

    .goods-title {
      width: 66%;
      margin-top: 0rpx;
      font-size: 28rpx;
      margin-left: 20rpx;
      display: inline-block;

      .goods-title-name {
        height: 70rpx;
        margin-top: -125rpx;
        float: left;
        text-overflow: ellipsis; /* 使用省略符号 */


      }
      .goods-title-content {
        display: block;
        color: #969493;
        margin-top: 5rpx;
      }

    }


    .item-foot {
      text-align: right;

      .goods-price {
        margin-top: 40rpx;
        vertical-align: bottom;
        color: $uni-text-color-active;
        font-size: 32rpx;
      }
    }

  }
}

// 空数据按钮
.empty-ipt {
  width: 300rpx;
  margin: 0 auto;
  font-size: 28rpx;
  height: 74rpx;
  line-height: 74rpx;
  text-align: center;
  color: #fff;
  border-radius: 50rpx;
  background: linear-gradient(to right, #1c223b, #1c223b);
}

// 底部操作栏
.footer-fixed {
  display: flex;
  align-items: center;
  height: 96rpx;
  background: #fff;
  padding: 0 30rpx;
  position: fixed;
  bottom: var(--window-bottom);
  left: 0;
  right: 0;
  z-index: 11;

  .all-radio {
    width: 140rpx;
    display: flex;
    align-items: center;

    .radio {
      margin-bottom: -4rpx;
      transform: scale(0.76)
    }
  }

  .total-info {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 30rpx;

    .goods-price {
      vertical-align: bottom;
      color: #fa2209;

      .unit {
        font-size: 24rpx;
      }

      .value {
        font-size: 32rpx;
      }
    }
  }

  .cart-action {
    width: 200rpx;

    .btn-wrapper {
      height: 100%;
      display: flex;
      align-items: center;
    }

    .btn-item {
      flex: 1;
      font-size: 28rpx;
      height: 72rpx;
      line-height: 72rpx;
      text-align: center;
      color: #fff;
      border-radius: 50rpx;
    }

    // 立即购买按钮
    .btn-main {
      background: linear-gradient(to right, #1c223b, #1c223b);

      // 禁用按钮
      &.disabled {
        background: #9F9F9F;
        display: none;
      }
    }

  }

}
</style>