<template>
  <div>
    <div v-if="!shop_com" class="right-main clearfix">
      <div class="float_left h-goods-div">
        <el-input
          ref="barCodeInput"
          v-model="shop"
          :placeholder="'请输入' + goods_key_sel"
          clearable
          class="input-with-select"
          style="width: 88%; margin-left: 20px"
          @keyup.enter.native="searchGoods"
        >
          <el-select
            slot="prepend"
            v-model="goods_key_sel"
            style="width: 120px"
            placeholder="请选择"
          >
            <el-option label="条形码" value="商品条形码"></el-option>
            <el-option label="商品名称" value="商品名称"></el-option>
          </el-select>
          <!--                      @click="pageChange(1)"-->
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="searchGoods"
          ></el-button>
        </el-input>
        <ul v-if="allShop === true">
          <li
            v-for="(item, index) in shop_shop"
            :key="index"
            class="shop_info clearfix"
            @click="selGoods(item.id)"
          >
            <div class="float_left">
              <img :src="item.images[0]" alt="" />
            </div>
            <div class="float_left goods-info">
              <p>{{ item.title }}</p>
              <div>
                <span class="price-color" style="margin-right: 8px">
                  ￥{{ item.minSalePrice }}
                </span>
                <span style="font-size: 12px; color: #999">
                  库存：{{ item.inventorTotal }}
                </span>
              </div>
            </div>
          </li>
        </ul>

        <FooterPage
          :page-size="pageSize"
          :total-page.sync="total"
          :current-page.sync="page"
          @pageChange="pageChange"
          @sizeChange="sizeChange"
        ></FooterPage>
      </div>
      <!--                  商品分类-->
      <div class="cate-div">
        <p
          class="cate-li"
          :class="[!cate_id ? 'cate-on' : '']"
          @click="changeCate()"
        >
          全部
        </p>
        <p
          v-for="(item, index) in classify_list"
          :key="index"
          class="cate-li"
          :class="[cate_id === item.id ? 'cate-on' : '']"
          @click="changeCate(item)"
        >
          {{ item.title }}
        </p>
      </div>
    </div>
    <div v-else class="right-main">
      <div>
        <div class="head_back">
          <i class="el-icon-back"></i>
          <span style="margin-left: 6px" @click="goShop">返回</span>
          <span class="head_line"></span>
          <span class="head-back-tit">选择规格</span>
        </div>
        <div class="shop_info clearfix">
          <div class="float_left">
            <img :src="shop_all.images[0]" alt="" />
          </div>
          <div class="float_right goods-info">
            <p>
              {{ shop_all.title }}
            </p>
            <div v-if="now_sku_data.id">
              <span class="price-color" style="margin-right: 10px">
                ￥{{ now_sku_data.salePrice }}
              </span>
              <span style="font-size: 12px; color: #999">
                库存：{{ now_sku_data.inventory }}
              </span>
            </div>
            <div v-else>
              <span class="price-color" style="margin-right: 10px">
                ￥{{ shop_all.minSalePrice }}
              </span>
              <span style="font-size: 12px; color: #999">
                库存：{{ shop_all.inventorTotal }}
              </span>
            </div>
          </div>
        </div>
        <div style="color: #333333">
          <p style="margin-left: 10px">单位</p>
          <ul>
            <li
              v-for="(item, index) in shop_all.unitData"
              :key="index"
              class="shop_color"
              :class="
                parseInt(spec_id_group[1]) === parseInt(item.unitId)
                  ? 'shop_color_li'
                  : 'shop_color'
              "
              @click="bindPickerChange(item.unitId, 1)"
            >
              {{ item.unitName }}
            </li>
          </ul>
        </div>
        <div
          v-for="(item, index) in shop_all.specGroup"
          :key="index"
          style="color: #333333"
        >
          <p style="margin-left: 10px">
            {{ item.groupSpec.specName }}
          </p>
          <ul>
            <li
              v-for="(res, resIndex) in item.params"
              :key="resIndex"
              class="shop_color"
              :class="
                parseInt(spec_id_group[index + 2]) === parseInt(res.specValueId)
                  ? 'shop_color_li'
                  : 'shop_color'
              "
              @click="
                bindPickerChange(
                  res.specValueId,
                  index + 2,
                  item.groupSpec.specId,
                  res
                )
              "
            >
              {{ res.specValueName }}
            </li>
          </ul>
        </div>
        <div style="color: #333333">
          <p style="margin-left: 10px">
            {{
              ["KG", "kg"].includes(now_sku_data.unitName) ? "重量/kg" : "数量"
            }}
          </p>
          <el-popover v-model="keyboard_visible" placement="bottom">
            <keyboard :lb-num="false" @click="numFnThree"></keyboard>
            <div slot="reference" style="width: 200px">
              <el-input v-model="num2"></el-input>
            </div>
          </el-popover>
        </div>
        <div
          v-if="['KG', 'kg'].includes(now_sku_data.unitName)"
          style="color: #333333"
        >
          <p style="margin-left: 10px">皮重/kg</p>
          <el-input
            v-model="pack_weight"
            style="width: 200px"
            readonly
          ></el-input>
        </div>
      </div>
      <div style="text-align: right; padding-right: 40px">
        <div
          v-if="['KG', 'kg'].includes(now_sku_data.unitName)"
          style="display: inline-block; padding-right: 10px"
        >
          <el-button @click="clearPack">去皮</el-button>
          <el-button @click="plusPack">清皮</el-button>
        </div>
        <el-button type="primary" @click="addCart">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import { getAllCategory, getGoodsByBarCode } from "@/api/goods";
  import Keyboard from "./Keyboard";
  import {
    addCartCashier,
    getCartByUser,
    getGoodsDetail,
    GoodsByCategory,
    updateBuyNumCashier,
  } from "@/api/Cashier";

  export default {
    name: "Goods",
    components: {
      Keyboard,
    },
    props: {
      shopCom: {
        type: Boolean,
        default: false,
      },
      allShop: {
        type: Boolean,
        default: false,
      },
      userCenterId: {
        type: [String, Number],
        default: 0,
      },
      numList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      nowSelShop: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    data() {
      return {
        shop: "",
        goods_key_sel: "商品条形码",
        shop_shop: [],
        total: 0,
        page: 1,
        pageSize: 10,
        goodsId: "",
        spec_id_group: [],
        shop_all: {
          images: [],
        },
        goodsBasicId: "",
        shopId: 1,
        now_sku_data: {},
        input_key_num: "",
        num2: "1",
        pack_weight: 0, // 商品皮重
        keyboard_visible: false, // 商品数量输入弹窗
        cate_id: "", // 当前已选择分类id
        add_cart_lodaing: false, // 加入购物车按钮加载中
        discount_list: [], // 优惠活动
        classify_list: [],
        shop_com: false,
      };
    },
    mounted() {
      this.shop_com = this.shopCom;
      // 获取焦点
      this.$nextTick(() => {
        this.$refs["barCodeInput"].focus();
      });
      this.getAllCategory();
      this.GoodsByCategory();
    },
    methods: {
      pageChange(val) {
        this.page = val;
        this.GoodsByCategory();
      },
      // 每页数据大小改变
      sizeChange(val) {
        this.pageSize = val;
        this.pageChange(1);
      },
      numFnThree(e, num) {
        if (!["x", "清除", "确定"].includes(num)) {
          this.numList.push(num);
        }
        if (num === "x") {
          this.num2 = this.num2.substring(0, this.num2.length - 1);
        } else if (num === "清除") {
          this.num2 = "";
          this.numList = [];
        } else if (num === "确定") {
          this.keyboard_visible = false;
        } else {
          this.num2 += num;
        }
      },
      // 去皮
      clearPack() {
        this.pack_weight = this.num2;
        this.num2 = 0;
      },
      // 清皮
      plusPack() {
        this.num2 = this.$NP.plus(this.num2, this.pack_weight);
        this.pack_weight = 0;
      },
      // 搜索商品
      searchGoods() {
        if (this.goods_key_sel === "商品条形码") {
          this.getGoodsByBarCode();
        } else {
          this.pageChange(1);
        }
      },
      // 根据条码获取商品
      async getGoodsByBarCode() {
        if (!this.shop) {
          this.$message.warning("请输入条形码");
          return;
        }
        const { data } = await getGoodsByBarCode({
          barCode: this.shop,
          userCenterId: this.userCenterId,
        });

        this.goodsId = data.goodsId;
        this.spec_id_group = data.index.split(":");
        this.shop_all = data.detail;
        this.goodsBasicId = data.detail.basicGoodsId;
        this.shopId = data.detail.shopId;

        this.now_sku_data = data.detail.specMultiple.find((item) => {
          return item.id === data.skuId;
        });

        // 选择商品后清除key
        this.shop = "";
        this.$refs["barCodeInput"].focus();
        if (["KG"].includes(this.now_sku_data.unitName)) {
          //打开输入弹窗
          this.$emit("openKeyboard", "-2");
          this.input_key_num = data.setNum || 1;
          this.$emit("inputKey", this.input_key_num);
        } else {
          this.num2 = data.setNum || 1;
          await this.addCart();
        }
      },
      // 切换分类
      changeCate(cate) {
        this.cate_id = cate ? cate.id : "";
        this.page = 1;
        this.GoodsByCategory();
      },
      // 商品列表
      async GoodsByCategory() {
        const data = await GoodsByCategory({
          page: this.page,
          pageSize: this.pageSize,
          categoryId: this.cate_id,
          keyword: this.shop,
          userCenterId: this.userCenterId,
          shopId: this.nowSelShop.id,
        });

        this.shop_shop = data.data;
        this.total = data.pageTotal;
      },
      // 选择商品
      selGoods(id) {
        // this.now_sku_data = {}
        this.goodsId = id;
        this.$emit("goodsId", this.goodsId);
        this.getGoodsDetail(id);
      },
      // 商品详情
      async getGoodsDetail(id) {
        // 选择商品后清除商品数量
        this.num2 = 1;
        const data = await getGoodsDetail(id, {
          userCenterId: this.userCenterId,
        });

        this.spec_id_group[0] = id;
        this.shop_all = data.data;
        this.goodsBasicId = data.data.basicGoodsId;
        this.shopId = data.data.shopId;
        if (["KG", "kg"].includes(this.shop_all.unitData.unitName)) {
          this.num2 = 0;
        }
        if (this.shop_all.specMultiple.length === 1) {
          this.num2 = 1;
          this.now_sku_data = this.shop_all.specMultiple[0];
          this.addCart();
        } else {
          this.shop_com = true;
        }
      },
      // 选择规格
      bindPickerChange(id, index, specId) {
        this.$set(this.spec_id_group, index, parseInt(id));
        // console.log(this.spec_id_group);
        if (this.spec_id_group.every((item) => !!item)) {
          const indexGroup = this.spec_id_group.join(":");
          // console.log(indexGroup);
          const nowSkuData = this.shop_all.specMultiple.find(
            (item) => item.index === indexGroup
          );
          if (nowSkuData) {
            this.now_sku_data = nowSkuData;
          }
          // console.log("now_sku_data:", this.now_sku_data);
        }
      },
      // 加入购物车
      async addCart() {
           console.log()
        if (!this.now_sku_data.id) {
          this.$message.warning("请选择规格");
          return;
        }
        if (!Number(this.num2) || Number(this.num2) <= 0) {
          this.$message.warning("请输入正确的商品数量");
          return;
        }
        const data = await addCartCashier({

          goodsData: [
            {
              skuId: this.now_sku_data.id,
              goodsId: this.goodsId,
              buyNum: this.num2,
              shopId: this.shopId,
              source: "4",
              goodsBasicId: this.goodsBasicId,
              warehouseId:this.shop_all.warehouseId
            },
          ],
          userCenterId: this.userCenterId,
        });

        this.$message.success("已选择");
        this.goShop();
        this.$emit("getCartByUser");
      },
      // 商品详情返回按钮
      goShop() {
        // 点击返回按钮重置数据
        this.now_sku_data = {};
        this.spec_id_group = [];
        this.shop_com = false;
      },
      // 获取分类列表
      async getAllCategory() {
        const { data } = await getAllCategory();

        if (JSON.stringify(data) === "{}") {
          this.classify_list = [];
        } else {
          this.classify_list = data;
        }
      },
    },
  };
</script>

<style scoped>
  .right-main {
    height: calc(99vh - 166px);
    overflow: auto;
  }
  .h-goods-div {
    width: 89.8%;
    height: 100%;
    overflow: auto;
  }

  .cate-div {
    float: right;
    overflow: auto;
    width: 10%;
    height: 100%;
    border-left: 1px solid #f2f2f2;
    text-align: center;
    color: #333333;
  }
  .shop_info {
    display: inline-block;
    width: 276px;
    border-radius: 4px;
    border: 1px solid #ededed;
    margin: 20px 10px 15px 10px;
    padding: 12px 12px 12px 10px;
    cursor: pointer;
    color: #333333;
    line-height: 18px;
  }
  .shop_info img {
    border: 1px solid #f4f4f4;
    border-radius: 4px;
    width: 68px;
    height: 68px;
  }

  .shop_info .goods-info {
    width: calc(100% - 80px);
    margin-left: 10px;
  }
  .goods-info > p {
    padding-bottom: 5px;
    color: #333333;
    height: 36px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
  .price-color {
    color: #f56c6c;
  }
  .cate-li {
    height: auto;
    line-height: 16px;
    padding: 16px 6px;
    cursor: pointer;
    /*background: rgba(32,83,212, 0.1);*/
    /*color: #409EFF;*/
  }

  .cate-on {
    background: rgb(236, 245, 255);
    color: #409eff;
  }
  .right-main {
    height: calc(99vh - 166px);
    overflow: auto;
  }
  .head_back {
    color: #ccc;
    font-size: 14px;
    cursor: pointer;
    height: 50px;
    line-height: 50px;
    padding-left: 20px;
  }
  .head_back .head-back-tit {
    color: #333333;
  }

  .head_back .head_line {
    height: 20px;
    width: 1px;
    background-color: #ededed;
    display: inline-block;
    margin: 4px 10px -6px 10px;
  }
  .shop_color {
    width: 148px;
    height: 48px;
    line-height: 48px;
    background: #f5f6fa;
    border: 1px solid #f5f6fa;
    border-radius: 4px;
    padding: 0 20px;
    text-align: center;
    margin: 0 14px 14px 0;
    cursor: pointer;
    display: inline-block;
  }
  .shop_color_li {
    background: rgb(236, 245, 255);
    color: #409eff;
    border: 1px solid #409eff;
  }
</style>
