<template>
  <div class="index wrapper_1200">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>购物车</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="shopping_cart_Box" v-if="tableData.length">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="selRow"
        ref="multipleTable"
        :header-cell-style="{ background: '#fafafa' }"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column prop="id" label="商品" width="260" align="center">
          <template slot-scope="scope">
            <div class="commodityBox">
              <img :src="imgUrl + scope.row.sku_image" alt />
              <div class="commoditytxt">
                <p>{{ scope.row.goods_name }}</p>
                <p v-if="scope.row.commoditytag">
                  <span
                    :class="{
                      commodityTagBg: scope.row.commodityTagType === 1,
                    }"
                    >{{ scope.row.commoditytag }}</span
                  >
                </p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="commodityNum" label="数量" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.num }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount1" label="单价" align="center">
          <template slot-scope="scope">
            <span>￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount2" label="小计" align="center">
          <template slot-scope="scope">
            <span>￥{{ Math.round(scope.row.num * scope.row.price * 100) / 100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="moveIn(scope.row)"
              v-if="!scope.row.isCollect"
              >移入收藏夹</el-button
            >
            <el-button type="text" size="small" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table_footer">
        <div class="table_footer_checkbox">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="selAll"
            >全选</el-checkbox
          >
          <div class="table_footer_checkbox_btn" @click="Selectdel">
            <img
              style="width: 18px; height: 18px; margin-left: 40px"
              src="../../assets/images/delete.png"
              alt
            />
            删除选择商品
          </div>
          <!-- <div class="table_footer_checkbox_btn" @click="allMoveIn()">
            <img style="width: 18px; height: 18px" src="../../assets/images/favorites.png" alt />
            移入收藏夹
          </div>-->
        </div>

        <div class="table_footer_right">
          <div>商品：{{ speciesNum }}种{{ orderPiece }}件</div>
          <div style="color: #ff3030">合计：¥{{ orderTotal }}</div>
          <div>
            <el-button type="primary" size="small" @click="submitOrder"
              >提交订单</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <div class="nothing" v-if="!tableData.length">
      <img src="@/assets/images/noGoods.png" />
      暂无商品，去看点别的吧
    </div>

    <!-- 为你推荐 -->
    <Guess
      v-if="guessList.length"
      :guessList="guessList"
      :Page="guessPage"
      @changePage="changePage"
    />

    <!-- 起订金额提醒  -->
    <el-dialog
      :visible.sync="depositTipsDialog"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div slot="title" style="display: flex">
        <img
          style="width: 24px; height: 24px; margin-right: 10px"
          src="~assets/images/Tips.png"
          alt
        />
        <div style="height: 24px; line-height: 24px; font-size: 16px; font-weight: 500">
          提示
        </div>
      </div>
      <div style="margin: 0px auto; width: 330px; height: 100%">
        订单金额不能小于{{ orderAmount }}元
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="depositTipsDialog = false">确定</el-button>
      </span>
    </el-dialog>

    <!-- 起删除提醒  -->
    <el-dialog
      :visible.sync="delDialog"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div slot="title" style="display: flex">
        <img
          style="width: 24px; height: 24px; margin-right: 10px"
          src="~assets/images/Tips.png"
          alt
        />
        <div style="height: 24px; line-height: 24px; font-size: 16px; font-weight: 500">
          提示
        </div>
      </div>
      <div style="margin: 0px auto; width: 330px; height: 100%">确认要删除所选商品？</div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="delDialog = false">取消</el-button>
        <el-button size="small" type="primary" @click="submitdel()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Setting from "~/setting";
import Guess from "@/components/guess.vue";
export default {
  auth: false,
  components: { Guess },
  data() {
    return {
      imgUrl: Setting.uplodBaseURL,
      tableData: [],
      sku_ids: [],
      // 为你推荐
      guessList: [],
      // 为你推荐分页
      guessPage: {
        total: 0,
        pageSize: 4,
        currentPage: 1,
      },
      orderTotal: 0,
      multipleSelection: [],
      isIndeterminate: false,
      checkAll: false,
      // 起订金额提醒
      depositTipsDialog: false,
      // 删除
      isAllDel: false,
      delDialog: false,
      delIdList: [],
      delId: "",
      cart_ids: [],
      orderAmount: 1,
      orderPiece: 0,
      speciesNum: 0,
    };
  },
  created() {
    this.getCartData();
    this.getGuessData();
    this.getOrderAmount();
    // this.getCartCount();
  },
  methods: {
    getOrderAmount() {
      this.$axios.post(`/config/init`).then((res) => {
        this.orderAmount = Number(res.data.order_limit_start_money);
      });
    },
    getCartData() {
      this.tableData = [];
      this.sku_ids = [];
      let obj = {
        province_name: "成都",
      };
      this.$axios
        .post(`/cart/goodsLists`, obj)
        .then((res) => {
          console.log(res.data);
          // 查询购物车计算参数
          res.data.map((item) => {
            this.sku_ids.push({
              sku_id: item.sku_id,
              num: item.num,
              cart_id: item.cart_id,
            });
          });
          this.cart_calculate();
          console.log(this.tableData);
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 购物车计算
    cart_calculate() {
      let obj = {
        sku_ids: JSON.stringify(this.sku_ids),
      };
      this.$axios
        .post(`/cartcalculate/calculate`, obj)
        .then((res) => {
          console.log(res.data, `calculate`);
          res.data.goods_list.forEach((item) => {
            // 查询当前列表每行商品是否已收藏
            this.$axios
              .post(`/goodscollect/iscollect`, {
                goods_id: item.goods_id,
                province_name: "成都",
              })
              .then((res) => {
                item.isCollect = res.data;
                this.tableData.push(item);
                this.mergeArray(this.tableData, this.sku_ids);
              });
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 两个数组对象中id相同合并数组
    mergeArray(arr1, arr) {
      for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr.length; j++) {
          if (arr1[i].sku_id == arr[j].sku_id) {
            arr1[i].num = arr[j].num;
            arr1[i].cart_id = arr[j].cart_id;
          }
        }
      }
    },

    // 表格多选
    selRow(val) {
      // 联动表格下方全选多选框
      if (val.length < this.tableData.length && val.length > 0) {
        this.isIndeterminate = true;
      } else if (val.length == this.tableData.length) {
        this.isIndeterminate = false;
        this.checkAll = true;
      } else if (val.length == 0) {
        this.isIndeterminate = false;
        this.checkAll = false;
      }
      // 计算选中每行订单的价格
      this.multipleSelection = val;

      let subtotal = [];
      subtotal = val.map(function (item) {
        return Math.round(item.num * item.price * 100) / 100;
      });
      let arr = [];
      arr = val.map((item) => {
        return item.num;
      });
      this.speciesNum = this.multipleSelection.length;
      this.orderPiece = arr.reduce(function (a, b) {
        return a + b;
      }, 0);
      this.orderTotal = this.sum(subtotal);
      this.cart_ids = this.multipleSelection.map((item) => {
        return item.cart_id;
      });
    },
    // 选中每行订单的总价
    sum(args) {
      // var args = arguments,//获取所有的参数
      var d = 0, //定义小数位的初始长度，默认为整数，即小数位为0
        sum = 0; //定义sum来接收所有数据的和
      //循环所有的参数
      for (var key in args) {
        //遍历所有的参数
        //把数字转为字符串
        var str = "" + args[key];
        if (str.indexOf(".") != -1) {
          //判断数字是否为小数
          //获取小数位的长度
          var temp = str.split(".")[1].length;
          //比较此数的小数位与原小数位的长度，取小数位较长的存储到d中
          d = d < temp ? temp : d;
        }
      }
      //计算需要乘的数值
      var m = Math.pow(10, d);
      //遍历所有参数并相加
      for (var key in args) {
        sum += args[key] * m;
      }
      //返回结果
      return sum / m;
    },

    // 表格底部全选按钮
    selAll(val) {
      if (this.$refs.multipleTable.selection.length < this.tableData.length) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
      this.$refs.multipleTable.toggleAllSelection();
      this.isIndeterminate = false;
      console.log(val);
    },
    // 提交订单按钮
    submitOrder() {
      if (this.orderTotal < this.orderAmount) {
        this.depositTipsDialog = true;
      } else {
        // 跳转提交订单页面
        this.$router.push({
          path: "/shopping_cart/submit_order",
          query: {
            cart_ids: this.cart_ids,
            sku_ids: this.sku_ids,
          },
        });
      }
    },
    // 移入收藏夹
    moveIn(row) {
      console.log(row);
      let { goods_id, sku_id, sku_name, sku_price, sku_image } = { ...row };
      let obj = {
        goods_id,
        sku_id,
        sku_name,
        sku_price,
        sku_image,
      };
      this.$axios
        .post(`/goodscollect/add`, obj)
        .then((res) => {
          console.log(res);
          this.$message({
            message: "收藏成功",
            type: "success",
            offset: 100,
          });
          this.getCartData();
        })
        .catch((err) => {
          console.log(err);
          // this.$message({
          //   message: err,
          //   type: "error",
          //   offset: 100
          // });
        });
    },

    // 多选移入收藏夹
    // allMoveIn() {
    //   const flag = this.multipleSelection.every(item => {
    //     return [1].includes(item.isCollect);
    //   });
    //   console.log(flag);
    //   // 判断多选中有没有已经移入收藏夹的商品
    //   if (flag) {
    //       this.$message({
    //       message: '当前选择中已有商品在收藏夹中',
    //       type: 'error'
    //     })
    //   }else{

    //   }
    // },

    // 删除弹出框
    del(row) {
      this.delDialog = true;
      this.delId = row.cart_id;
      this.isAllDel = false;
    },
    // 删除确定按钮
    submitdel() {
      let obj = {
        // 判断是否多选删除
        cart_id: this.isAllDel ? this.cart_ids : this.delId,
      };
      this.$axios.post(`/cart/delete`, obj).then((res) => {
        this.$message({
          message: "删除成功",
          type: "warning",
        });
        this.getCartData();
      });
      this.delDialog = false;
    },
    // 删除选中商品
    Selectdel() {
      this.delDialog = true;
      this.isAllDel = true;
    },
    // 为你推荐分页
    changePage(e) {
      this.guessPage.currentPage = e;
      this.getGuessData();
    },
    // 获取为你推荐数据
    getGuessData() {
      let obj = {
        page: this.guessPage.currentPage,
        page_size: this.guessPage.pageSize,
        route: "cart",
      };
      this.$axios
        .post(`/goodssku/recommend`, obj)
        .then((res) => {
          res.data.list.forEach((item) => {
            item["num"] = 0;
          });
          this.guessList = res.data.list;

          this.guessPage.total = res.data.count;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.index {
  .crumbs {
    margin: 20px 0;
  }
  .shopping_cart_Box {
    width: 1200px;
    min-height: 530px;
    background: #ffffff;
    border-radius: 4px;
    margin-bottom: 20px;
    padding: 30px 20px;
    /deep/ .el-table {
      .el-checkbox {
        .el-checkbox__input {
          .el-checkbox__inner {
            border-radius: 50%;
          }
        }
      }
      .el-button--text {
        color: #333;
      }
      .commodityBox {
        display: flex;
        img {
          width: 60px;
          height: 60px;
        }
        .commoditytxt {
          p {
            line-height: 30px;
            text-align: left;
            margin-left: 10px;
          }

          p:first-child {
            font-weight: 600;
          }
          p:last-child {
            font-size: 12px;

            span {
              background: #ff7d02;
              border-radius: 2px;
              width: 36px;
              padding: 3px 4px;
              color: #ffffff;
            }
            .commodityTagBg {
              background: #ff1449;
            }
          }
        }
      }
    }
    .table_footer {
      padding: 0px 17px;
      width: 100%;
      height: 60px;
      background: #ffffff;
      border: 1px solid #ebeef5;
      background: #fafafa;
      border-top: none;
      display: flex;
      justify-content: space-between;
      /deep/ .el-checkbox {
        .el-checkbox__input {
          .el-checkbox__inner {
            border-radius: 50%;
          }
        }
      }
      .table_footer_checkbox {
        line-height: 60px;
        display: flex;
        .table_footer_checkbox_btn {
          display: flex;
          margin-left: 30px;
          cursor: pointer;
          img {
            margin: auto;
          }
        }
      }
      .table_footer_right {
        display: flex;
        line-height: 60px;
        div {
          margin-right: 30px;
        }
      }
    }
  }
  .nothing {
    padding-top: 100px;
    padding-bottom: 150px;
    font-size: 16px;
    text-align: center;
    color: #969696;

    img {
      margin: 0 auto;
    }
  }
}
</style>
