<template>
  <div class="containe">
    <Search :navId="navId"></Search>
    <div class="contentWrap">
      <div class="top">
        <div class="title">{{ title }}</div>
        <div class="wrap">
          <Nav v-model:navList="navList" />
        </div>
      </div>
      <div class="info">
        <a-steps :current="0" size="small">
          <a-step title="我的购物车" />
          <a-step title="填写核对订单信息" />
          <a-step title="提交订单" />
        </a-steps>
        <div class="productList">
          <a-table
            :dataSource="productList"
            :columns="columns"
            :pagination="false"
            childrenColumnName="cartProductDetailList"
            rowKey="uuid"
            :scroll="{ y: 450 }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'type'">
                <span v-if="record.goodsType === 'PRODUCT'">产品</span>
                <span v-else-if="record.goodsType === 'KIT'">套件</span>
              </template>
              <template v-if="column.key === 'quantity'">
                <a-input-number
                  v-model:value="record.quantity"
                  :min="1"
                  @change="handleQuantityChange($event, record)"
                  :disabled="record.type === 'KIT'"
                />
              </template>
              <template v-if="column.key === 'active' && record.type != 'KIT'">
                <a-popconfirm
                  title="是否确认删除?"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="confirm(record.uuid, record.id)"
                  @cancel="() => {}"
                >
                  <a-button type="link">删除</a-button>
                </a-popconfirm>
              </template>
            </template>
          </a-table>
          <div class="btnWrap">
            <a-button type="default" size="large" @click="handleEmptyShoppingCart">
              <template #icon>
                <shopping-cart-outlined />
              </template>
              清空购物车
            </a-button>

            <div class="right">
              <span class="title"
                >已选数量：<span class="num">{{ productNum }}</span
                >件</span
              >
              <a-button type="primary" size="large" @click="handleGoCheckOrder" :disabled="productNum === 0">
                去结算
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import { useNavTree, useCartList } from '/@/hooks/myhooks/index';
  import Search from '../components/search.vue';
  import Nav from '../components/nav.vue';
  import { DataItem } from '/@/views/product/goods-category/type';
  import { toNumber } from 'lodash';
  import { columns } from './schema';
  import { ShoppingCartOutlined } from '@ant-design/icons-vue';
  import { useGo } from '/@/hooks/web/usePage';
  import * as CartApi from '/@/api/order/cartApi';
  import { message } from 'ant-design-vue';

  const go = useGo();
  const navTree = useNavTree();
  const route = useRoute();
  const getCartList = useCartList();

  columns.push({
    title: '操作',
    key: 'active',
    width: '100px',
  });

  const query = route.query;
  const navId = toNumber(query.nav); // 一级选择id
  const navList = ref<DataItem[]>([]); // 菜单树
  const title = ref(''); // 标题名称
  // const productList = shoppingStore.shoppingCart;
  const productList = ref<any>([]);

  const getGrandsonList = (arr: DataItem[]) => {
    arr.some((item) => {
      if (item.id === navId) {
        title.value = item.name;
        return true;
      }
    });
  };

  // 删除
  const confirm = (uuid, id) => {
    const uuidArr = uuid.split('-');
    if (uuidArr.length === 1) {
      CartApi.remove([{ id }]).then((res) => {
        message.success('删除成功');
        getCartList(productList);
      });
    } else if (uuidArr.length === 2) {
      const goodsId = toNumber(uuidArr[0]);
      const index = productList.value.findIndex((item) => {
        const idx = item.cartProductDetailList.findIndex((pro) => {
          return pro.uuid === uuid;
        });

        if (idx != -1) {
          item.cartProductDetailList.splice(idx, 1);
        }
        return item.goodsId === goodsId;
      });
      if (index != -1) {
        CartApi.update(productList.value[index]);
      }
    }
  };

  // 数量改变
  const handleQuantityChange = (val, record) => {
    if (record.cartProductDetailList) {
      record.cartProductDetailList.forEach((product) => {
        if (record.goodsType === 'KIT') {
          product.quantity = product.basicQuantity * val;
        } else if (record.goodsType === 'PRODUCT') {
          product.quantity = val;
        }
      });
      CartApi.update(record);
    } else {
      const uuid = record.uuid;
      const goodsId = toNumber(uuid[0]);
      const index = productList.value.findIndex((item) => {
        return item.goodsId === goodsId;
      });
      if (index != -1) {
        CartApi.update(productList.value[index]);
      }
    }
  };

  // 清空购物车
  const handleEmptyShoppingCart = () => {
    CartApi.removeAll().then((_) => {
      message.success('清除成功');
    });
    getCartList(productList);
  };

  const productNum = computed(() => {
    let num = 0;
    productList.value.forEach((item) => {
      item.cartProductDetailList.forEach((product) => {
        num += product.quantity;
      });
    });
    return num;
  });

  const handleGoCheckOrder = () => {
    go('/main/store/check-order' + `?nav=${navId}`);
  };

  onMounted(() => {
    navTree(navList, getGrandsonList, 'getGrandsonList');
    getCartList(productList);
  });
</script>

<style lang="less" scoped>
  p {
    margin: 0;
    padding: 0;
  }
  .containe {
    padding: 30px;
    .contentWrap {
      padding: 30px;
      background: #fff;
      border-radius: 10px;
      max-width: 1400px;
      min-width: 1200px;
      margin: 0 auto;

      .top {
        display: flex;
        justify-content: space-between;

        .title {
          width: 25%;
          background: #f7f9fa;
          color: #1890ff;
          border-radius: 10px;
          text-align: center;
          height: 50px;
          padding: 5px;
          line-height: 40px;
          font-size: 20px;
        }

        .wrap {
          width: 73%;
          margin: 0;
        }
      }

      .info {
        .ant-steps {
          width: 800px;
          margin: 20px auto;
        }

        .productList {
          .ant-table-wrapper {
            height: 505px;
          }
          .btnWrap {
            background: #2d374b;
            height: 80px;
            line-height: 40px;
            padding: 20px 40px;
            border-radius: 0 0 10px 10px;
            display: flex;
            justify-content: space-between;

            .right {
              color: #fff;
              height: 40px;
              line-height: 40px;
              display: flex;
              align-content: center;

              .title {
                font-size: 20px;
                margin-right: 40px;

                .num {
                  font-size: 30px;
                  font-weight: 600;
                  color: #ff0003;
                }
              }
            }
          }
        }
      }
    }
  }
</style>
