<template>
  <Container>
    <div v-if="$accessCheck($Access.PublishGoodsSearch)" slot="right">
      <el-form :inline="true" size="small">
        <el-form-item label="关键词">
          <el-input
            v-model="keyword"
            style="width: 220px"
            placeholder="商品名称/编码/条码"
            clearable
            @keyup.enter.native="pageChange(1)"
            @clear="pageChange(1)"
          >
            <el-button slot="append" @click="pageChange(1)">
              <i class="el-icon-search"></i>
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="分类">
          <GoodsCategory
            v-model="form.categoryPath"
            :width="160"
            check-strictly
            clearable
            size="small"
            @change="goodsChane"
          />
        </el-form-item>

        <el-form-item label="销售状态">
          <el-select
            v-model="enableStatus"
            placeholder="销售状态"
            style="width: 100px"
            clearable
            @change="pageChange(1)"
          >
            <el-option label="上架" :value="5"></el-option>
            <el-option label="下架" :value="4"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div slot="left">
      <el-button
        v-if="
          $accessCheck($Access.PublishGoodsAddGoods) ||
          $accessCheck($Access.PublishGoodsAddBasicAndPublishGoods)
        "
        size="small"
        type="primary"
        @click="openAddGoods"
      >
        发布商品
      </el-button>
      <!--      <el-button size="small" type="primary" plain @click="getData(1)">-->
      <!--        导出-->
      <!--      </el-button>-->
    </div>
    <el-table
      ref="goodsTable"
      :data="goods_data"
      @selection-change="selectionChange"
      @expand-change="showSpec"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      ></el-table-column>
      <el-table-column
        prop="id"
        label="ID"
        fixed="left"
        width="80"
      ></el-table-column>
      <el-table-column
        prop="materialName"
        label="商品"
        fixed="left"
        min-width="220"
      >
        <template slot-scope="scope">
          <div class="clearfix">
            <div class="float_left">
              <el-image fit="cover" :src="scope.row.images[0]"></el-image>
            </div>
            <div class="float_left goods-name-view" style="margin-left: 10px">
              <div class="goods-title">
                {{ scope.row.title }}
              </div>
              <div class="goods-no">
                {{ scope.row.code }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="categoryName"
        label="商品分类"
        min-width="100"
      ></el-table-column>
      <el-table-column label="规格" width="80">
        <template slot-scope="scope">
          <el-button size="mini" @click="toggleRowExpansion(scope.row)">
            {{ scope.row.specTotal }}种
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="" width="40" type="expand">
        <template slot-scope="scope">
          <ul class="sku-ul">
            <li
              v-for="(item, index) in scope.row.goods_sku_list"
              :key="index"
              class="sku-li"
            >
              <div class="clearfix">
                <div class="float_left">
                  <img
                    class="sku-img"
                    :src="item.specImage || scope.row.images[0]"
                    alt=""
                  />
                </div>
                <div class="sku-info float_left">
                  <p>
                    <span class="label">规格:</span>
                    {{ item.unitName }};{{ item.specValueName }}
                  </p>
                  <p>
                    <span class="label">库存:</span>
                    {{ Number(item.inventory) }}；
                    <span class="label">销量:</span>
                    {{ item.salesNum }}
                  </p>
                  <p>
                    <span class="label">起订量:</span>
                    {{ item.setNum }}；
                    <span class="label">市场价:</span>
                    ¥{{ item.marketPrice }}
                  </p>
                  <p>
                    <span class="label">阶梯价:</span>
                    {{ item.enabledLadder === 1 ? "是" : "否" }}；
                    <span v-if="!item.enabledLadder">
                      <span class="label">销售价:</span>
                      ¥{{ item.salePrice }}
                    </span>
                  </p>
                </div>
              </div>
              <div v-if="item.enabledLadder" class="clearfix">
                <div class="float_left" style="width: 50px; margin-right: 10px">
                  销售价:
                </div>
                <div class="float_left">
                  <p v-for="(price, indexP) in item.ladderPrice" :key="indexP">
                    <span>
                      数量:
                      <span style="color: #ff4040">
                        {{ price.from }}-{{
                          indexP === item.ladderPrice.length - 1
                            ? "∞"
                            : price.to
                        }}
                      </span>
                      ,
                    </span>
                    <span>
                      价格:
                      <span style="color: #ff4040">¥{{ price.price }}</span>
                      ;
                    </span>
                  </p>
                </div>
              </div>
            </li>
          </ul>
        </template>
      </el-table-column>

      <el-table-column
        prop="unitNameMaster"
        label="基本单位"
        min-width="80"
      ></el-table-column>
      <el-table-column prop="masterInventory" label="总库存" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.inventorTotal - 0 }}
        </template>
      </el-table-column>
      <el-table-column prop="virtualSalesNum" label="虚拟销量" min-width="80">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.sale_false_visible"
            v-model="virtual_sales_num"
            style="width: 100%"
            :controls="false"
            size="small"
            @keyup.enter.native="setSalesNum(scope.$index)"
            @blur="setSalesNum(scope.$index)"
          ></el-input-number>
          <div v-else class="click-div" @click="showSetSaleNum(scope.$index)">
            {{ scope.row.virtualSalesNum }}
            <el-button
              v-if="$accessCheck($Access.PublishGoodssetSalesNum)"
              type="text"
              icon="el-icon-edit"
            ></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="salesNum"
        label="真实销量"
        min-width="80"
      ></el-table-column>
      <el-table-column prop="enableStatus" label="当前状态" min-width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.enableStatus === 5" class="success-status">
            上架
          </span>
          <span v-else class="danger-status">下架</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="shopName"
        label="销售店铺"
        show-overflow-tooltip
        min-width="120"
      ></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160">
        <template slot-scope="scope">
          {{ $_common.formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" header- fixed="right" width="260">
        <template slot-scope="scope">
          <el-button
            v-if="$accessCheck($Access.PublishGoodsUpdateEnableStatus)"
            type="text"
            @click="changeGoodsStatus(scope.row)"
          >
            {{ scope.row.enableStatus === 5 ? "下架" : "上架" }}
          </el-button>
          <!--<el-button
              v-if="
                $accessCheck($Access.PublishGoodsEditGoods) &&
                $accessCheck($Access.PublishGoodsGetGoodsInfo)
              "
              type="text"
              @click="openPriceModel(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="$accessCheck($Access.PublishGoodsDelGoods)"
              type="text"
              @click="delData(scope.row.id)"
            >
              删除
            </el-button>-->
          <el-button
            v-if="$accessCheck($Access.PublishGoodssetTop)"
            type="text"
            @click="setTop(scope.row.id)"
          >
            {{ scope.row.topTime !== 0 ? "取消置顶" : "置顶" }}
          </el-button>
          <!--          <el-button type="text">查看</el-button>-->
          <!--          <el-button type="text" @click="goodsSet(scope.row)">设置</el-button>-->
          <el-popover
            placement="top-start"
            width="200"
            trigger="hover"
            @show="createwxaqrcode(scope.row.id)"
          >
            <div style="text-align: center">
              <p
                style="
                  font-size: 14px;
                  font-weight: bold;
                  padding-bottom: 10px;
                  border-bottom: 1px solid #eee;
                "
              >
                推广码
              </p>
              <img style="width: 130px; margin: 10px 0" :src="wxaqrcode" />
              <p>
                <a :href="wxaqrcode" target="_blank">下载</a>
              </p>
            </div>
            <el-button slot="reference" type="text">推广码</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer
      class="edit-drawer"
      :title="goods_name"
      :visible.sync="is_price"
      direction="rtl"
      size="50%"
    >
      <EditGoods
        v-if="is_price"
        :goods-id="price_goods_detail.id"
        @subData="editsubData"
      />
    </el-drawer>
    <FooterPage
      :page-size="pageSize"
      :total-page.sync="total"
      :current-page.sync="page"
      @pageChange="pageChange"
      @sizeChange="sizeChange"
    >
      <div slot="btn-div" class="foot-btn-div">
        <span class="batch-checkbox">
          <el-checkbox
            v-model="checkedAll"
            @change="checkAllChange"
          ></el-checkbox>
        </span>
        <el-dropdown
          v-if="$accessCheck($Access.PublishGoodsUpdateEnableStatus)"
        >
          <el-button size="mini">
            批量上下架
            <i class="el-icon-caret-top"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <div class="dropdown-div" @click="BatchUnloading(5)">
                批量上架
              </div>
            </el-dropdown-item>
            <el-dropdown-item>
              <div class="dropdown-div" @click="BatchUnloading(4)">
                批量下架
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </FooterPage>
    <BrandSelModel
      v-if="sel_brand"
      :is-check="false"
      :dialog-visible="sel_brand"
      @close="sel_brand = false"
      @confirm="brandConfirm"
    />
    <GoodsSet
      :is-show="is_set"
      :set-tit="set_tit"
      @close="is_set = false"
      @confirm="getData"
    />
    <GoodsSetOnly
      :is-show="set_show"
      @close="set_show = false"
      @confirm="getData"
    />
  </Container>
</template>

<script>
  import GoodsCategory from "@/component/common/GoodsCategory.vue";
  import BrandSelModel from "@/component/goods/BrandSelModel.vue";
  import EditGoods from "@/views/goods/sale/AddGoods";
  import SelectShop from "@/component/goods/SelectShop.vue";

  import { apiUrl } from "@/config/settings";
  import {
    setSalesNum,
    getGoodsInfo,
    getAllGoods,
    exportGetAllGoods,
    searchGood,
    exportSearchGood,
    delGoods,
    setTop,
    BatchUnloading,
    GoodsUpdateEnableStatus,
    batchGoodsExpress,
  } from "@/api/goods";
  import { createwxaqrcode } from "@/api/common";
  import GoodsSet from "@/views/Multistore/store/components/GoodsSet.vue";
  import GoodsSetOnly from "@/views/Multistore/store/components/GoodsSetOnly.vue";
  export default {
    name: "PublishGoods",
    components: {
      GoodsCategory,
      EditGoods,
      BrandSelModel,
      GoodsSet,
      GoodsSetOnly,
    },
    data() {
      return {
        imgUrl:
          "http://image.qianniao.vip/160672655503427/ff74e17b6ff82b13e5a84afc84451779/22182da790403ef539354be01f3efcd1.jpg",
        virtual_sales_num: 0, //虚拟销量

        goods_sku_list: [],
        checkedAll: false,
        is_price: false,
        sku_visible: false,
        sku_goods_name: "",
        goods_name: "",
        keyword: "",
        brandId: "",
        categoryId: "",
        enableStatus: "",
        shopId: "",
        sel_brand: false,
        total: 0,
        page: 1,
        pageSize: 10,
        goods_data: [], // table 数据
        choose_data: [],
        form: {
          categoryPath: [],
          search_key: "",
          brand: "",
          shop: "",
          enableStatus: "",
        },
        price_goods_detail: {},
        inSales: 0,
        inStock: 0,
        spec_loading: false,
        assistForm: {},
        more_sub_btn: false,
        unit_show: false,
        set_show: false, // 商品设置
        is_set: false, // 商品批量设置
        set_tit: "",
        wxaqrcode: "", // 小程序码
      };
    },
    created() {
      if (this.$route.name === "GoodsSale") {
        this.inSales = 5;
      } else if (this.$route.name === "SoldOut") {
        this.inStock = 4;
      } else if (this.$route.name === "InWarehouse") {
        this.inStock = 5;
      }
      if (this.$route.query.shopId) {
        this.shopId = parseInt(this.$route.query.shopId);
      }

      this.getData();
    },
    activated() {
      if (this.$_isInit()) return;
      this.getData();
    },
    methods: {
      async setSalesNum(index) {
        if (this.virtual_sales_num <= 0) {
          this.$message.warning("请输入大于0的值");
          return;
        }
        const data = await setSalesNum({
          id: this.goods_data[index].id,
          val: this.virtual_sales_num,
        });

        this.goods_data[index].sale_false_visible = false;
        this.getData();
      },
      showSetSaleNum(index) {
        this.virtual_sales_num = this.goods_data[index].virtualSalesNum;
        this.goods_data[index].sale_false_visible = true;
      },
      openAddGoods() {
        if (parseInt(this.$store.getters["MUser/enterpriseScope"]) === 4) {
          this.$router.push("/goods/sale/AddGoodsOneStore");
        } else {
          this.$router.push("/goods/sale/AddGoods");
        }
      },
      // 用于可展开表格与树形表格，切换某一行的展开状态，如果使用了第二个参数，则是设置这一行展开与否（expanded 为 true 则展开）
      toggleRowExpansion(row) {
        this.$refs.goodsTable.toggleRowExpansion(row);
        this.showSpec(row);
      },
      async showSpec(row) {
        const index = this.goods_data.findIndex((item) => item.id === row.id);
        if (!this.goods_data[index].goods_sku_list.length) {
          const { data } = await getGoodsInfo(row.id);
          if (data.specType === 2) {
            this.$nextTick(() => {
              this.goods_data[index].goods_sku_list = data.specMultiple.map(
                (item) => {
                  const specValueName = item.specGroup
                    .map((itemS) => {
                      return itemS.specValueName;
                    })
                    .join(";");
                  return {
                    ...item,
                    specValueName: specValueName,
                  };
                }
              );
            });
          } else if (data.specType === 1) {
            this.$nextTick(() => {
              this.goods_data[index].goods_sku_list = data.specMultiple.map(
                (item) => {
                  return {
                    ...item,
                    specValueName: "",
                  };
                }
              );
            });
          }
        }
        // this.goods_data = target
      },
      delBrand() {
        this.form.brand = "";
        this.brandId = "";
        this.pageChange(1);
      },
      // 批量选择
      selectionChange(val) {
        this.checkedAll = val.length === this.goods_data.length;
        this.choose_data = val;
      },
      // 编辑完成回调
      editsubData() {
        this.getData();
      },
      // 调整价格 编辑查看
      openPriceModel(row) {
        if (parseInt(this.$store.getters["MUser/enterpriseScope"]) === 5) {
          this.is_price = true;
          this.goods_name = row.title;
          this.price_goods_detail = row;
        } else {
          this.$router.push(`/goods/sale/EditGoodsOneStore/${row.id}`);
        }
      },

      // 获取列表
      async getAllGoods(exports) {
        let params = {
          page: this.page,
          pageSize: this.pageSize,
        };
        if (this.inSales) {
          params.inSales = this.inSales;
        }
        if (this.inStock) {
          params.inStock = this.inStock;
        }
        if (exports) {
          const data = await exportGetAllGoods({
            ...params,
            export: 1,
          });
        } else {
          const data = await getAllGoods(params);

          this.goods_data = data.data.map((item) => {
            return {
              ...item,
              sale_false_visible: false,
              goods_sku_list: [],
            };
          });
          this.total = data.pageTotal;
        }
      },
      //  搜索商品 searchGood
      async searchGood(exports) {
        let params = {
          keyword: this.keyword,
          brandId: this.brandId,
          categoryPath: this.form.categoryPath.join(","),
          enableStatus: this.enableStatus,
          shopId: this.shopId,
          page: this.page,
          pageSize: this.pageSize,
        };
        if (this.inSales) {
          params.inSales = this.inSales;
        }
        if (this.inStock) {
          params.inStock = this.inStock;
        }
        if (exports) {
          const data = await exportSearchGood({
            ...params,
            export: 1,
          });
        } else {
          const data = await searchGood(params);

          this.goods_data = data.data.map((item) => {
            return {
              ...item,
              sale_false_visible: false,
            };
          });
          this.total = data.pageTotal;
        }
      },
      // 判断当前使用方法为列表接口还是搜索引擎接口 获取列表数据
      getData(exports) {
        // 搜索参数规整
        const obj = {
          keyword: this.keyword,
          brandId: this.brandId,
          categoryPath: this.form.categoryPath.join(","),
          enableStatus: this.enableStatus,
          shopId: this.shopId,
        };
        const isKey = this.$_common.isSerch(obj);
        if (isKey) {
          this.searchGood(exports);
        } else {
          this.getAllGoods(exports);
        }
      },
      // 分类搜索
      goodsChane(val) {
        this.pageChange(1);
      },
      // 品牌搜索
      brandConfirm(row) {
        this.form.brand = row[0].title;
        this.brandId = row[0].id;
        this.pageChange(1);
      },
      // 删除商品
      async delData(id) {
        this.$confirm("确定要删除该条商品吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await delGoods(id);

          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getData();
        });
      },
      // 置顶商品
      async setTop(id) {
        this.$confirm("是否要将该商品置顶?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await setTop(id);

          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.getData();
        });
      },
      // 商品上下架
      changeGoodsStatus(row) {
        if (!this.$accessCheck(this.$Access.PublishGoodsUpdateEnableStatus)) {
          return;
        }
        const tit =
          row.enableStatus === 5
            ? "是否要下架该商品？"
            : "是否要将该商品上架？";
        this.$confirm(tit, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await GoodsUpdateEnableStatus({
            id: row.id,
            enableStatus: row.enableStatus === 4 ? 5 : 4,
          });

          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.getData();
        });
      },
      //  批量上下架
      async BatchUnloading(enableStatus) {
        let title =
          enableStatus === 4
            ? "确定要批量下架这些商品吗？"
            : "确定要批量上架这些商品吗？";
        if (!this.choose_data.length) {
          this.$message.warning("请选择要操作的商品");
          return;
        }
        this.$confirm(title, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          if (!this.choose_data.length) {
            this.$message.warning("请选择要操作的商品");
            return;
          }
          const idData = this.choose_data.map((item) => {
            return item.id;
          });
          const data = await BatchUnloading({
            id: idData,
            enableStatus: enableStatus,
          });
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.getData();
        });
      },
      // 切页
      pageChange(val) {
        this.page = val;
        this.getData();
      },
      // 每页数据大小改变
      sizeChange(val) {
        this.pageSize = val;
        this.pageChange(1);
      },
      checkAllChange() {
        this.$refs.goodsTable.toggleAllSelection();
      },
      async createwxaqrcode(goodsId) {
        const { data } = await createwxaqrcode({
          path: "pagesT/product/product",
          params: goodsId,
        });
        this.wxaqrcode = apiUrl.UPLOAD_URL + data;
      },
      goodsSet(row) {
        this.set_show = true;
      },
    },
  };
</script>
<style scoped lang="scss">
  .open-span,
  .disabled-span {
    cursor: pointer;
  }
  .open-span:hover,
  .disabled-span:hover {
    color: #1c8fef;
  }
  .goods-name-view {
    width: calc(100% - 76px);
  }
  .goods-title {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
  .sku-ul {
    .sku-li {
      display: inline-block;
      margin-right: 10px;
      border: 1px solid #ebeef5;
      padding: 10px;
      width: 294px;
      vertical-align: middle;
      .sku-img {
        width: 50px;
        margin-right: 8px;
      }
      .sku-info {
        line-height: 23px;
        color: #111111;
        .label {
          display: inline-block;
          width: 50px;
          color: #666666;
          text-align: right;
        }
      }
    }
  }
</style>
