<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import { cartListApi, cartDeleteApi, cartChangeApi } from "@/api/store.js";
import price from "./price.vue";
import mitt from "@/utils/mitt.js";
import { useUserStore } from "@/store/user.js"

const list = ref([]);
const allPrice = ref(0); //商品总价
const costPrice = ref(0); //商品原价
const discounts = ref(0); //优惠金额

const userStore = useUserStore();

const clearAll = () => {
  let cart_id = [];
  list.value.map((item) => {
    cart_id.push(item.cart_id);
  });
  if (cart_id.length == 0) return;
  deleteShop(cart_id);
};

const deleteOne = (cart_id) => {
  list.value = list.value.filter((item) => item.cart_id != cart_id);
  deleteShop([cart_id]);
};

const deleteShop = (arr) => {
  cartDeleteApi({
    cart_id: arr,
  }).then((res) => {
    console.log(res);
    getList();
  });
};

const getList = () => {
  allPrice.value = 0;
  costPrice.value = 0;
  discounts.value = 0;
  cartListApi({
      staff_id: userStore.userInfo.service.service_id,
  }).then((res) => {
    if (res.data?.list?.length > 0) {
      list.value = res.data.list[0].list;
      list.value.forEach((item) => {
        allPrice.value += item.productAttr.price * item.cart_num;
      });
      costPrice.value = allPrice.value;
    } else list.value = [];
  });
};
getList();

const emit = defineEmits(["goPay","editAttr"]);

const goPay = () => {
  emit("goPay");
};

const changeCartNum = (val, old) => {
  cartChangeApi(val.cart_id, {
    cart_num: val.cart_num,
  }).then((res) => {
    allPrice.value = 0;
    list.value.forEach((item) => {
      allPrice.value += item.productAttr.price * item.cart_num;
    });
    costPrice.value = allPrice.value;
  });
};

const editAttr = (data)=>{
  emit("editPupop", data);
}

const editItem = (id, data)=>{
  cartChangeApi(id, data).then((res) => {
    getList()
  });
}

const changeAllPrice = (price)=>{
  discounts.value = costPrice.value - price;
  allPrice.value = +price;
  nextTick(()=>{
    setTimeout(()=>{
      showPrice(false)
    }, 150)
  })
}

const nowPrice = ref(0);
const priceRef = ref(null);
const showPrice = (type=true)=>{
  priceRef.value.show(type, costPrice.value);
}

defineExpose({
  getList,
  list,
  editItem,
  discounts,
  allPrice
});

// 键盘事件
const ainsert = () => {
  if(priceRef.value.dialogVisible) priceRef.value.dialogVisible = false;
  else showPrice();
};
const adelete = () => {
  if(list.value.length > 0) clearAll();
};
onMounted(() => {
  mitt.on("insert", ainsert);
  mitt.on("delete", adelete);
});

onUnmounted(() => {
  mitt.off("insert", ainsert);
  mitt.off("delete", adelete);
});


</script>

<template>
  <div class="my-order">
    <div class="header-nav">
      <div class="nav-item">
        已选购 <span>{{ list.length }}</span> 件
      </div>
      <div class="nav-item-clear" @click="clearAll">
        <el-icon><Delete /></el-icon>清空 (Delete)
      </div>
    </div>
    <div class="order-list">
      <el-empty v-if="list.length == 0" description="请点击右侧添加商品" />
      <div v-else class="order-item" v-for="(item, index) in list" :key="index">
        <el-image loading="lazy"
          class="order-item-img"
          :src="
            (item.productAttr && item.productAttr.image) || item.product.image
          "
        ></el-image>
        <div class="order-item-info">
          <div class="order-item-title">
            <div class="title">{{ item.spu.store_name }}</div>
            <div class="delete" @click="deleteOne(item.cart_id)">删除</div>
          </div>
          <div class="order-item-sku">
            <span style="display: flex;align-items: center;" @click="editAttr(item)">商品规格: {{ item.productAttr.sku || '默认规格' }}<el-icon size="16" style="margin-left: 0.2rem;"><ArrowDown /></el-icon></span>
          </div>
          <div class="order-item-price">
            <div>
              ¥<span>{{ item.productAttr.price }}</span>
            </div>
            <div>
              <el-input-number
                v-model="item.cart_num"
                step-strictly
                :min="1"
                :step="1"
                @change="changeCartNum(item)"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="order-footer">
      <div class="order-total">
        <div class="price">
          <div class="total-item">
            实付:
            <span
              >¥<span style="font-size: 1.4rem">{{
                allPrice.toFixed(2)
              }}</span></span
            >
          </div>
          <div class="total-item">
            优惠:
            <span
              >¥<span>{{ discounts.toFixed(2) }}</span></span
            >
          </div>
        </div>
        <div class="update-price">
          <el-button class="btn" type="primary" @click="showPrice" size="small">改价 (Insert)</el-button>
        </div>
      </div>
      <div class="order-btn">
        <el-button class="btn" type="primary" @click="goPay" :disabled="list.length == 0"
          >立即结账 (F9)</el-button
        >
      </div>
    </div>
    <price ref="priceRef" @changeAllPrice="changeAllPrice"></price>
  </div>
</template>

<style scoped lang="scss">
.my-order {
  border-radius: 1.2rem;
  height: 100%;
  background-color: #fff;
  width: 30rem;
  position: relative;
  overflow: hidden;

  .header-nav {
    display: flex;
    justify-content: space-between;
    padding: 1rem;
    height: 1.5rem;
    border-bottom: 1px solid #eee;

    span {
      color: #ff4a00;
    }
    .nav-item-clear {
      display: flex;
      align-items: center;
      font-size: 0.8rem;
      cursor: pointer;
    }
  }
  .order-list {
    height: calc(100vh - 100px - 14rem);
    overflow-y: auto;
    .order-item {
      display: flex;
      padding: 1rem;
      border-bottom: 1px solid #eee;

      .order-item-img {
        width: 5rem;
        height: 5rem;
        border-radius: 0.5rem;
      }
      .order-item-info {
        flex: 1;
        box-sizing: border-box;
        padding-left: 0.75rem;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        & > div {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .order-item-title {
          .title {
            width: 18rem;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .delete {
            color: #1890ff;
            cursor: pointer;
          }
        }
        .order-item-sku {
          cursor: pointer;
          font-size: 0.8rem;
          color: #999;
        }
      }
    }
  }
  .order-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    box-shadow: 0 -1px 0.625rem #eee;

    .order-total {
      height: 2.5rem;
      padding: 1rem 2rem;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #eee;
      align-items: center;
      .price {
        display: flex;
        align-items: center;
        .total-item {
          padding-right: 1.5rem;
          span {
            color: #f5222d;
          }
        }
      }
      .update-price {
        .btn {
          border-radius: 3rem;
          font-size: 1rem;
        }
      }
    }
    .order-btn {
      height: 3.2rem;
      padding: 1rem 1.5rem;
      .btn {
        width: 100%;
        height: 100%;
        font-size: 1.2rem;
        border-radius: 3rem;
      }
    }
  }
}
</style>
