<!--
  @description:购物车组件
  @Modifier: haofengxian
  @routerPath: /shop/myshoppingCart
  @date: 2021-12-04 12:45
-->
<template>
  <div>
    <div class="middle_width1200 all_product">
      <span :style="{ opacity: listCopy.length > 0 ? 1 : 0 }">
        全部商品&nbsp;{{ productNum }}
      </span>
      <el-upload
        v-if="buyerType!=='03'"
        ref="upload"
        :on-success="handleSuccess"
        :limit="1"
        :show-file-list="false"
        :headers="headers"
        :action="uploadAction"
        accept=".xls,.xlsx"
        multiple
      >
        <el-button size="small" type="text" style="color:#fd6b2b">
          导入
        </el-button>
      </el-upload>
    </div>
    <div v-loading="loading" element-loading-text="拼命加载中">
      <!--表头-->
      <div v-if="listCopy.length>0" class="middle_width1200 shopping_cart_wrap">
        <ul class="ulStyle">
          <li class="ulStyle_Title cart_title">
            <p>
              <el-checkbox v-model="checked" @change="checkedAll">
                全选
              </el-checkbox>
            </p>
            <p style="text-align:center;">
              商品名称
            </p>
            <p>单价</p>
            <p>数量</p>
            <p>小计</p>
            <p class="flex_1 textac">
              操作
            </p>
          </li>
        </ul>
        <!--店铺列表-->
        <div v-for="(item,index) in listCopy" :key="index" class="shop">
          <!--店铺-->
          <div class="shop_title">
            <el-checkbox v-model="item.checked" @change="checkedShop(index)" />店铺：
            <span>{{ item.departName }}</span>
          </div>
          <!--商品列表-->
          <ul class="ulStyle">
            <li
              v-for="(chidren,chidrenIndex) in item.productsList"
              :key="chidrenIndex"
              :class="[chidren.state !==1 ?'lose_efficacy':'']"
              class="ulStyle_content"
            >
              <p>
                <!--多选框-->
                <el-checkbox
                  v-model="chidren.checked"
                  :disabled="chidren.state !==1"
                  @change="checkedChange(index)"
                />
                <span class="shop_img cursor" @click="goToDetail(chidren)">
                  <img :src="chidren.productPicture" class="goods_img">
                  <!--失效-->
                  <span v-if="chidren.state !==1" class="invalid">失效</span>
                </span>
              </p>
              <div class="goods_name_box">
                <p
                  class="goods_item_title_two goods_name"
                  :title="chidren.goodsName"
                  @click="goToDetail(chidren)"
                >
                  {{ chidren.goodsName }}
                </p>
                <p v-if="item.departName=='京东商城' && chidren.giftStatus=='2'" class="goods_item_title_two gift">
                  <span @click="getSkuGift(chidren.productCode)">查看赠品</span><span @click="removeGift(chidren.id)">删除赠品</span>
                </p>
              </div>
              <!--商品名称-->
              <p style="display:flex;flex-direction: column">
                <span>￥{{ chidren.unitPrice }}</span> <span v-if="chidren.checkResult === '01'">价格已变更</span><span v-if="chidren.checkResult === '02'">失效原因：库存不足</span><span v-if="chidren.checkResult === '03'">失效原因：已下架</span>
              </p>
              <!--单价-->
              <p class="number_chage">
                <!--数量-->
                <el-input-number
                  v-model="chidren.number"
                  :disabled="chidren.state !==1"
                  :min="1"
                  :max="9999"
                  @change="numberChage(item,index,chidrenIndex,chidren,chidren.number)"
                />
              </p>
              <!--小计-->
              <p class="subtotal" style="margin-left:0px;">
                ￥{{ chidren.number.mul(chidren.unitPrice) }}
              </p>
              <!--操作 删除-->
              <!-- <p class="delete">
                <span style="color:#00AACA" @click="getCompareInfo(chidren.compareGoodIds)">比价详情</span>
              </p> -->
              <p class="delete flex_1 textac">
                <span
                  v-if="buyerType!=='03'"
                  class="cursor iconfont icon-shanchu"
                  @click="deleteCommodity(item,index,chidrenIndex)"
                />
                <span
                  v-if="buyerType==='03'"
                  class="cursor iconfont icon-shanchu"
                  @click="falseDelete(item,index,chidren,chidrenIndex)"
                />
              </p>
            </li>
          </ul>
        </div>
        <div class="shop_footer clearfix">
          <div class="shop_footer_content clearfix">
            <div class="fl">
              <p>
                <el-checkbox v-model="checked" @change="checkedAll">
                  全选
                </el-checkbox>
              </p>
              <p class="remove_goods">
                <span v-if="buyerType!=='03'" class="cursor del" @click="deleteSeltect">删除选中商品</span>
                <span v-if="buyerType==='03'" class="cursor del" @click="falseDeleteSeltect">删除选中商品</span>
              </p>
              <p class="remove_goods">
                <span v-if="buyerType!=='03'" class="cursor" @click="deleteInvalid">移除失效商品</span>
                <span v-if="buyerType==='03'" class="cursor" @click="falseDeleteInvalid">移除失效商品</span>
              </p>
            </div>
            <div class="fr">
              <p class="selected">
                已选择
                <span class="total_price_nember">{{ selectData.length }}</span>件商品
              </p>
              <p>
                订单金额
                <span class="tax_inclusive">（ 含税 ）</span>：
              </p>
              <p>
                <span class="total_price">￥{{ formData.orderAmount.toFixed(2) }}</span>
              </p>
              <el-button class="place_order" @click="printCommodityInfo">
                打印
              </el-button>
              <el-button class="place_order" @click="submit">
                下单
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="middle_width1200 shopping_cart_wrap">
        <div class="cart_null">
          <dl>
            <dt>
              <img src="@/assets/img/shopmall/cart.png" alt>
            </dt>
            <dd>
              <p>购物车空空的哦~，去看看心仪的商品吧~</p>
              <p @click="goToHome">
                去购物 >
              </p>
            </dd>
          </dl>
        </div>
      </div>
    </div>
    <!--查看赠品-->
    <giftDetailDialog ref="giftDetail" />
    <!--比价详情-->
    <priceDetailsDialog ref="priceDetail" />
  </div>
