<template>
  <div class="shoppingCart">
    <el-tabs v-model="listIdx">
      <el-tab-pane label="购物车列表" name="1">
        <template>
          <div class="top">
            <div class="btn-list">
              <el-button type="primary" @click="openBox"
                >删除所选商品</el-button
              >
              <el-button type="info" @click="removeCart">清空购物车</el-button>
            </div>
            <div class="select-info">
            <template v-if="Object.keys(addressObj).length > 0">
              <el-descriptions title="选择的地址信息（用于购物车的发货）">
                <el-descriptions-item label="收货人姓名">{{
                  addressObj.receiveName
                }}</el-descriptions-item>
                <el-descriptions-item label="收货人电话号码">{{
                  addressObj.receivePhone
                }}</el-descriptions-item>
                <el-descriptions-item label="地址标签">
                  <el-tag size="small">{{ addressObj.label }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="是否是默认地址">
                  {{ addressObj.ifDefault == 1 ? "是" : "否" }}
                </el-descriptions-item>
                <el-descriptions-item label="收货地址"
                  >{{ addressObj.receiveAdress
                  }}{{ addressObj.address }}</el-descriptions-item
                >
              </el-descriptions>
            </template>
            <template v-else>
              <el-empty
                :image-size="50"
                description="暂未选择你的收货地址"
              >
                <el-button type="primary" @click="gpAddress"
                  >去选择收货地址</el-button
                >
              </el-empty>
            </template>
          </div>
          </div>

          <el-table
            v-loading="loading"
            ref="multipleTable"
            border
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column
              label="商品名称"
              align="center"
              prop="productName"
              width="200"
            ></el-table-column>
            <el-table-column label="商品图片" align="center">
              <template slot-scope="scope">
                <img :src="scope.row.image" style="width: 50px; height: 50px" />
              </template>
            </el-table-column>
            <el-table-column label="商品价格" align="center">
              <template slot-scope="scope">
                ￥{{ scope.row.price || 0 }}
              </template>
            </el-table-column>
            <el-table-column label="商品库存" prop="stockNumber" align="center">
            </el-table-column>

            <el-table-column label="商品数量" align="center">
              <template #header="scope">
                <div class="number-box">
                  <p>商品数量</p>
                  <span style="color: red; font-size: 12px"
                    >最大商品数量不得超过商品库存且最小数量为1</span
                  >
                </div>
              </template>
              <template slot-scope="scope">
                <el-input-number
                  size="mini"
                  :min="1"
                  :max="scope.row.stockNumber"
                  v-model="scope.row.number"
                  @change="changeNum(scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              label="商品规格"
              align="center"
              prop="value"
            ></el-table-column>
            <el-table-column label="该商品总价" align="center">
              <template slot-scope="scope">
                ￥{{ scope.row.price * scope.row.number }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="clearnShop(scope.row)"
                  >删除该商品</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="settlement">
              <div class="txt-price">
                <p>总价：￥{{ allPrice }}</p>
                <p>商家代金券余额：{{ voucherNum.toFixed(2) }}</p>
              </div>

              <el-button type="danger" @click="settleShop">结算商品</el-button>
            </div>
         
        </template>
      </el-tab-pane>
      <el-tab-pane label="地址列表" name="2">
        <AddressCom :addressObj="addressObj" @selectAddress="selectAddress" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {
  getShopCarList,
  updateShopCar,
  deleteShopCar,
  clearShopCar,
  getSettlement,
  requertVoucher,
  shopSysGetById,
  voucherPay,
} from "@/api/threeSelection";
import { getShopId } from "@/utils/auth";
import AddressCom from "./components/addressCom.vue";
export default {
  created() {
    this.getList();
    this.getVoucher();
    this.getShopInfo();
    //  拿到商铺 id
    // this.settlementQuery.shopId = getShopId();
  },
  components: {
    AddressCom,
  },
  data() {
    return {
      //  传递给 地址组件的数据
      addressObj: {},
      //  tab 切换
      listIdx: "1",
      tableData: [],
      multipleSelection: [],
      //  加载状态
      loading: false,
      settlementQuery: {
        type: "1",
        shopId: null,
        shops: [],
        receiveId: "",
        voucherTotalAll: "",
        isVoucher: false,
        voucherId: "",
      },
      //  代金券数量
      voucherNum: 0,
      //  店铺信息
      shopInfo: {},
    };
  },
  computed: {
    allPrice() {
      let price = this.multipleSelection.reduce((prev, item) => {
        prev += item.price * item.number;
        return prev;
      }, 0);
      return price.toFixed(2);
    },
  },
  methods: {
    //  选中的地址
    selectAddress(val) {
      this.addressObj = val;
    },
    async getList() {
      this.loading = true;
      try {
        let res = await getShopCarList();
        this.tableData = res.data[0]?.skus;
      } finally {
        this.loading = false;
      }
    },
    // 请求店铺信息
    async getShopInfo() {
      let res = await shopSysGetById({});
      this.shopInfo = res.data;
    },
    //  获取代金券数量
    async getVoucher() {
      let res = await requertVoucher();
      // console.log(res);
      if (res.code == "") {
        this.voucherNum = res.data;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //  修改商品数量
    async changeNum(item) {
      let { skuId, number } = item;
      let res = await updateShopCar({ skuId, number });
      if (res.code == "") {
        this.$message({
          message: "修改数量成功",
          type: "success",
        });
      }
      // console.log(res);
    },
    //  删除所选商品
    async delShopCar() {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          message: "请选择你要删除购物车的商品",
          type: "warning",
        });
        return;
      }
      let skuIdList = this.multipleSelection.map((item) => {
        return item.skuId;
      });
      let res = await deleteShopCar({ ids: skuIdList });
      if (res.code == "") {
        this.$message({
          message: "删除商品成功",
          type: "success",
        });
        this.getList();
      }
    },
    openBox() {
      this.$confirm("请确定是否需要删除购物车中所选择的商品？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.delShopCar();
      });
    },
    //  删除所选商品
    async clearnShop(row) {
      this.$confirm("请确定是否需要该商品？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let res = await deleteShopCar({ ids: [row.skuId] });
        if (res.code == "") {
          this.$message({
            message: "删除商品成功",
            type: "success",
          });
          this.getList();
        }
      });
    },
    //  清空购物车
    removeCart() {
      this.$confirm("此操作将清空购物车, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await clearShopCar();
          if (res.code == "") {
            this.$message({
              message: "清空成功",
              type: "success",
            });
            this.getList();
          }
        })
        .catch(() => {});
    },
    // 结算
    async settleShop() {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          message: "请选择要结算的商品",
          type: "warning",
        });
        return;
      }
      if (!this.addressObj.receiveId) {
        this.$message({
          message: "请选择收货地址",
          type: "warning",
        });
        return;
      }
      this.settlementQuery.shops = this.multipleSelection.reduce(
        (prev, item) => {
          console.log(item.shopId);
          let obj = {
            ifWork: 0,
            shopId: item.shopId,
            shopName: item.shopName,
            shopDiscountId: "",
            shopSeckillId: "",
            skus: [
              {
                productId: item.productId,
                skuId: item.skuId,
                productName: item.productName,
                image: item.image,
                price: item.price,
                number: item.number,
                weight: item.weight,
                SKU: "",
                total: item.total,
                ifLogistics: item.ifLogistics,
              },
            ],
          };
          prev.push(obj);
          return prev;
        },
        []
      );
      this.settlementQuery.shopId = this.multipleSelection[0].shopId
      console.log(this.settlementQuery);
      let res = await getSettlement(this.settlementQuery);
      // console.log("到这里了");
      // let res2 = await voucherPay(res.data)
      this.$confirm("是否使用代金券支付该产品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.pay(res.data);
        })
        .catch(() => {});
    },
    //  下单
    async pay(data) {
    // console.log(data);
    // return
      let skusData = data.shops.reduce((prev, item) => {
        prev.push(...item.skus);
        return prev;
      }, []);

      let queryData = {
        procureType: 1,
        shopDiscountId: null,
        collageId: 0,
        type: "",
        shopGroupWorkId: 0,
        receiveId: null,
        areaId: 0,
        communityId: "",
        couponId: 0,
        remark: "",
        discountPrice: 0,
        shopSeckillId: null,
        voucherTotalAll: 0,
        isVoucher: false,
        voucherId: 0,
        communityPhone: "",
        franchiseeRule: [],
        paymentMode: 4,
        _isShowToast: false,
        shops: [
          {
            shopId: 186,
            distribution: {
              distributionPrice: 0,
              distributionName: "结算类型-拼团商品单独立即购买",
            },
            skus: [],
          },
        ],
      };
      queryData.receiveId = this.addressObj.receiveId;
      queryData.shops[0].skus = skusData;
      let res = await voucherPay(queryData);
      if (res.code == "") {
        this.$message({
          message: "支付成功",
          type: "success",
        });
        this.getVoucher();
        this.getList();
      }
    },
    //  去选择收货地址
    gpAddress() {
      this.listIdx = "2";
    },
  },
};
</script>

<style lang="scss" scoped>
.shoppingCart {
  padding: 50px;
  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .btn-list {
    margin: 20px 0;
    flex:1;
  }
  .select-info {
  margin: 30px 0;
  flex:2;

  ::v-deep .el-descriptions__body {
    padding: 20px;
    box-sizing: border-box;
  }

  ::v-deep .el-descriptions-item {
    margin-top: 20px;
  }
}

  
  }
  .settlement {
    margin: 30px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    box-sizing: border-box;

    .txt-price {
      p {
        font-size: 32px;
        color: red;
        font-weight: 700;
        margin-top: 10px;
      }
    }
  }

}

.number-box {
  display: flex;
  align-items: center;
  flex-direction: column;
  gap: 5px;
}

</style>
