<template>
  <view class="xd-store-cart" v-if="dataList.length > 0">
    <view
      class="xd-store-cart__item"
      v-for="(item,index) in dataList"
      :key="index"
    >
      <view class="xd-store-cart__store">
        <view class="xd-store-cart__store-radio">
          <xd-radio
            size="mini"
            :color="uiColor"
            v-model="item.shop_selected"
            @change="handleChangeToAll(item)"
          ></xd-radio>
        </view>
        <view class="xd-store-cart__store-name">{{item.shop_name}}</view>
        <view class="xd-store-cart__store-line" :style="{background: $mainColor}"></view>
      </view>
      <view class="xd-store-cart__products">
        <uni-swipe-action>
          <uni-swipe-action-item
            :right-options="options"
            @click="(e)=>{bindClick(e,product,item,idx,index)}"
            @change="swipeChange(product,idx)"
            v-for="(product,idx) in item['products']"
            :key="product.key"
          >
            <view class="xd-store-cart__products-item">
              <view class="xd-store-cart__products-item-radio">
                <xd-radio
                  :color="uiColor"
                  :disabled="!(product['status'] === status)"
                  @change="handleProductChange(item)"
                  size="mini"
                  v-model="product.checked"
                ></xd-radio>
              </view>
              <view
                class="xd-store-cart__products-item-icon"
                @click="toDetial(product,item)"
                :style="{width: productWidth + 'rpx', height: productHeight + 'rpx'}"
              >
                <xd-image
                  mode="scaleToFill"
                  :width="productWidth"
                  :height="productHeight"
                  :image="product['thumb']"
                ></xd-image>
                <view
                  v-if="product['status'] !== status && product['msg']"
                  class="xd-store-cart__products-item-icon-tips"
                >
                  <view>{{product['msg']}}</view>
                </view>
              </view>
              <view
                class="xd-store-cart__products-item-body"
                @click="toDetial(product,item)"
              >
                <view class="xd-store-cart__products-item-body-name" >{{product['product_name']}}</view>
                <view class="xd-store-cart__products-item-body-sku">{{product['product_sku_text']}}</view>
                <view class="xd-store-cart__products-item-body-price">
                  <xd-unit :price="getProductPrice(product['price'])" unit="点" :iocn-size="0.4"></xd-unit>
                </view>
              </view>
              <view class="xd-store-cart__products-item-number">
                <xd-number
                  :disabled="product['status'] !== status"
                  @change="(value)=>{handleAddChange(product, idx , item, index,value)}"
                  :min="min"
                  :max="max"
                  v-model="product['num']"
                ></xd-number>
              </view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <view v-if="0" class="xd-store-cart__btn">
        <view>不含运费</view>
        <view>合计：</view>
        <view>
          <xd-unit :price="getProductPrice(item['totalPrice'])" :font-size="36" unit="点" :iocn-size=".5"></xd-unit>
        </view>
        <view>
          <xd-button btn-type="primary" radius="18rpx" @click="toConfirm(item)" size="mini">结算</xd-button>
        </view>
        <view class="xd-store-cart__btn-line" :style="{background: $mainColor}"></view>
      </view>
    </view>
  </view>
</template>

