<template>
  <div class="cart-pages">
    <div class="cart-bos">
      <div class="cart-head flex-row-between">
        <div class="flex-row-start head1">
          <img src="@/assets/images/cart1.png" alt="" />
          <div>我的购物车</div>
        </div>
        <div class="head2">导出订单</div>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{
          color: '#1D2129',
          backgroundColor: '#F2F3F5',
          fontWeight: 'normal'
        }"
        @selection-change="handleSelectionChange1"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品信息" width="490">
          <template #default="scope">
            <div class="cart-info">
              <img class="cart-img" :src="scope.row.productImage" alt="" />
              <div class="cart-text">
                <div class="text1">{{ scope.row.itemName }}</div>
                <div class="text2">
                  <span>单位:{{ scope.row.unitName }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="130">
          <template #default="scope"> ¥{{ scope.row.memberPrice }} </template>
        </el-table-column>
        <el-table-column label="数量" width="200">
          <template #default="scope">
            <el-input-number v-model="scope.row.productNum" :min="1" :max="scope.row.allStock" @change="(res) => handleChange(res, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="小计" width="140">
          <template #default="scope"> ¥{{ (scope.row.memberPrice * scope.row.productNum).toFixed(2) }} </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <div>
              <el-button @click="editCollection(scope.row)" link>{{ scope.row.isCollect == 1 ? '取消收藏' : '移入收藏' }} </el-button>
            </div>
            <div>
              <el-button link @click="onDel(scope.row)"> 删除 </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="cart-shi">失效商品</div>
      <el-table
        :data="noTableData"
        style="width: 100%"
        :header-cell-style="{
          color: '#1D2129',
          backgroundColor: '#F2F3F5',
          fontWeight: 'normal'
        }"
        :row-style="{
          backgroundColor: '#F9F9F9'
        }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品信息" width="490">
          <template #default="scope">
            <div class="cart-info">
              <img class="cart-img" :src="scope.row.productImage" alt="" />
              <div class="cart-text">
                <div class="text1">{{ scope.row.itemName }}</div>
                <div class="text2">
                  <span>单位:{{ scope.row.unitName }}</span>
                </div>
                <div class="text3">当前商品库存不足，当前库存量：0</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="130" align="center">
          <template #default="scope"> ¥{{ scope.row.memberPrice }} </template>
        </el-table-column>
        <el-table-column label="数量" width="200" align="center">
          <template #default="scope">
            <el-input-number disabled v-model="scope.row.productNum" :controls="false" :min="1" :max="10" style="width: 130px" />
          </template>
        </el-table-column>
        <el-table-column label="小计" width="140" align="center">
          <template #default="scope"> ¥{{ (scope.row.memberPrice * scope.row.productNum).toFixed(2) }} </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <div>
              <el-button @click="editCollection(scope.row)" link>{{ scope.row.isCollect == 1 ? '取消收藏' : '移入收藏' }} </el-button>
            </div>
            <div>
              <el-button link @click="onDel(scope.row)"> 删除 </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="cart-bnt">
      <div class="bnt-bos flex-row-between">
        <div></div>
        <!-- <div class="flex-row-start">
          <el-checkbox v-model="checked1" label="全选" @change="handleSelectAll" />
          <el-button style="margin-left: 10px">删除</el-button>
          <el-button>移入收藏</el-button>
        </div> -->
        <div class="bnt-box flex-row-start">
          <span>共</span>
          <span class="hig">{{ tableData.length }}</span>
          <span>种商品，已选择</span>
          <span class="hig">{{ selectedList.length }}</span>
          <span>件，商品合计：</span>
          <span class="hig">¥{{ onMoney }}</span>
          <span>，活动优惠：0.00</span>
          <span class="span1">合计:</span>
          <span class="span2">¥{{ onMoney }}</span>
          <el-button class="bnt" type="primary" @click="goTrad">去结算</el-button>
        </div>
      </div>
    </div>
    <!-- 取消收藏 -->
    <el-dialog
      v-model="dialogVisible"
      title="选择取消的收藏夹"
      width="500"
      :before-close="
        () => {
          dialogVisible = false;
        }
      "
    >
      <div>
        <el-radio-group v-model="radio">
          <el-radio v-for="(item, index) in favorites" :key="index" :value="item.id">{{ item.title }}</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onCancel"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { TableInstance } from 'element-plus';
const tableData = ref<any>([]);
const selectedList = ref<any>([]);
const noTableData = ref<any>([]);
const multipleTableRef = ref<TableInstance>();
const checked1 = ref(false);
const dialogVisible = ref<any>(false);
const favorites = ref<any>([]);
const radio = ref<any>(null);
const radioRow = ref<any>({});
import {
  shoppingCartList,
  deleteProductShoppingCart,
  isProductInDefaultCollect,
  cancelProductCollect,
  addProductCollect,
  favoritesList
} from '@/api/goods/index';
import { onPath } from '@/utils/siteConfig';