</template>

<script>
import { deleteShoppingCart, updateNumberForCart, abandonOfGift, shopCarExport } from '@/api/shoppingmall/order'
import { download } from '@assets/js/utils'// 常用方法
import { Loading } from 'element-ui'
import { getToken } from '@/assets/js/utils/auth'
// 组件
import giftDetailDialog from './giftDetail-dialog' // 赠品详情
import priceDetailsDialog from './priceDetails-dialog' // 比价详情

export default {
  name: 'MyshoppingCart',
  components: {
    giftDetailDialog, // 赠品详情
    priceDetailsDialog // 比价详情
  },
  props: {
    // 购物车数据
    list: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 03再次购买
    buyerType: {
      type: String,
      default: ''
    },
    // 购物车loading
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      checked: false, // 是否全选
      // 已选择的商品
      selectData: [],
      // 下单总价及数量
      formData: {
        orderAmount: 0, // 总价
        ids: ''
      },
      listCopy: [],
      // 上传token
      headers: { 'X-AUTH-TOKEN': getToken() },
      // 上传Action
      uploadAction: 'importCartItems'
    }
  },
  computed: {
    // 所有商品的总数
    productNum() {
      let len = 0
      if (this.listCopy.length > 0) {
        this.listCopy.forEach(item => {
          len += item.productsList.length
        })
        return len
      }
      return 0
    }
  },
  watch: {
    'list'(val) {
      this.listCopy = val
    },
    // 多选框
    listCopy: {
      handler(val) {
        this.totalPrice()
        const selectData = []
        this.selectData = []
        // 存储已选的商品
        this.listCopy.forEach((item, index) => {
          if (item.checked) { selectData.push(item) }
          item.productsList.forEach((chidren) => {
            if (chidren.checked) {
              this.selectData.push(chidren)
            }
          })
        })
        // 判断是否全选改变状态
        if (selectData.length < 1) {
          this.checked = false
          return false
        } else if (selectData.length === val.length) {
          // this.isIndeterminate = false
          this.checked = true
          return false
        } else {
          this.checked = false
        }
      },
      deep: true
    }
  },
  created() {
    this.totalPrice()
  },
  methods: {
    // 上传
    handleSuccess(res) {
      if (res.header.ret === '0') {
        this.$message.success(res.header.msg)
      } else {
        this.$message.error(res.header.msg)
        this.$refs.upload.clearFiles()
      }
    },
    // 查看详情
    goToDetail(item) {
      this.$router.push({ path: '/shop/goodsClassDetail', query: { id: item.goodsId }})
    },
    //  计算总价
    totalPrice() {
      this.formData.orderAmount = 0// 总价
      this.listCopy.forEach((item, index) => {
        item.productsList.forEach((chidren, chidrenIndex) => {
          chidren.subTotal = chidren.unitPrice.mul(chidren.number)// 小计
          // 只计算选中的商品
          if (chidren.checked === true) {
            this.formData.orderAmount = this.formData.orderAmount.add(chidren.subTotal)// 总价
          }
        })
      })
    },
    //  商品数量改变的时候
    numberChage(item, index, chidrenIndex, chidren, num) {
      //        店铺 店铺索引   商品索引  商品数量
      if (!num) {
        chidren.number = 1
        return
      }
      // 商品数量小于一的时候直接删除
      if (num < 1) {
        this.$message({
          type: 'warning',
          message: '最小购买数量不能小于1'
        })
        return
      }
      if (num >= 9999) {
        this.$message({
          type: 'warning',
          message: '超过购买数量限制'
        })
        chidren.number = 9999
        return
      }
      chidren.totalPrice = num.mul(chidren.unitPrice)
      // 再次购买不调用接口
      if (this.buyerType !== '03') {
        updateNumberForCart(chidren).then(res => {
        }).catch(() => {
        })
      }
      // 如果该商家商品为空的时候直接删除商家
      if (item.productsList.length < 1) {
        this.listCopy.splice(index, 1)
      }
    },
    // 全选//全不选
    checkedAll() {
      this.formData.orderAmount = 0
      this.selectData = []
      this.listCopy.forEach((item, index) => {
        item.checked = this.checked
        item.productsList.forEach((chidren, chidrenIndex) => {
          chidren.checked = this.checked
          chidren.subTotal = chidren.unitPrice * chidren.number// 小计
          // 只计算选中的商品
          if (chidren.checked === true) {
            this.formData.orderAmount += chidren.subTotal// 总价
          }
          if (chidren.checked) {
            this.selectData.push(chidren)
          }
        })
      })
    },
    // 商品单选/反选
    checkedChange(index) {
      const data = this.listCopy[index]
      const selectData = []
      data.productsList.forEach((item, index) => {
        if (item.checked) {
          selectData.push(item)
        }
      })
      if (selectData.length === data.productsList.length) {
        data.checked = true
      } else {
        data.checked = false
      }
      this.listCopy.splice(index, 1, data)
    },
    // 店铺单选/反选
    checkedShop(index) {
      const data = this.listCopy[index]
      // 让该店铺的商品等于店铺的选框状态
      data.productsList.forEach((item, index) => {
        item.checked = data.checked
      })
      this.listCopy.splice(index, 1, data)
    },
    // 删除购物车信息
    deleteShoppingCartInfo(obj) {
      deleteShoppingCart(obj).then(res => {
        this.$message.success(res.data)
        this.$emit('getCartList')
      }).catch(() => {
      })
    },
    // 删除商品
    deleteCommodity(item, index, chidrenIndex) {
      const obj = { ids: [] }
      obj.ids.push(item.productsList[chidrenIndex].id)
      this.$confirm('确定将该商品移出购物车吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        this.deleteShoppingCartInfo(obj)
      }).catch(() => {
      })
    },
    // 删除店铺
    deleteShops(index) {
      // 店铺索引
      this.$confirm('确定要删除该商品吗??', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        this.listCopy.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {
      })
    },
    //  删除已选的商品
    deleteSeltect() {
      if (this.selectData.length) {
        this.$confirm('确定要删除选中的商品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'confirmBtn',
          cancelButtonClass: 'cancelBtn',
          type: 'warning'
        }).then(() => {
          const obj = { ids: [] }
          this.selectData.forEach((val, index) => {
            obj.ids.push(val.id)
          })
          this.deleteShoppingCartInfo(obj)
        }).catch(() => {
        })
      } else {
        this.$alert('请至少选择一件商品', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
        })
      }
    },
    // 移除失效商品
    deleteInvalid() {
      const obj = { ids: [] }
      for (let i = 0; i < this.listCopy.length; i++) {
        for (let x = 0; x < this.listCopy[i].productsList.length; x++) {
          // state 1:正常 其他:失效
          if (this.listCopy[i].productsList[x].state !== 1) {
            obj.ids.push(this.listCopy[i].productsList[x].id)
          }
        }
      }
      if (obj.ids.length) {
        this.$confirm('确定移除失效商品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'confirmBtn',
          cancelButtonClass: 'cancelBtn',
          type: 'warning'
        }).then(() => {
          this.deleteShoppingCartInfo(obj)
        }).catch(() => {
        })
      } else {
        this.$message.warning('当前列表没有失效商品')
      }
    },
    // 再次购买-移除失效商品
    falseDeleteInvalid() {
      let listRes = this.listCopy.silce(0)
      listRes.forEach(item => {
        item.productsList = item.productsList.filter(ele => ele.state === 1)
      })
      // 移除失效的商品后，如果商品数量为0 就删除店铺
      listRes = listRes.filter(item => item.productsList.length)
      this.listCopy = listRes.slice(0)
    },
    // 下单
    submit() {
      if (this.selectData.length < 1) {
        this.$message.warning('请选择商品')
        return
      }
      this.formData.ids = []
      this.selectData.forEach((val, index) => {
        this.formData.ids.push(val.id)
      })
      sessionStorage.setItem('formData', JSON.stringify(this.formData))
      sessionStorage.setItem('list', JSON.stringify(this.listCopy))
      // 再次购买
      if (this.buyerType === '03') {
        this.$emit('onceAgainPurchaseSubmit')
      } else {
        this.$router.push({ path: '/shop/settle', query: { from: 'myshoppingCart' }})
      }
    },
    // 去购物
    goToHome() {
      this.$router.replace({ path: '/shop/shopHome' })
    },
    // 查看赠品
    getSkuGift(skuId) {
      this.$refs.giftDetail.openDialogGetSkuGift(skuId)
    },
    // 删除赠品
    removeGift(id) {
      abandonOfGift(id).then(res => {
        this.$message.success(res.data)
        this.$emit('getCartList')
      })
    },
    // 购物车比价
    getCompareInfo(compareIds) {
      this.$refs.priceDetail.openDialogProductCompareInfo(compareIds)
    },
    // 打印商品信息
    printCommodityInfo() {
      if (this.selectData.length < 1) {
        this.$message.warning('请选择商品')
        return
      }
      this.$confirm('确认打印购物车商品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        const params = {
          // 购物车 00 结算页 01
          printType: '00',
          productsList: this.selectData
        }
        shopCarExport(params).then(res => {
          loadingInstance.close()
          const filename = '购物车商品列表' + '.pdf'
          download(res, filename)
          this.$message.success('打印成功！')
        }).catch(() => {
          loadingInstance.close()
        })
      }).catch(() => {})
    },
    // 删除 商品
    falseDelete(item, index, chidren, cIndex) {
      // 删除商品
      item.productsList.splice(cIndex, 1)
      // 店铺商品无商品，则删除店铺
      if (item.productsList.length === 0) {
        this.listCopy.splice(index, 1)
      }
    },
    // 删除选中商品
    falseDeleteSeltect() {
      // 选中的商品的 checked 为 true
      if (this.selectData.length) {
        this.$confirm('确定要删除选中的商品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'confirmBtn',
          cancelButtonClass: 'cancelBtn',
          type: 'warning'
        }).then(() => {
          // 删除全部选中的店铺
          this.listCopy = this.listCopy.filter(item => !item.checked)
          // 删除选中的商品
          this.listCopy.forEach(item => {
            item.productsList = item.productsList.filter(ele => !ele.checked)
          })
        }).catch(() => {
        })
      } else {
        this.$alert('请至少选择一件商品', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
        })
      }
    }
  }
}
</script>