<script>
  import XdRadio from "@/components/XdRadio/XdRadio";
  import XdNumber from "@/components/XdNumber/XdNumber";
  import xdImage from "@/components/XdImage/XdImage";
  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 XdImage from "@/components/XdImage/XdImage";

  /**
   * @description 带店铺商品信息 (XdCartList)
   * @property radioColor {String} 选中按钮颜色值 默认：$mainColor
   * @property isCannelBtn {Boolean} 滑动显示按钮 默认：65%
   * @property confirmText {String} 确认按钮文本 默认：删除
   * @property isAll {String} 是否全选 默认：true
   * @property productWidth {Number} 产品图宽度 默认：180  单位：rpx
   * @property productHeight {Number} 产品图高度 默认：138  单位：rpx
   * @property min {Number} 购物车购买最小数量  默认：1
   * @property max {Number} 购物车购买最大数量  默认：10
   *
   * @event {Function} onSelect    选中商品事件
   * @event {Function} onCurtRemove    滑选删除事件
   * @event {Function} onCurtSetNumber    重置数量事件
   * @event {Function} onCartList   获取购物车列表数据
   * @event {onPay} onPay  点击结算按钮事件
   *
   * @method {Function} setIsAll    设置全选/取消方法（this.$refs['xd-store-cart'].setIsAll(status);
   */

  export default {
    name: "XdCartList",
    components: {
      XdImage,
      XdButton,
      XdMore,
      XdUnit,
      xdImage,
      XdNumber,
      XdRadio,
      UniSwipeActionItem,
      UniSwipeAction
    },
    props:{
      radioColor: {
        type: String,
        default: '',
      },
      confirmText:{
        type: String,
        default: ''
      },
      isCannelBtn: {
        type: Boolean,
        default: false,
      },
      isAll: {
        type: Boolean,
        default: true,
      },
      productWidth: {
        type: Number,
        default: 180
      },
      productHeight: {
        type: Number,
        default: 138
      },
      min: {
        type: Number,
        default: 1,
      },
      max: {
        type: Number,
        default: 10,
      },
    },

    data(){
      return {
        status: 1, //商品在线
        uiColor: '', //主色调
        options: [
          {text: '取消', type: 'cannel', style: {backgroundColor: '#ccc', padding: '0 30rpx'}},
          {text: '删除', type: 'confirm', style: {backgroundColor: 'red'}}
        ],
        storeTestSourceDataList: [
          {
            "shop_id": 3389,
            "shop_name": "\u5fa1\u8776\u574a(\u516c\u660e\u5e97)(\u5149\u660e\u65b0)",
            "shop_icon": "http:\/\/image.58yuecai.com\/img\/202008250\/4.jpg?x-oss-process=style\/200_200",
            "products": [
              {
                "product_uuid": "759255d2-66db-11eb-9776-ae2a2986c9fc",
                "product_id": 6935,
                "product_sku": 16017,
                "product_sku_text": "1\u78c5\n\t",
                "product_name": "\u840c\u5ba0\u5154\u5154\u840c\u5ba0\u5154\u5154\u840c\u5ba0\u5154\u5154\u840c\u5ba0\u5154\u5154",
                "thumb": "http:\/\/image.58yuecai.com\/img\/20200811\/254.jpg?x-oss-process=style\/200_200",
                "price": 138.13,
                "status": 0, //商品是否已下架 1=>正常 0=>异常
                'msg': '补货中', //补货中 已下架，
                "num": 1
              },
              {
                "product_uuid": "7592564a-66db-11eb-b2e4-ae2a2986c9fc",
                "product_id": 6936,
                "product_sku": 16020,
                "product_sku_text": "1\u78c5\n\t",
                "product_name": "\u5bff\u6bd4\u5357\u5c71",
                "thumb": "http:\/\/image.58yuecai.com\/img\/20200811\/271.jpg?x-oss-process=style\/200_200",
                "price": 13800,
                "status": 0, //商品是否已下架
                'msg': '补货中', //补货中 已下架，
                "num": 1
              }
            ]
          },
          {
            "shop_id": 1591,
            "shop_name": "\u5e78\u798f\u897f\u997c\u5eca\u574a\u5e97",
            "shop_icon": "https:\/\/jfbcake.oss-cn-beijing.aliyuncs.com\/uploads\/20200826\/733372b7f9022ce6c127ffbe03c54cb5.jpg?x-oss-process=style\/200_200",
            "products": [
              {
                "product_uuid": "e80e5fc8-ec26-11ea-9303-fabb3051d9e2",
                "product_id": 2929,
                "product_sku": 5693,
                "product_sku_text": "8\u82f1\u5bf8",
                "product_name": "\u51b0\u8bed\u7425\u73c0",
                "thumb": "https:\/\/jfbcake.oss-cn-beijing.aliyuncs.com\/uploads\/20200709\/d924c414e7d57a1cb9e1e1109f8a83c7.jpg?x-oss-process=style\/200_200",
                "price": 12900,
                "status": 0,
                'msg': '补货中', //补货中 已下架，
                "num": 1
              },
              {
                "product_uuid": "0aaac314-ec27-11ea-bc14-fabb3051d9e2",
                "product_id": 2930,
                "product_sku": 5694,
                "product_sku_text": "1\u78c5",
                "product_name": "\u8292\u8292\u590f\u65e5",
                "thumb": "https:\/\/jfbcake.oss-cn-beijing.aliyuncs.com\/uploads\/20200709\/e8762830c4914cb0fb698de13fff32a0.jpg?x-oss-process=style\/200_200",
                "price": 12900,
                "status": 1,
                "num": 1
              }
            ],
          },
        ], //测试数据
        dataList:[], //列表数据
      }
    },
    created(){
      this.uiColor = this.$mainColor;
      if (this.radioColor) {
        this.uiColor = this.radioColor;
      }

      //设置背景色
      let tempOptions = [];
      this.options.map((item)=>{
        if(!this.isCannelBtn && item.type === 'cannel')  {
          return;
        }
        if(item.type === 'confirm') {
          if(this.confirmText) {
            item['text'] = this.confirmText;
          }
          tempOptions.push({...item, style: {backgroundColor: this.uiColor}}) ;
        }else{
          tempOptions.push(item);
        }
      });
      this.options = tempOptions;

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

    },
    methods:{
      /**
       * @description 获取商品价格（价格为整数）比如：5.32 = 532
       */
      getProductPrice(price){
        return this.$xdUniHelper.divisionFloatNumber(price, 100);
      },

      /**
       * @description 设置全选操作
       */
      setIsAll(value){
        let list = [];
        this.dataList.map((item) => {
          let products = [];
          item['shop_selected'] = value;
          item.products.map((it) => {
            if (it['status'] === this.status) {
              it['checked'] = value;
            }
            products.push(it);
          });
          let temp = {...item, products};
          this.resComputedPrice(temp)
          list.push(temp);
        });
        this.dataList = list;
        this.computedInit();
      },

      /**
       * @description 初始化数据
       * @param list
       */
      init(list) {
        let data = list || this.$xdUniHelper.cloneDeep(this.storeTestSourceDataList);
        let temp = [];
        try {
          data.map((item, i) => {
            let tempProduct = [];
            if (!item['shop_id']) {
              throw  new Error(`list[${i}]['shop_id] is require`);
            }
            if (!item['shop_name']) {
              throw  new Error(`list[${i}]['shop_name'] is require`);
            }
            if (!item['products']) {
              throw  new Error(`list[${i}]['products'] is require`);
            }
            let totalPrice = 0;
            let shop_selected = [];
            let shop_able = [];
            item.products.map((product, index) => {
              if (!product['product_uuid']) {
                throw  new Error(`list[${i}]['products'][${index}]['product_uuid'] is require`);
              }
              if (!product['product_id']) {
                throw  new Error(`list[${i}]['products'][${index}]['product_id'] is require`);
              }
              if (!product['product_name']) {
                throw  new Error(`list[${i}]['products'][${index}]['product_name'] is require`);
              }

              //设置是否选中
              let check = this.isAll;
              if (product.check) check = product.check;
              if (product['status'] !== this.status) {
                check = false;
              }
              if(product['status'] === this.status) shop_able.push(true)

              if (check) shop_selected.push(true);

              //计算商品小计
              if(check && product['status'] === this.status) {
                totalPrice = this.$xdUniHelper.addFloatNumber(
                  totalPrice,
                  this.$xdUniHelper.multiplyFloatNumber(product['price'], product['num'])
                );
              }

              tempProduct.push({
                ...product,
                old_num: product['num'],
                key:  this.$xdUniHelper.randomChar(20),
                checked: check
              });
            });
            if(this.isAll) {
              temp.push({
                ...item,
                shop_selected: shop_selected.length === shop_able.length,
                products: tempProduct,
                totalPrice
              })
            }
            else {
              temp.push({
                ...item,
                shop_selected: shop_selected.length === shop_able.length && this.isAll,
                products: tempProduct,
                totalPrice
              })
            }

          });
          this.dataList = temp;
          console.log('List format',this.dataList);
          this.computedInit();
        } catch (e) {
          console.error(e);
          console.log('List format：', this.storeTestSourceDataList);
          this.dataList = [];
          this.computedInit();
        }
      },

      computedInit(){
        let totalPrice = 0;
        let selectProduct = [];
        let countNum = 0;
        let totalNum = 0;
        let isAll = true;
        this.dataList.map((item)=>{
          let products = [];
          if(!item.shop_selected) isAll = false;
          item.products.map((it)=>{
            if(it.checked) {
              products.push(it);
              countNum++;
              totalNum = totalNum + it.num;
            }
          });
          let temp = {...item, products: products};
          totalPrice = this.$xdUniHelper.addFloatNumber(totalPrice, item.totalPrice);

          //店铺有选中的商品
          if(products.length > 0) {
            selectProduct.push(temp);
          }
        });
        this.$emit('onSelect', {totalPrice, selectProduct, countNum, totalNum, isAll});
      },

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

      /**
       * @description 设置购物车数量
       * @param product 商品对象
       * @param idx 商品对象所在位置
       * @param item 门店对象
       * @param index 门店所在位置
       * @param value 购买数量
       */
      handleAddChange(product, idx, item, index , value){
        if(value === ''){
          console.log('handleAddChange', JSON.stringify(product))
          let tempProduct = this.$xdUniHelper.cloneDeep(product);
          let tempItem = this.$xdUniHelper.cloneDeep(item);
          tempProduct['num'] = tempProduct['old_num'];
          tempProduct['key'] = this.$xdUniHelper.randomChar(20);
          tempItem.products.splice(idx, 1, tempProduct);
          this.dataList.splice(index, 1, tempItem);
          this.dataList = this.$xdUniHelper.cloneDeep(this.dataList);
          console.log('handleAddChange', JSON.stringify(this.dataList))
          this.resComputedPrice(tempItem);
          return
        }
        console.log(product, idx, item, index, this.dataList);
        this.$emit('onCurtSetNumber', product, item, (status) => {
          let tempProduct = this.$xdUniHelper.cloneDeep(product);
          let tempItem = this.$xdUniHelper.cloneDeep(item);
          if(status === 1) {
            tempProduct['old_num'] = tempProduct['num'];
          }
          if(status === 2) {
            tempProduct['num'] = tempProduct['old_num'];
          }
          tempItem.products.splice(idx,1, tempProduct);
          this.dataList.splice(index,1, tempItem);
          this.resComputedPrice(tempItem);
        });
      },

      /**
       * @description 获取门店下正常商品数量
       */
      getStatusEqOneLen(item){
        let temp = this.$xdUniHelper.cloneDeep(item);
        let tempProducts = [];
        temp['products'].map((value) => {
          if (value.status === this.status) {
            tempProducts.push(value);
          }
        });

        return tempProducts.length;
      },

      /**
       * @description 确认订单
       */
      toConfirm(item){
        let temp = this.$xdUniHelper.cloneDeep(item);
        let tempProducts = [];
        temp['products'].map((value)=>{
          if(value.checked) {
            tempProducts.push(value);
          }
        });
        temp['products'] = tempProducts;
        this.$emit('onPay', temp)
      },

      /**
       * @description 删除购物车
       * @param product 产品对象
       * @param item 店铺对象
       * @param index 门店索引值
       * @param idx 商品索引值
       */
      removeCartProduct(product, item , idx, index){
        this.$emit('onCurtRemove', product, item , ()=>{
          item['products'].splice(idx,1);
          //当门店无购物车商品信息，直接删除门店信息
          if(item['products'].length === 0) {
            this.dataList.splice(index,1);
            this.resComputedPrice(item);
            return;
          }
          this.resComputedPrice(item);
        });
      },
      bindClick(e, product, item, idx, index) {
        if (e.position === 'right') {
          console.log('removeCartProduct', product, item, idx , index);
          this.removeCartProduct(product, item, idx, index);
        }
      },
      swipeChange(e, index) {
      },

      /**
       * @description 重新计算门店小计
       * @param item 店铺对象
       */
      resComputedPrice(item){
        let totalPrice = 0;
        item['products'].map(value => {
          if (value['status'] === this.status && value['checked']) {
            totalPrice = this.$xdUniHelper.addFloatNumber(
              totalPrice,
              this.$xdUniHelper.multiplyFloatNumber(value['price'], value['num'])
            );
          }
        });
        item['totalPrice'] = totalPrice;
        this.computedInit();
      },

      /**
       * @description 选中商品信息
       * @param item 店铺对象
       */
      handleProductChange(item){
        let len = this.getStatusEqOneLen(item); //可选择商品数量
        let selected = 0; //已选中
        let select = 0; //未选中
        item['products'].map((value)=>{
          if(value.status === this.status) {
            if (value.checked) selected++;
            else select++;
          }
        });

        if(selected === len) {
          item.shop_selected = true;
        }
        else{
          item.shop_selected = false;

        }

        this.resComputedPrice(item);
      },


      /**
       * @description 门店数据全选/取消
       * @param item 门店数据对象
       */
      handleChangeToAll(item){
        console.log('handleChangeToAll', item);
        item.products.map((value)=>{
          if(value.status === this.status) {
            value.checked = item.shop_selected;
          }
        });
        this.resComputedPrice(item);
      },

      /**
       * @description 查看产品详情事件
       * @param item
       * @param product
       */
      toDetial(product, item){
        this.$emit('onToDetail', {item, product})
      }

    },
  }