onMounted(() => {
  getInfo();
});

const getInfo = () => {
  shoppingCartList({}).then((res) => {
    if (res.code == 200) {
      tableData.value = [];
      noTableData.value = [];
      if (res.rows && res.rows.length > 0) {
        res.rows.forEach((item: any) => {
          item.allStock = Number(item.totalInventory || 0) + Number(item.nowInventory || 0) + Number(item.virtualInventory || 0);
          // item.allStock = 8888;
          if (item.productStatus == 1 && item.allStock > 0) {
            tableData.value.push(item);
          } else {
            noTableData.value.push(item);
          }
        });
      }
    }
  });
};

const handleChange = (val: any, row: any) => {
  const numberVal = Number(val);
  const step = row.minOrderQuantity || 1;
  row.productNum = Math.ceil(numberVal / step) * step;
};

//购物车选中
const handleSelectionChange1 = (val: any) => {
  selectedList.value = val;
};

//全选
const handleSelectAll = (val: any) => {
  if (val) {
    multipleTableRef.value?.toggleAllSelection();
  } else {
    multipleTableRef.value?.clearSelection();
  }
};

import { cartStore } from '@/store/modules/cart';
const cart = cartStore();
const onDel = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteProductShoppingCart(row.shoppingCartId).then((res) => {
      if (res.code == 200) {
        ElMessage.success('删除成功');
        getInfo();
        cart.onCartCount();
      }
    });
  });
};

const goTrad = () => {
  if (selectedList.value.length == 0) {
    ElMessage.warning('请选择商品');
    return;
  }
  const ids = selectedList.value.map((item: any) => item.shoppingCartId).join(',');
  onPath('/trad?ids=' + ids);
};

const onMoney = computed(() => {
  let money = 0;
  let price = '';
  selectedList.value.forEach((item: any) => {
    money = money + Number(item.memberPrice * item.productNum);
  });
  price = Number(money).toFixed(2);
  return price;
});

//修改收藏
const editCollection = (row: any) => {
  if (row.isCollect == 1) {
    dialogVisible.value = true;
    favoritesList(row.id).then((res) => {
      if (res.code == 200) {
        if (res.rows.length > 0) {
          radio.value = res.rows[0].id;
        }
        favorites.value = res.rows;
        radioRow.value = row;
      }
    });
  } else {
    // 添加
    addProductCollect({ productId: row.id }).then((res) => {
      if (res.code == 200) {
        getInfo();
      }
    });
  }
};

// 取消收藏
const onCancel = () => {
  cancelProductCollect({ productId: radioRow.value.id, favoritesId: radio.value }).then((res) => {
    if (res.code == 200) {
      dialogVisible.value = false;
      getInfo();
    }
  });
};
</script>

<style lang="scss" scoped>
.cart-pages {
  width: 100%;
  background: #ffffff;
  .cart-bos {
    width: 1200px;
    margin: 0 auto;
  }
  .cart-head {
    margin-bottom: 20px;
    padding-top: 20px;
    .head1 {
      font-weight: 600;
      font-size: 16px;
      color: #101828;
      img {
        width: 18px;
        height: 18px;
        margin-right: 6px;
      }
    }
    .head2 {
      width: 88px;
      height: 25px;
      border-radius: 4px 4px 4px 4px;
      border: 1px solid #e7000b;
      font-size: 12px;
      color: #e7000b;
      line-height: 25px;
      text-align: center;
    }
  }
  .cart-info {
    width: 490px;
    height: 94px;
    display: flex;
    .cart-img {
      width: 94px;
      height: 94px;
      border-radius: 6px;
    }
    .cart-text {
      flex: 1;
      width: 0;
      padding-left: 10px;
      .text1 {
        font-size: 14px;
        color: #000000;
        height: 50px;
      }
      .text2 {
        font-size: 14px;
        color: #364153;
        span {
          margin-right: 10px;
        }
      }
      .text3 {
        font-size: 14px;
        color: #e7000b;
      }
    }
  }
  .cart-shi {
    font-weight: 600;
    font-size: 16px;
    color: #101828;
    padding: 20px 0;
  }
  .cart-bnt {
    width: 100%;
    height: 82px;
    background: #ffffff;
    box-shadow: 0px -2px 13px 0px rgba(0, 0, 0, 0.05);
    margin-top: 48px;
    .bnt-bos {
      width: 1200px;
      margin: 0 auto;
      height: 82px;
      .bnt-box {
        font-size: 14px;
        color: #000000;
        .span1 {
          font-weight: 600;
          color: #101828;
          margin-left: 20px;
        }
        .span2 {
          font-weight: 600;
          color: #e7000b;
          font-size: 16px;
          margin-top: 2px;
          margin-left: 2px;
        }
        .hig {
          color: #e7000b;
        }
        .bnt {
          width: 142px;
          height: 50px;
          font-size: 16px;
          margin-left: 20px;
        }
      }
    }
  }
}
</style>
