<template>
  <div class="product" style="padding-top: 46px">
    <van-nav-bar title="产品" class="van-nav-bar-my-fixed" fixed />
    <div v-loading="loading" class="clear">
      <div class="product-kucun clear">
        <ul>
          <li
            v-for="(pitem, index) in productList"
            :key="pitem + index"
            @click="changePitem(index)"
          >
            <div class="input-radio" :class="{ checked: radioV === pitem.id }">
              <div class="radio-box">
                <div class="radio-check"></div>
              </div>
            </div>

            <img :src="pitem.img" alt="" />
            <div>
              <p>{{ pitem.name }}</p>
              <p>
                可用库存：{{ pitem.stock }}{{ pitem.unit }}/{{ pitem.weight }}kg
              </p>
            </div>
          </li>
        </ul>
      </div>
      <div v-if="ad && ad.id" @click="getaddress" class="item-ad clear">
        <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 clear">添加地址</div>
      <div class="product-footer clear">
        <div class="fl">
          <input-number :numb="num" :max="stock" @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 resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/product/index";
import { getGoodsUnit, getGoodsNum, getAd } from "@/utils/auth";
export default {
  mixins: [resToken],
  data() {
    return {
      num: 0,
      total: 0,
      radioV: "",
      address: [],
      unitist: [],
      productList: [],
      stock: 0,
      ad: null,
    };
  },
  mounted() {
    this.ad = getAd() ? JSON.parse(getAd()) : {};
    this.num = isNaN(getGoodsNum()) ? 0 : parseInt(getGoodsNum());
    if (this.ad && this.ad.id) {
      this.initData(this.ad.id);
    }
    this.getStock();
  
  },

  methods: {
    changePitem(index) {
      this.radioV = this.productList[index].id;
      this.stock = this.productList[index].stock;

      if (this.num > this.stock) {
        this.num = this.stock;
      }
    },
    async getaddress() {
      let numRes = await this.set_user_goodsNum(this.num);
      console.log("保存时单位：" + this.radioV);
      let unitRes = await this.set_user_goodsUnit(this.radioV);
      if (numRes && numRes.code === 0 && unitRes && unitRes.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 = parseInt(res.data.stock);
            await this.getUnitist();
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.total = 0;
        }
      }
    },
    async getUnitist() {
      if (!this.loading) {
        let res = await asyncRequest.unitist({});
        if (res && res.code == 0 && res.data && res.data.list) {
          this.unitist = res.data.list;
          this.distributeGoods();
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.unitist = [];
        }
      }
    },
    distributeGoods() {
      if (this.unitist.length > 0) {
        this.productList = [];
        this.unitist.forEach((v1) => {
          let item = {
            id: v1.id,
            name: v1.id === "1" ? "藏金1745普通装" : "藏金1745礼盒",
            img: require(`@/assets/images/product/unit${v1.id}.png`),
            stock: parseInt(this.total / parseInt(v1.weight)),
            weight: v1.weight,
            unit: v1.name,
          };
          this.productList.push(item);
        });
        let index = this.productList.findIndex((v1) => {
          return v1.id == getGoodsUnit() + "";
        });

        this.changePitem(index === -1 ? 0 : index);
      }
    },
    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(11);
    },
    backNum(e) {
      this.num = e;
    },
    async placeOrder() {
      if (!this.loading) {
        if (this.ad && this.ad.id) {
          this.num = this.num;
          if (isNaN(this.num)) {
            this.num = 0;
          }
          if (this.stock === 0) {
            this.show_title("当前商品库存为0，无法购买！");
            return;
          }

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

          Dialog.confirm({
            title: "确认下单？",
          })
            .then(async () => {
              await this.placeHttpOrder();
            })
            .catch(() => {});
        } else {
          this.show_title("请选择收货地址！");
        }
      }
    },
    async placeHttpOrder() {
      this.loading = true;
      let model = {
        addrid: this.ad.id,
        num: this.num + "",
        unit_id: this.radioV,
      };
      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(res.msg);
      }
    },
    async set_user_goodsNum(num) {
      return new Promise((resolve, reject) => {
        this.$store.dispatch("user/set_goodsNum", num).then((res) => {
          resolve(res);
        });
      });
    },
    async set_user_goodsUnit(unit) {
      return new Promise((resolve, reject) => {
        this.$store.dispatch("user/set_goodsUnit", unit).then((res) => {
          resolve(res);
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.product {
  padding-left: 16px !important;
  padding-right: 16px !important;
  .product-kucun {
    width: 100%;
    padding: 0 0 30px 0;
    ul {
      float: left;
      width: 100%;
      li {
        float: left;
        width: 100%;
        padding: 24px 0 0 0;
        &:hover {
          cursor: pointer;
        }
        .input-radio {
          height: 80px;
          width: 15px;
          padding: 0;
          float: left;
          line-height: 80px;
          margin: 0 8px 0 0;
          padding: 0 1px;
          .radio-box {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            border: 1px solid #c0c0c0;
            padding: 2px;
            margin: 33px 0 0 0;
            box-sizing: border-box;
            .radio-check {
              width: 9px;
              height: 9px;
              background: transparent;
              box-sizing: border-box;
              border-radius: 50%;
            }
          }
          &.checked {
            .radio-box {
              border: 1px solid #f4d022;
              .radio-check {
                background: #f4d022;
              }
            }
          }
        }

        input {
          float: left;
          height: 80px;
          width: 17px;
          padding: 0;
          margin: 0 8px 0 0;
        }
        img {
          float: left;
          height: 84px;
          width: 130px;
          box-sizing: border-box;
          padding: 0 5px;
        }
        p {
          float: left;

          width: calc(100% - 155px);
          margin: 0;
          box-sizing: border-box;
          padding: 0 0 0 10px;
          &:first-child {
            margin-top: 8px;
            font-size: 17px;
            color: #333;
            height: 38px;
            line-height: 38px;
            font-weight: bolder;
          }
          &:last-child {
            height: 28px;
            line-height: 28px;
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }
  .item-ad {
    position: relative;
    color: #323233;
    font-size: 13px;
    line-height: 18px;
    padding: 10px 16px;
    border-radius: 12px;
    box-sizing: border-box;
    width: 100%;
    border: 1px solid #e0e0e0;
    .item-ad__name {
      font-size: 15px;
    }
    .item-ad__address {
      text-align: justify;
    }
  }
  .kong {
    position: relative;

    height: 40px;
    line-height: 40px;
    width: 100%;
    background: #f2f2f2;
    border-radius: 42px;
    color: #333;
    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: #f4d022;
      color: #333;
      border: 1px solid #f4d022;
      border-radius: 10px;
      overflow: hidden;
      margin: 0 16px 0 0;
    }
  }
}
</style>