<template>
  <view
    :style="{
      paddingBottom: defaultFooterHeight + 'rpx'
    }"
  >
    <view
      class="xd-store-cart"
      v-if="dataList.length > 0 && uiOptions !== null"
    >
      <uni-swipe-action>
        <uni-swipe-action-item
          @click="(e)=>{bindClick(e,item,index)}"
          @change="swipeChange(item,index)"
          :right-options="uiOptions"
          v-for="(item,index) in dataList"
          :key="item.key"
        >
          <view class="xd-store-cart__item">
            <view class="xd-store-cart__item-radio">
              <xd-radio
                :disabled="(item['stock'] === '0' || !item['stock']) || (item['status'] !== undefined && item['status'] !== status)"
                @change="(status)=>{handleSelectToItem(item,index, status)}"
                :color="uiRadioColor"
                size="mini"
                v-model="item.check"></xd-radio>
            </view>
            <view
              class="xd-store-cart__item-image"
              @click="toCartDetial(item)"
              :style="{width: productWidth + 'rpx', height: productHeight + 'rpx'}"
            >
              <image :src="item['thumb']"></image>
              <view
                v-if="item['status'] !== status && item['msg']"
                class="xd-store-cart__item-image-tips"
              >
                <view>{{item['msg']}}</view>
              </view>
            </view>
            <view class="xd-store-cart__item-right" :style="{height: productHeight + 'rpx' }">
              <view class="xd-store-cart__item-right-title" @click="toCartDetial(item)">{{item['product_name']}}</view>
              <view class="xd-store-cart__item-right-bottom">
                <xd-unit :price="item['sale_price']"></xd-unit>
                <xd-number
                  :min="0"
                  v-if="!(item['stock'] === '0' || !item['stock'])"
                  v-model="item.number"
                  :width="60"
                  @change="(res, type)=>{handleUpdateChange(item, index , res, type)}"
                ></xd-number>
              </view>
            </view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>
    <view class="no-data" v-if="uiOptions !== null && dataList.length === 0">{{noData}}</view>
    <xd-more color="#333" v-if="idRecommend">
      <view class="xd-store-cart-tips">
        <view>
          <xd-font-icon icon="icontesetuijian" size="40" :color="$mainColor"></xd-font-icon>
        </view>
        <view>为您推荐</view>
      </view>
    </xd-more>
    <view class="xd-store-recommend" v-if="idRecommend">
      <slot>
        <view class="xd-store-recommend-left" v-if="recommendLeftList.length > 0">
          <view v-for="(itemL,idxL) in recommendLeftList" :key="idxL">
            <xd-shop-item @onToProductDetail="handleToProductDetail" :item="itemL"></xd-shop-item>
          </view>
        </view>
        <view class="xd-store-recommend-right" v-if="recommendRightList.length > 0">
          <view v-for="(itemR,idxR) in recommendRightList" :key="idxR">
            <xd-shop-item @onToProductDetail="handleToProductDetail" :item="itemR"></xd-shop-item>
          </view>
        </view>
      </slot>
    </view>
    <view
      class="xd-store-cart-btn"
      v-if="totalPrice !== null && totalProductCount !== null"
      :style="{
        bottom: bottom + 'px',
        height: defaultFooterHeight + 'rpx'
      }"
    >
      <view>
        <xd-radio
          size="mini"
          :color="uiRadioColor"
          v-model="uiIsAll"
          @change="handleSelectToAll"
        ></xd-radio>
        <view>全选</view>
      </view>
      <view>
        <text>合计：</text>
        <view>
          <xd-unit color="#333" :price="totalPrice"></xd-unit>
        </view>
      </view>
      <view>
        <xd-button
          :disabled="toPayStatus"
          type="primary"
          size="mini"
          @click="toConfirm"
        >去结算({{totalProductCount}})</xd-button>
      </view>
    </view>
  </view>
</template>