<style scoped lang="less">
@import "./index";
.cart_null {
  text-align: center;
  padding-top: 150px;
  dl {
    width: 40%;
    margin: 0 auto 100px;
    display: flex;
    img {
      width: 82px;
      height: 82px;
      vertical-align: middle;
    }
    dd {
      text-align: left;
      margin-left: 20px;
    }
    p {
      line-height: 26px;
      font-size: 20px;
      margin-top: 10px;
      &:nth-last-of-type(1) {
        color: #FF6600;
        cursor: pointer;
        margin-top: 20px;
        &:hover {
          color: #fc7d29;
        }
      }
    }
  }
}
.cursor{
  cursor: pointer;
}
.gift{
  span{
    cursor: pointer;
    display: inline-block;
    color: #FF6600;
    padding-left:2px;
  }
}
  .dialog-content{
    width: 100%;
    padding: 5px;
    margin:10px 0;
    .product-content{
      display: flex;
      justify-content: space-between;
      line-height: 30px;
    }
  .product-name{
    width: 400px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.ulStyle_content .goods_name_box {
  width: calc((100% - 275px) / 4) !important;
  .goods_name {
    width: 100% !important;
    cursor: pointer;
    text-align:left !important;
    display: -webkit-box !important;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .goods_name:hover {
    color:#00aaca;
  }
}
.all_product {
    font-family: 'PingFangSC-Regular', 'PingFang SC';
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-weight: 400;
    font-size: 14px;
    margin-top:10px;
    > span {
      color: #fd6b2b;
    }
}
.goods_img {
  width: 76px !important;
  height: 76px !important;
  margin: 2px 0 0 2px;
}

.cart_title {
  color:#333 !important;
  display: flex;
  .el-checkbox {
    color:#333 !important;
  }
}
.flex_1 {
  flex:1 !important;
}
.textac {
  text-align: center !important;
}

</style>