</script>

<style scoped lang="less">
  /deep/ .uni-swipe_button-group {
    & > view {
      margin-left: unit(15,rpx);
    }
  }

  .xd-store-cart {
    padding: 0;
    box-sizing: border-box;

    &__item {
      background: #fff;
      border-radius: unit(10, rpx);
      margin-bottom: unit(20,rpx);
      padding: unit(19,rpx);
      box-sizing: border-box;
    }

    &__store {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height: unit(70,rpx);
      font-size: @xd-font-size-base;
      position: relative;
      padding-bottom: unit(10,rpx);
      margin-bottom: unit(10,rpx);

      &-radio {
        margin-right: unit(10,rpx);
        &-body {
          width: unit(40,rpx);
          height: unit(40, rpx);
          display: flex;
          justify-content: center;
          align-items: center;

          /deep/ .uni-radio-input,
          /deep/ .uni-radio-wrapper {
            width: unit(32, rpx);
            height: unit(32, rpx);
            margin: 0;
          }

          /deep/ .uni-radio-wrapper {
            display: flex;
            justify-content: center;
            align-items: center;
            width: unit(40, rpx);
            height: unit(40, rpx);
          }
        }
      }

      &-name {
        .uni-cut(1, 70);
        line-height: unit(70,rpx);
        font-size: @xd-font-size-lg - 2;
      }

      &-line {
        height: 1px;
        opacity: .2;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
      }

    }

    &__products {
      &-item {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        position: relative;
        margin-top: unit(19, rpx);
        margin-bottom: unit(10,rpx);

        /deep/ .xd-number__label {
          display: none;
        }

        &-radio {
          margin-right: unit(19,rpx);
          flex-shrink: 0;
        }

        &-icon {
          margin-right: unit(19, rpx);
          flex-shrink: 0;
          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(120,rpx);
            width: unit(120,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));
            }
          }

          /deep/ .xd-logo {
            border-radius: unit(10,rpx);
            overflow: hidden;
          }
        }

        &-body {
          flex: 1;
          width: 0;

          &.disabled {
            opacity: 0.4;
          }

          &-name {
            font-size: @xd-font-size-lg - 2;
            .uni-cut(1, 36);
          }
          &-sku {
            font-size: @xd-font-size-base;
            padding: unit(10,rpx) 0;
            color: @xd-text-color-grey;


          }
        }

        &-number {
          position: absolute;
          bottom: 0;
          right: 0;
        }
      }
    }

    &__btn {
      margin-top: unit(19,rpx);
      padding-top: unit(30,rpx);
      position: relative;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-bottom: unit(10,rpx);

      view:first-child {
        font-size: @xd-font-size-base;
        color: @xd-text-color-grey;
        margin-right: unit(10,rpx);
      }

      view:nth-child(2) {
        font-size: @xd-font-size-lg;
      }

      view:nth-child(3) {
        margin-right: unit(20,rpx);
      }

      &-line {
        height: 1px;
        opacity: .2;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
      }
    }
  }
</style>