<script>
  import XdRadio from "@/components/XdRadio/XdRadio";
  import XdNumber from "@/components/XdNumber/XdNumber";
  import XdUnit from "@/components/XdUnit/XdUnit";
  import UniSwipeActionItem from "@/components/swipeActionItem/UniSwipeActionItem";
  import UniSwipeAction from "@/components/swipeAction/UniSwipeAction";
  import XdMore from "@/components/XdMore/XdMore";
  import XdButton from "@/components/XdButton/XdButton";
  import XdFontIcon from "@/components/XdFontIcon/XdFontIcon";
  import XdStoreItem from "@/dome/components/XdStoreItem/XdStoreItem";
  import storage from "@/common/storage";

  /**
   * @description 带店铺商品信息 (XdCartList)
   * @property radioColor {String} 选中按钮颜色值 默认：$mainColor
   * @property defaultFooterHeight {Number} 底部去结算所在高度 默认：100 单位:rpx
   * @property options {Object} 左滑动块选项配置 默认：{text: '收藏', type: 'collect', style: {backgroundColor: 'orange', padding: '0 30rpx'}},
   * @property isAll {String} 是否全选 默认：true
   * @property noData {String} 无数据显示文案 默认：购物车暂无商品
   * @property idRecommend { Boolean } 是否显示推荐列表 默认：true
   * @property productWidth {Number} 产品图宽度 默认：240  单位：rpx
   * @property productHeight {Number} 产品图高度 默认：240  单位：rpx
   *
   * @event {Function} onCartRemove    滑选删除事件
   * @event {Function} onCartUpdateNumber    重置数量事件
   * @event {Function} onCartList   获取购物车列表数据
   * @event {Function} onPay  点击结算按钮事件
   * @event {Function} onToCartDetail 点击购物车列表中商品事件
   * @event {Function} onRecommendList 获取推荐商品列表事件
   * @event {Function} onToProductDetail  点击推荐商品列表中商品事件
   *
   * @method {Function} setIsAll    设置全选/取消方法（this.$refs['xd-store-cart'].setIsAll(status);
   */

  export default {
    name: "XdCartNoStoreList",
    components: {
      XdStoreItem,
      XdFontIcon,
      XdButton,
      XdMore,
      XdUnit,
      XdNumber,
      XdRadio,
      UniSwipeActionItem,
      UniSwipeAction
    },
    props:{
      radioColor: {
        type: String,
        default: '',
      },

      defaultFooterHeight: {
        type: Number,
        default: 120, //底部tabber高度 单位rpx
      },

      options: {
        type: Array,
        default(){
          return [
            //格式（text:文案,type: 按钮类型, style: 按钮样式）
            {text: '收藏', type: 'collect', style: {backgroundColor: 'orange', padding: '0 30rpx'}},
          ];
        }
      },

      //是否为全选
      isAll: {
        type: Boolean,
        default: false,
      },

      //无购物车数据提示文案
      noData: {
        type: String,
        default: '购物车暂无商品'
      },


      //是否显示推荐商品数据
      idRecommend: {
        type: Boolean,
        default: true,
      },

      productWidth: {
        type: Number,
        default: 240
      },
      productHeight: {
        type: Number,
        default: 240
      },

    },
    computed:{
      toPayStatus(){
        return this.totalPrice <= 0 || this.totalProductCount <= 0;
      },
    },
    data(){
      return {
        status: 1,
        uiRadioColor: null, //选中框主色调
        paddingBottom: 0,
        bottom: 0, //支付按钮底部距离
        uiOptions: null,

        swipeClickTime: null, //防止多次点击
        uiIsAll: null, //是否为全选
        totalPrice: null, //合计总价
        totalProductCount: null, //共计N件商品
        totalProductTypeCount: null,//共计N种商品

        //购物车数据格式
        cartTestData: [
          {
            "thumb": "https:\/\/jfb-public-images.oss-cn-qingdao.aliyuncs.com\/20210119153621543.jpg?x-oss-process=style\/200_200",
            "product_name": "\u8d1d\u87ba\u6865 \u67f3\u5dde\u87ba\u86f3\u7c89\u666e\u901a\u88c5 330g*5\u5305",
            "sale_price": 55,
            "number": 2,
            "id": 251928,
            'stock': '0',
            'check': false,
            "status": 0, //商品是否已下架
            'msg': '补货中', //补货中 已下架，
          }, {
            "thumb": "https:\/\/jfb-public-images.oss-cn-qingdao.aliyuncs.com\/20210119151849615.jpg?x-oss-process=style\/200_200",
            "product_name": "JIAJIA\/\u52a0\u52a0 \u8c03\u5473\u54c1\u7ec4\u5408C\u6b3e",
            "sale_price": 47,
            "number": 3,
            "id": 251906,
            'stock': 10,
            'check': false
          }
        ],

        //购物车数据列表
        dataList:[],

        //推荐测试数据
        recommendTestData:[
          {
            "id": "1409469",
            "product_name": "\u8d1d\u87ba\u6865 \u67f3\u5dde\u87ba\u86f3\u7c89\u666e\u901a\u88c5 330g*5\u5305",
            "sale_price": 55,
            "thumb": "https:\/\/jfb-public-images.oss-cn-qingdao.aliyuncs.com\/20210119153621543.jpg?x-oss-process=style\/200_200",
            "hot": "1",
            "newon": "2"
          }, {
            "id": "1409459",
            "product_name": "JIAJIA\/\u52a0\u52a0 \u8c03\u5473\u54c1\u7ec4\u5408C\u6b3e",
            "sale_price": 47,
            "thumb": "https:\/\/jfb-public-images.oss-cn-qingdao.aliyuncs.com\/20210119151849615.jpg?x-oss-process=style\/200_200",
            "hot": "2",
            "newon": "2"
          }, {
            "id": "1409458",
            "product_name": "JIAJIA\/\u52a0\u52a0 \u8c03\u5473\u54c1\u7ec4\u5408B\u6b3e",
            "sale_price": 47,
            "thumb": "https:\/\/jfb-public-images.oss-cn-qingdao.aliyuncs.com\/20210119151734654.jpg?x-oss-process=style\/200_200",
            "hot": "2",
            "newon": "2"
          }, {
            "id": "1409457",
            "product_name": "JIAJIA\/\u52a0\u52a0 \u8c03\u5473\u54c1\u7ec4\u5408A\u6b3e",
            "sale_price": 57,
            "thumb": "https:\/\/jfb-public-images.oss-cn-qingdao.aliyuncs.com\/20210119151624114.jpg?x-oss-process=style\/200_200",
            "hot": "2",
            "newon": "1"
          }
        ],
        recommendRightList: [],
        recommendLeftList: [],

      }
    },
    created(){
      this.uiIsAll = this.isAll;
      this.uiRadioColor = this.$mainColor;
      if (this.radioColor) {
        this.uiRadioColor = this.radioColor;
      }

      //滑块显示按钮（已设置默认删除）
      this.uiOptions = this.options
        .concat([{text: '删除', type: 'del', system: true, style: {backgroundColor: 'red'}}]);

      this.paddingBottom = storage.get('xd-layout') ? storage.get('xd-layout')['safeHeight'] : 0;
      this.bottom = this.$rpxNum * this.defaultFooterHeight + this.paddingBottom;

      //获取购物车列表数据
      this.getList();

      //显示推荐数据
      if(this.idRecommend) {
        this.getRecommendList();
      }


    },
    methods:{

      /**
       * @description 获取购物车已选中商品
       */
      getSelectData(){
        let temp = [];
        this.$xdUniHelper.cloneDeep(this.dataList).map(item=>{
          if(item.check) temp.push(item);
        });
        return temp;
      },

      /**
       * @description 初始化数据
       * @param list
       */
      init(list) {
        let temp = [];
        try {
          if(this.$xdUniHelper.checkVarType(list) !== 'array') {
            throw new Error('购物车列表数据格式为：Array');
          }else {
            list.map(item => {
              let check = null;
              if(item.check) check = item.check;
              else check = this.isAll;

              if(item['stock'] === '0' || !item['stock'] || (item['status'] !== undefined && item['status'] !== status)) {
                check = false;
              }
              temp.push({
                ...item,
                check: check,
                key: this.$xdUniHelper.randomChar(30) ,
                oldNumber: item['number'],
              });
            });

            //计算产品各种总数
            this.setTotal(temp);
            this.dataList = this.$xdUniHelper.cloneDeep(temp)
          }
        } catch (e) {
          console.error(e);
          console.log('List format：', this.cartTestData);
          this.dataList = [];
        }

      },

      /**
       * @description 获取购物车列表数据
       */
      getList(){
        //this.$xdShowLoading({});
        this.$emit('onCartList', (list) => {
          //this.$xdHideLoading();
          if(list === null) {
            this.init(this.$xdUniHelper.cloneDeep(this.cartTestData))
          }else{
            this.init(list)
          }
        });
      },

      /**
       * @description 初始化数据
       * @param list
       */
      initRecommend(list) {
        if(list.length === 0) {
          this.recommendRightList = [];
          this.recommendLeftList = [];
          return
        }
        let recommendRightList = [];
        let recommendLeftList = [];
        list.map((item,index)=>{
          if(index%2 === 0) recommendLeftList.push(item);
          else recommendRightList.push(item)
        });
        this.recommendRightList = recommendRightList;
        this.recommendLeftList = recommendLeftList;

        console.log('initRecommend',this.recommendRightList, this.recommendLeftList, list)
      },

      /**
       * @description 获取推荐数据列表
       */
      getRecommendList() {
        console.log('initRecommend')
        this.$emit('onRecommendList', (list) => {
          console.log('initRecommend', list)
          if (list === null) {
            this.initRecommend(this.$xdUniHelper.cloneDeep(this.recommendTestData))
          } else {
            this.initRecommend(list)
          }
        });
      },

      /**
       * 设置各种总是设置
       */
      setTotal(list){
        let totalPrice = 0;
        let totalProductCount = 0;
        this.totalProductTypeCount = list.length;
        let all = true;
        list.map(item => {
          if(item.check) {
            totalProductCount += item.number;
            let price = this.$xdUniHelper.multiplyFloatNumber(item.number, item.sale_price);
            totalPrice = this.$xdUniHelper.addFloatNumber(price, totalPrice);
          }
          if(!item.check) all = false;
        });
        this.totalPrice = totalPrice;
        this.totalProductCount = totalProductCount;
        this.uiIsAll = all;
        if(this.totalProductTypeCount === 0) this.uiIsAll = false;
        this.$emit('update:count', this.totalProductTypeCount)
      },

      /**
       * @description 设置购物车数量
       * @param item 当前操作购物车对象
       * @param index 操作对象所在购物车位置
       * @param number 购物车对象更新数量
       * @param type 操作类型 add=>增加 cut=>减少
       */
      handleUpdateChange(item , index, number, type){
        this.$xdShowLoading({});
        //status 1=>更新成功 2=>更新失败
        this.$emit('onCartUpdateNumber',{item, index, number, type}, (status) => {
          let temp = this.$xdUniHelper.cloneDeep(item);
          temp['key'] = this.$xdUniHelper.randomChar(30)
          if(status === 1) {
            temp['oldNumber'] = number;
          }else{
            temp['number'] = temp['oldNumber'];
          }
          this.dataList.splice(index, 1, temp);
          this.setTotal(this.dataList);
          this.$xdHideLoading();
        });
      },

      /**
       * @description 删除购物车
       * @param item 购物车商品信息
       * @param index 购物车商品所在位置
       */
      removeCartProduct(item, index){
        this.$xdShowLoading({});
        //status 1=>删除成功 2=>删除失败
        this.$emit('onCartRemove', {item, index} , (status)=>{
          if(status === 1) {
            this.dataList.splice(index, 1);
            this.setTotal(this.dataList);
          }
          this.$xdHideLoading();
        });
      },

      /**
       * @description 点击滑动按钮时间
       * @param e 被点击按钮对象
       * @param item 店铺对象
       * @param index 门店索引值
       */
      bindClick(e, item, index) {
        if(this.swipeClickTime){
          clearTimeout(this.swipeClickTime);
          this.swipeClickTime = null;
        }
        this.swipeClickTime = setTimeout(()=>{
          //删除按钮
          if(e.position === 'right' && e.content.type === 'del' && e.content.system) {
            this.removeCartProduct(item, index);
          }
          //自定义按钮
          else{
            this.$emit('onCustomBtn', {e, item, index});
          }
          console.log(e, item, index)
        }, 100);
      },

      /**
       * @description 滑动事件
       * @param item 店铺对象
       * @param index 当前购物车位置
       */
      swipeChange(item, index) {
        this.$emit('onSwipeChange', {item, index})
      },

      /**
       * @description 购物车选中/取消商品
       * @param item 店铺对象
       * @param index 当前购物车位置
       * @param status 选中状态
       */
      handleSelectToItem(item,index, status){
        let temp = {...item, key: this.$xdUniHelper.randomChar(30), check: status};
        this.dataList.splice(index,1, temp);
        this.setTotal(this.dataList);
      },

      /**
       * @description 购物车全选/取消
       */
      handleSelectToAll(status){
        let temp = [];
        this.dataList.map(item=>{
          let check = status;
          if (item['stock'] === '0' || !item['stock']) {
            check = false;
          }
          temp.push({...item, check: check, key: this.$xdUniHelper.randomChar(30)})
        });
        this.dataList = temp;
        this.setTotal(temp);
      },

      /**
       * @description 购物车列表查看产品详情事件
       * @param item
       */
      toCartDetial(item){
        this.$emit('onToCartDetail', item)
      },

      /**
       * @description 推荐商品查看详情
       * @param item
       */
      handleToProductDetail(item){
        this.$emit('onToProductDetail', item)
      },

      /**
       * @description 确认订单
       */
      toConfirm() {
        this.$emit('onPay', {
          data: this.getSelectData(),
          ids: this.$xdUniHelper.getListKeyForValue(this.getSelectData())
        });
      },

    },
  }



