<template>
  <div class="product" style="padding-top: 46px">
    <van-nav-bar title="产品" class="van-nav-bar-my-fixed" fixed />
    <div v-loading="loading" class="">
      <div class="kucun">可用库存：{{ total }}袋/2.5kg</div>
      <div v-if="ad && ad.id" @click="getaddress" class="item-ad">
        <p class="item-ad__name">
          <span>{{ ad.name }}</span
          ><span class="fr">{{ ad.tel }}</span>
        </p>

        <p class="item-ad__address">
          <span>{{ ad.address }}</span>
        </p>
      </div>
      <div v-else @click="getaddress" class="kong">添加地址</div>
      <div class="product-footer clear">
        <div class="fl">
          <input-number
            :numb="num || goodsNum"
            :max="total"
            @backNum="backNum"
          />
        </div>
        <van-button
          type="info"
          class="fr"
          style="width: 30%"
          @click="placeOrder"
          >确认下单</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { Dialog } from "vant";
import { mapGetters } from "vuex";
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/product/index";
export default {
  mixins: [resToken],
  computed: {
    ...mapGetters(["ad", "goodsNum"]),
  },
  data() {
    return {
      num: this.goodsNum,
      total: 0,
      address: [],
    };
  },
  mounted() {
    if (this.ad && this.ad.id) {
      this.initData(this.ad.id);
    }

    this.getStock();
  },

  methods: {
    async getaddress() {
      let res = await this.set_user_goodsNum(this.num || this.goodsNum);
      if (res && res.code === 0) {
        window.vm.$router.push({
          path: "/address",
          query: {
            id: this.ad && this.ad.id ? this.ad.id : "0",
          },
        });
      }
    },
    async getStock() {
      if (!this.loading) {
        let res = await asyncRequest.get_stock({});
        if (res && res.code == 0) {
          this.total = res.data.stock;
        } else if (res.code === 10011) {
          this.show_title("连接超时，请重新登录！");
          setTimeout(() => {
            this.logOut();
          }, 3000);
        } else {
          // this.show_title("获取个人信息失败！");
        }
      }
    },
    async initData(id) {
      const res = await asyncRequest.addrdetail({ id: id });
      if (res && res.code === 0) {
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$store.dispatch("user/set_ad", {}).then((res) => {
          console.log(res);
        });
      }
    },
    backNum(e) {
      this.num = e;
    },
    handleChange(value) {
      console.log(value);
    },
    async placeOrder() {
      if (!this.loading) {
        if (this.ad && this.ad.id) {
          this.num = this.num || this.goodsNum;
          if (isNaN(this.num)) {
            this.num = 0;
          }
          if (this.total === 0) {
            this.show_title("当前商品库存为0，无法购买！");
            return;
          }

          if (this.num === 0) {
            this.show_title("购买数量不能为0！");
            return;
          }

          Dialog.confirm({
            title: "确认下单？",
            // message: "确认删除该地址？",
          })
            .then(async () => {
              await this.placeHttpOrder();
            })
            .catch(() => {
              // on cancel
            });
        } else {
          this.show_title("请选择收货地址！");
        }
      }
    },
    async placeHttpOrder() {
      this.loading = true;
      let model = {
        addrid: this.ad.id,
        num: this.num + "",
      };
      let res = await asyncRequest.add(model);
      this.loading = false;
      if (res && res.code == 0) {
        let setRes = await this.set_user_goodsNum(0);
        if (setRes && setRes.code === 0) {
          window.vm.$router.push({
            path: "/orderRes",
            query: {
              id: res.data.orderid,
            },
          });
        }
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.show_title("连接超时，请重新登录");
      }
    },
    async set_user_goodsNum(num) {
      return new Promise((resolve, reject) => {
        this.$store.dispatch("user/set_goodsNum", num).then((res) => {
          resolve(res);
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.product {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background: #ffffff;
  padding-left: 16px;
  padding-right: 16px;
  .kucun {
    margin: 17px 0 15px 0;
    background: #f7f7f7;
    border-radius: 10px;
    color: #333;
    padding: 20px 0;
    text-align: center;
  }
  .item-ad {
    color: #323233;
    font-size: 13px;
    line-height: 18px;
    padding: 10px 16px;
    border-radius: 12px;
    border: 1px solid #e0e0e0;
    .item-ad__name {
      font-size: 15px;
    }
    .item-ad__address {
      text-align: justify;
    }
  }
  .kong {
    height: 40px;
    line-height: 40px;
    width: 100%;
    background: #dbdbdb;
    border-radius: 42px;
    color: #fff;
    text-align: center;
  }
  .product-footer {
    position: absolute;
    background: #f7f7f7;
    bottom: 50px;
    left: 0;
    z-index: 3;
    width: 100%;
    height: 44px;
    .fl {
      padding: 5px 0 0 16px;
    }
    button {
      background: #fd762d;
      color: #fff;
      border: 1px solid #fd762d;
      border-radius: 10px;
      overflow: hidden;
      margin: 0 16px 0 0;
    }
  }
}
</style>