</script>

<style scoped lang="less">
  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: @xd-font-size-lg;
    line-height: unit(200,rpx);
    color: #999;
  }
  .xd-store-cart {
    padding: 0;
    box-sizing: border-box;


    &__item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: unit(20,rpx);
      background: #fff;
      padding: unit(20,rpx);

      &-radio {
        flex-shrink: 0;
        padding: 0 unit(20,rpx) 0 0;
      }

      &-image {
        flex-shrink: 0;
        margin-right: unit(20,rpx);
        background: #efefef;
        box-shadow: 0 0 unit(10,rpx) rgba(0,0,0,.08);
        position: relative;

        &-tips {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          background: rgba(0, 0, 0, .4);
          color: #666;
          font-size: @xd-font-size-base;
          display: flex;
          justify-content: center;
          align-items: center;
          height: unit(200, rpx);
          width: unit(200, rpx);
          border-radius: 50%;
          overflow: hidden;
          box-shadow: rgba(0, 0, unit(10, rpx), rgba(0, 0, 0, .5));


          & > view {
            line-height: unit(40, rpx);
            width: 100%;
            text-align: center;
            color: #f8f8f8;
            text-shadow: rgba(0, 0, unit(10, rpx), rgba(0, 0, 0, .5));
          }
        }

        & > image {
          width: 100%;
          height: 100%;
        }
      }

      &-right {
        flex: 1;
        width: 0;
        position: relative;

        &-title {
          .uni-max-cut(3, 120);
          line-height: unit(40,rpx);
          font-size: @xd-font-size-base;
        }

        &-bottom {
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }
  }

  .xd-store-cart-tips {
    display: flex;
    justify-content: center;
    align-items: center;

    & > view:first-child {
      margin-right: unit(10,rpx);
    }
  }

  .xd-store-recommend {
    padding-top: unit(20,rpx);
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    & > view {
      flex: 1;
      margin-right: unit(20,rpx);
      width: 0;

      &> view {
        margin-bottom: unit(20, rpx);

        &:last-child {
          margin-bottom: 0;
        }
      }

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .xd-store-cart-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    left: 0;
    right: 0;
    background: #fff;
    padding: 0 unit(20,rpx);
    box-shadow: 0 0 unit(10,rpx) rgba(0,0,0,.08);
    z-index: 300;

    & > view {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    & > view:first-child {
      flex-shrink: 0;
      font-size: @xd-font-size-base;
      padding-right: unit(30,rpx);

      & > view:last-child {
        margin-left: unit(10,rpx);
      }
    }

    & > view:last-child {
      flex-shrink: 0;
    }

    & > view:nth-child(2) {
      flex: 1;
      width: 0;
      justify-content: flex-start;
      font-size: @xd-font-size-lg;
    }
  }
</style>

