<template>
  <ContainerQuery>
    <div slot="left">
      <el-dropdown
        v-if="
          $accessCheck($Access.PublishGoodsAddGoods) ||
          $accessCheck($Access.PublishGoodsAddBasicAndPublishGoods)
        "
        split-button
        type="primary"
        @click="openAddGoods"
      >
        发布商品
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <div class="dropdown-div" @click="getAllGoodsList(1)">导出</div>
          </el-dropdown-item>
          <el-dropdown-item v-if="enterpriseScope == '4'">
            <div @click="$router.push('/goods/manageG/SingleGoodsImport')">
              导入
            </div>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button v-else size="small" type="primary" @click="getData(1)">
        导出
      </el-button>
    </div>
    <div v-if="$accessCheck($Access.PublishGoodsSearch)" slot="more">
      <el-form :inline="true" size="small">
        <el-form-item>
          <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>
          <GoodsCategory
            v-model="form.categoryPath"
            :width="160"
            check-strictly
            clearable
            size="small"
            @change="goodsChane"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="form.brand"
            style="width: 150px"
            placeholder="商品品牌"
            clearable
            @clear="delBrand"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="sel_brand = true"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="enableStatus"
            placeholder="销售状态"
            style="width: 150px"
            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-item>
          <SelectShop
            v-model="shopId"
            width="150"
            placeholder="销售店铺"
            @change="shopConfirm"
            @clear="delShop"
          />
        </el-form-item>
      </el-form>
    </div>
    <el-tabs v-model="activeName" type="card" @tab-click="tabChange">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="销售中" name="GoodsSale"></el-tab-pane>
      <el-tab-pane label="已售罄" name="SoldOut"></el-tab-pane>
      <el-tab-pane label="仓库中" name="InWarehouse"></el-tab-pane>
    </el-tabs>
    <vxe-table
      ref="goodsTable"
      show-overflow
      border="inner"
      :data="goods_data"
      :expand-config="{
        accordion: true,
        lazy: true,
        loadMethod: showSpec,
      }"
      :tooltip-config="{ contentMethod: showTooltipMethod, enterable: true }"
      @checkbox-all="selectionChange"
      @checkbox-change="selectionChange"
    >
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column
        field="code"
        width="140"
        title="编码"
      ></vxe-table-column>
      <vxe-table-column field="materialName" title="商品" min-width="300">
        <template #default="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">
              {{ scope.row.title }}
            </div>
          </div>
        </template>
      </vxe-table-column>
      <vxe-table-column
        v-if="classifyFlag"
        field="categoryName"
        title="商品分类"
        min-width="120"
      >
        <template #default="scope">
          {{ scope.row.categoryName || "未设置" }}
          <el-button
            v-if="$accessCheck($Access.BaseDataListUpdateCategory)"
            type="text"
            icon="el-icon-edit"
            @click="openSet('转移分类', scope.row)"
          ></el-button>
        </template>
      </vxe-table-column>
      <vxe-table-column
        v-if="specificationFlag"
        type="expand"
        title="规格"
        width="140"
      >
        <template #default="scope">
          <div class="sku-btn" @click="toggleRowExpansion(scope.rowIndex)">
            {{ scope.row.specTotal }}种规格
          </div>
        </template>
        <template #content="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>
                    {{ $_common.formatNub(item.inventory) }}；
                    <span class="label">销量:</span>
                    {{ $_common.formatNub(item.salesNum) }}
                  </p>
                  <p>
                    <span class="label">起订量:</span>
                    {{ $_common.formatNub(item.setNum) }}；
                    <span class="label">市场价:</span>
                    {{ $_common.formattedNumber(item.marketPrice) }}
                  </p>
                  <p>
                    <span class="label">阶梯价:</span>
                    {{ item.enabledLadder === 1 ? "是" : "否" }}；
                    <span v-if="!item.enabledLadder">
                      <span class="label">销售价:</span>
                      {{ $_common.formattedNumber(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">
                        {{ $_common.formattedNumber(price.price) }}
                      </span>
                      ;
                    </span>
                  </p>
                </div>
              </div>
            </li>
          </ul>
        </template>
      </vxe-table-column>
      <vxe-table-column
        v-if="unitFlag"
        field="unitNameMaster"
        title="基本单位"
        min-width="100"
      ></vxe-table-column>
      <vxe-table-column field="sort" title="排序" min-width="130">
        <template #default="{ row, $rowIndex }">
          <div v-if="row.sort_flag">
            <el-input-number
              v-model="member_sort"
              style="width: calc(100% - 30px)"
              :controls="false"
              size="mini"
              @keyup.enter.native="setSort($rowIndex)"
            ></el-input-number>
            <div class="virtualSalesNum-btn" @click="setSort($rowIndex)">
              <i class="el-icon-check"></i>
            </div>
          </div>

          <div v-else @click="showSort($rowIndex)">
            {{ row.sort }}
            <el-button type="text" icon="el-icon-edit"></el-button>
          </div>
        </template>
      </vxe-table-column>
      <vxe-table-column
        v-if="inventoryFlag"
        field="masterInventory"
        title="总库存"
        min-width="100"
      >
        <template #default="scope">
          <span
            :class="
              Number(scope.row.inventorTotal) <= 0
                ? 'danger-status'
                : 'success-status'
            "
            class=""
          >
            {{ $_common.formatNub(scope.row.inventorTotal) }}
          </span>
        </template>
      </vxe-table-column>
      <vxe-table-column
        v-if="false"
        field="virtualSalesNum"
        title="虚拟销量"
        min-width="100"
      >
        <template #default="scope">
          <div v-if="scope.row.sale_false_visible">
            <el-input-number
              v-model="virtual_sales_num"
              style="width: calc(100% - 28px)"
              :controls="false"
              size="mini"
              @keyup.enter.native="setSalesNum(scope.$index)"
              @blur="setSalesNum(scope.$index, -1)"
            ></el-input-number>
            <div class="virtualSalesNum-btn" @click="setSalesNum(scope.$index)">
              <i class="el-icon-check"></i>
            </div>
          </div>

          <div v-else @click="showSetSaleNum(scope.$index)">
            {{ scope.row.virtualSalesNum }}
            <el-button
              v-if="$accessCheck($Access.PublishGoodssetSalesNum)"
              type="text"
              icon="el-icon-edit"
            ></el-button>
          </div>
        </template>
      </vxe-table-column>
      <vxe-table-column
        v-if="trueFlag"
        field="salesNum"
        title="真实销量"
        min-width="100"
      >
        <template #default="scope">
          {{ $_common.formatNub(scope.row.salesNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column
        v-if="stateFlag"
        field="enableStatus"
        title="销售状态"
        width="100"
      >
        <template #default="scope">
          <el-switch
            v-if="$accessCheck($Access.PublishGoodsUpdateEnableStatus)"
            v-model="scope.row.enableStatus"
            class="switchStyle"
            active-color="#36B365"
            :active-value="5"
            :inactive-value="4"
            active-text="上架"
            inactive-text="下架"
            @change="changeGoodsStatus($event, scope.row)"
          ></el-switch>
          <div v-else>
            <span v-if="scope.row.enableStatus === 5" class="success-status">
              上架
            </span>
            <span v-else class="info-status">下架</span>
          </div>
        </template>
      </vxe-table-column>
      <vxe-table-column
        v-if="shopFlag"
        field="shopName"
        title="销售店铺"
        min-width="200"
      ></vxe-table-column>
      <vxe-table-column
        v-if="timeFlag"
        field="createTime"
        title="创建时间"
        width="150"
      >
        <template #default="scope">
          {{ $_common.formatDate(scope.row.createTime) }}
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right" width="160">
        <!--        <template slot="header" #default="scope">-->
        <!--          &lt;!&ndash;          <span v-if="false">{{ scope.$index }}</span>&ndash;&gt;-->
        <!--          <span class="operation">操作</span>-->
        <!--          <el-popover popper-class="custom-table-checkbox" trigger="click">-->
        <!--            <el-checkbox-group v-model="checkList">-->
        <!--              <el-checkbox-->
        <!--                v-for="(item, index) in columns"-->
        <!--                :key="index"-->
        <!--                :label="item.label"-->
        <!--                @change="change"-->
        <!--              ></el-checkbox>-->
        <!--            </el-checkbox-group>-->
        <!--            <el-button-->
        <!--              slot="reference"-->
        <!--              icon="el-icon-setting"-->
        <!--              type="text"-->
        <!--            ></el-button>-->
        <!--          </el-popover>-->
        <!--        </template>-->
        <template #default="scope">
          <div style="height: 34px; line-height: 34px">
            <el-button
              v-if="
                ($accessCheck($Access.PublishGoodsEditGoods) &&
                  $accessCheck($Access.PublishGoodsGetGoodsInfo) &&
                  $route.name === 'PublishGoods') ||
                ($accessCheck($Access.PublishGoodsEditQuickGoods) &&
                  $accessCheck($Access.PublishGoodsGetQuickGoodsInfo) &&
                  $route.name === 'PublishGoods')
              "
              type="text"
              @click="openPriceModel(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="
                $accessCheck($Access.PublishGoodsDelGoods) &&
                $route.name === 'PublishGoods'
              "
              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>
          </div>
        </template>
      </vxe-table-column>
    </vxe-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">
          <vxe-checkbox
            v-model="checkedAll"
            :indeterminate="isIndeterminate"
            @change="checkAllChange"
          ></vxe-checkbox>
        </span>
        <el-dropdown
          v-if="
            $accessCheck($Access.PublishGoodsUpdateEnableStatus) &&
            ['PublishGoods', 'InWarehouse'].includes($route.name)
          "
        >
          <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>
        <el-dropdown
          v-if="
            $accessCheck($Access.PublishGoodssetSalesNumBatch) ||
            $accessCheck($Access.PublishGoodsbatchGoodsExpress)
          "
        >
          <el-button size="mini">
            批量设置
            <i class="el-icon-caret-top"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-if="$accessCheck($Access.PublishGoodssetSalesNumBatch)"
            >
              <div class="dropdown-div" @click="openSet('虚拟销量')">
                设置虚拟销量
              </div>
            </el-dropdown-item>
            <el-dropdown-item
              v-if="$accessCheck($Access.PublishGoodsbatchGoodsExpress)"
            >
              <div class="dropdown-div" @click="openSet('物流设置')">
                批量设置物流
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown
          v-if="
            $accessCheck($Access.BaseDataListUpdateCategory) ||
            $accessCheck($Access.BaseDataListSetBrand)
          "
        >
          <el-button size="mini">
            批量转移
            <i class="el-icon-caret-top"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <div
                v-if="$accessCheck($Access.BaseDataListUpdateCategory)"
                class="dropdown-div"
                @click="openSet('转移分类')"
              >
                转移分类
              </div>
            </el-dropdown-item>
            <el-dropdown-item>
              <div
                v-if="$accessCheck($Access.BaseDataListSetBrand)"
                class="dropdown-div"
                @click="openSet('设置品牌')"
              >
                转移品牌
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown
          v-if="
            $accessCheck($Access.PublishGoodsUpdateEnableStatus) &&
            ['PublishGoods', 'InWarehouse'].includes($route.name)
          "
        >
          <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="batchSetDistribution(5)">
                批量启用
              </div>
            </el-dropdown-item>
            <el-dropdown-item>
              <div class="dropdown-div" @click="batchSetDistribution(4)">
                批量禁用
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown
          v-if="
            $accessCheck($Access.PublishGoodsUpdateEnableStatus) &&
            ['PublishGoods', 'InWarehouse'].includes($route.name)
          "
        >
          <el-button size="mini" @click="deleteBatchUnloading(4)">
            批量删除
          </el-button>
        </el-dropdown>
      </div>
    </FooterPage>
    <BrandSelModel
      v-if="sel_brand"
      :is-check="false"
      :dialog-visible="sel_brand"
      @close="sel_brand = false"
      @confirm="brandConfirm"
    />
    <BrandSelModel
      v-if="transferShow"
      :is-check="false"
      :dialog-visible="transferShow"
      @close="transferShow = false"
      @confirm="transferBrandConfirm"
    />
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :title="set_tit"
      :visible.sync="is_set"
      width="30%"
    >
      <el-form ref="set_form" :model="set_form" label-width="100px">
        <el-form-item v-if="set_tit === '虚拟销量'" label="销量区间：">
          <el-input-number
            v-model="sale_num_form.minVal"
            :controls="false"
          ></el-input-number>
          -
          <el-input-number
            v-model="sale_num_form.maxVal"
            :controls="false"
          ></el-input-number>
          <p class="form-tip">虚拟总销量等于销量区间内产生的随机数</p>
        </el-form-item>
        <el-form-item v-if="set_tit === '转移分类'" label="转移分类：">
          <GoodsCategory v-model="set_form.category" check-strictly />
        </el-form-item>
        <el-form-item v-if="set_tit === '设置品牌'" label="设置品牌：">
          <el-input
            v-model="set_form.brandName"
            readonly
            style="width: 240px"
            placeholder="请选择品牌"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="transferShow = true"
            ></i>
          </el-input>
        </el-form-item>
        <div v-if="set_tit === '物流设置'">
          <el-form-item v-if="false" label="物流支持：" prop="deliverySupIds">
            <el-checkbox-group v-model="set_form.deliverySupIds">
              <el-checkbox label="1">快递</el-checkbox>
              <el-checkbox label="2">自提</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <br />
          <el-form-item label="快递运费：">
            <el-radio-group v-model="set_form.expressType">
              <el-radio :label="1">包邮</el-radio>
              <el-radio :label="2">运费模版</el-radio>
              <el-radio :label="3">统一运费</el-radio>
            </el-radio-group>
          </el-form-item>
          <br />
          <div v-if="set_form.expressType === 2">
            <el-form-item label="运费模板：" prop="ruleId">
              <el-select v-model="set_form.ruleId" placeholder="请选择">
                <el-option
                  v-for="(item, index) in express_list"
                  :key="index"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div v-if="set_form.expressType === 3">
            <el-form-item label="统一运费：" prop="expressFee">
              <el-input-number
                v-model="set_form.expressFee"
                :controls="false"
              ></el-input-number>
              <span>元</span>
            </el-form-item>
          </div>
          <el-form-item v-if="false" label="是否展示快递：">
            <el-radio-group v-model="set_form.showExpress">
              <el-radio :label="4">不展示</el-radio>
              <el-radio :label="5">展示</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="is_set = false">取 消</el-button>
        <el-button :loading="more_sub_btn" type="primary" @click="moreSubData">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </ContainerQuery>
</template>

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

  import {
    setSalesNum,
    getGoodsInfo,
    BatchUnloading,
    getAllGoods,
    exportGetAllGoods,
    exportGetAllGoodsList,
    searchGood,
    exportSearchGood,
    delGoods,
    setTop,
    GoodsUpdateEnableStatus,
    batchGoodsExpress,
    setSalesNumBatch,
    setBrand,
    updateCategory,
    batchSetDistribution,
    setSort,
    getAllGoodsList,
  } from "@/api/goods";
  import { getAllExpressRule } from "@/api/System";
  import { mapGetters } from "vuex";
  export default {
    name: "PublishGoods",
    components: {
      GoodsCategory,
      // EditGoods,
      BrandSelModel,
      SelectShop,
    },
    data() {
      return {
        virtual_sales_num: 0,
        set_goods_id: 0,
        sale_num_form: {
          ids: [],
          minVal: "",
          maxVal: "",
        },
        activeName: "all",
        goods_sku_list: [],
        checkedAll: false,
        isIndeterminate: false,
        is_price: false,
        sku_visible: false,
        sku_goods_name: "",
        goods_name: "",
        keyword: "",
        brandId: "",
        categoryId: "",
        enableStatus: "",
        shopId: "",
        sel_brand: false,
        transferShow: 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,
        set_form: {
          masterUnitId: "",
          shopName: "",
          brandName: "",
          brandId: "",
          category: [],
          branchUnit: [],
          deliverySupIds: ["1", "2"], // 物流支持 固定值 1 快递 2 自提 传参格式：1,2
          expressType: 1, // 快递运费 1 包邮 2 运费模版 3 固定费用
          expressFee: "", // 固定费用
          showExpress: 5, // 是否展示快递 5展示 4不展示
          ruleId: "", // 运费模版id
        },
        express_list: [],
        assistForm: {},
        more_sub_btn: false,
        unit_show: false,
        is_set: false,
        set_tit: "",
        checkList: [
          "商品分类",
          "规格",
          "基本单位",
          "总库存",
          // "虚拟销量",
          "真实销量",
          "当前状态",
          "销售店铺",
          "创建时间",
        ],
        columns: [
          {
            label: "商品分类",
          },
          {
            label: "规格",
          },
          {
            label: "基本单位",
          },
          {
            label: "总库存",
          },
          // {
          //   label: "虚拟销量",
          // },
          {
            label: "真实销量",
          },
          {
            label: "当前状态",
          },
          {
            label: "销售店铺",
          },
          {
            label: "创建时间",
          },
        ],
        classifyFlag: true,
        specificationFlag: true,
        unitFlag: true,
        inventoryFlag: true,
        virtualFlag: true,
        trueFlag: true,
        stateFlag: true,
        shopFlag: true,
        timeFlag: true,
        member_sort: 0, //排序
      };
    },
    computed: {
      ...mapGetters({
        enterpriseScope: "MUser/enterpriseScope",
      }),
    },
    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;
      }
      this.getAllGoodsList();
      this.getAllExpressRule();
    },
    activated() {
      if (this.$_isInit()) return;
      this.getData();
    },
    methods: {
      showTooltipMethod({ type, column, row, items, _columnIndex }) {
        if (column.property === "shopName") {
          if (type === "body") {
            return column.shopName;
          }
        }
      },
      // 获取运费模版
      async getAllExpressRule() {
        const { data } = await getAllExpressRule();
        this.express_list = data;
      },
      async setSalesNum(index, tag) {
        if (tag === -1) {
          this.goods_data[index].sale_false_visible = false;
          return;
        }
        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");
        }
      },
      tabChange() {
        switch (this.activeName) {
          case "all":
            this.inSales = 1;
            this.inStock = 0;
            break;
          case "GoodsSale":
            this.inSales = 2;
            this.inStock = 0;
            break;
          case "SoldOut":
            this.inSales = 3;
            this.inStock = 4;
            break;
          case "InWarehouse":
            this.inSales = 4;
            this.inStock = 5;
            break;
        }
        this.pageChange(1);
      },
      // 用于可展开表格与树形表格，切换某一行的展开状态，如果使用了第二个参数，则是设置这一行展开与否（expanded 为 true 则展开）
      async showSpec({ row }) {
        return new Promise(async (resolve) => {
          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: "",
                    };
                  }
                );
              });
            }
          }
          resolve();
        });
        // this.goods_data = target
      },
      toggleRowExpansion(index) {
        this.$refs.goodsTable.toggleRowExpand(this.goods_data[index]);
      },
      delBrand() {
        this.form.brand = "";
        this.brandId = "";
        this.pageChange(1);
      },
      delShop() {
        this.form.shop = "";
        this.shopId = "";
        this.pageChange(1);
      },
      // 批量选择
      selectionChange({ records }) {
        this.checkedAll = this.$refs.goodsTable.isAllCheckboxChecked();
        this.isIndeterminate = this.$refs.goodsTable.isAllCheckboxChecked();
        this.choose_data = records;
      },
      // 编辑完成回调
      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;
          this.$router.push(`/goods/sale/EditGoods/${row.id}`);
        } else {
          this.$router.push(`/goods/sale/EditGoodsOneStore/${row.id}`);
        }
      },

      //  批量上下架
      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();
        });
      },
      // 批量删除
      async deleteBatchUnloading(deleteStatus) {
        if (!this.choose_data.length) {
          this.$message.warning("请选择要操作的商品");
          return;
        }
        this.$confirm("确定要批量删除这些商品吗", "提示", {
          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,
            deleteStatus: deleteStatus,
          });
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.getData();
        });
      },
      // 获取列表
      async getAllGoods(exports) {
        let params = {
          page: this.page,
          pageSize: this.pageSize,
          ifMerchant: this.ifMerchant,
          merchantId: this.merchantId,
        };
        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: [],
              address: item.shopName,
              sort_flag: false,
            };
          });
          this.total = data.pageTotal;
        }
      },
      async getAllGoodsList(exports) {
        let params = {
          page: this.page,
          pageSize: this.pageSize,
          keywordType: this.inSales,
          keyword: this.keyword,
          categoryPath: this.form.categoryPath.join(","),
          brandId: this.brandId,
          enableStatus: this.enableStatus,
          shopId: this.shopId,
        };
        if (exports) {
          const data = await exportGetAllGoodsList({
            ...params,
            export: 1,
          });
        } else {
          const data = await getAllGoodsList(params);
          this.goods_data = data.data.map((item) => {
            return {
              ...item,
              sale_false_visible: false,
              goods_sku_list: [],
              address: item.shopName,
              sort_flag: false,
            };
          });
          this.total = data.pageTotal;
        }
      },
      //  搜索商品 searchGood
      // async searchGood(exports) {
      //   if (this.activeName !== "all") {
      //     this.enableStatus = "";
      //   }
      //   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,
      //         goods_sku_list: [],
      //       };
      //     });
      //     this.total = data.pageTotal;
      //   }
      // },
      // 判断当前使用方法为列表接口还是搜索引擎接口 获取列表数据
      getData(exports) {
        if (this.activeName !== "all") {
          this.enableStatus = "";
        }
        // 搜索参数规整
        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);
      },
      //转移品牌
      transferBrandConfirm(row) {
        this.set_form.brandName = row[0].title;
        this.set_form.brandId = row[0].id;
      },
      // 商铺搜索
      shopConfirm(val, row) {
        this.shopId = row[0].id;
        this.form.shop = row[0].name;
        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();
        });
      },
      // 商品上下架
      async changeGoodsStatus(val, row) {
        try {
          const data = await GoodsUpdateEnableStatus({
            id: row.id,
            enableStatus: val,
          });
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        } catch (e) {
          this.getData();
        }
      },
      // 切页
      pageChange(val) {
        this.page = val;
        this.getAllGoodsList();
      },
      // 每页数据大小改变
      sizeChange(val) {
        this.pageSize = val;
        this.pageChange(1);
      },
      checkAllChange() {
        this.$refs.goodsTable.setAllCheckboxRow(this.checkedAll);
        this.isIndeterminate = this.$refs.goodsTable.isAllCheckboxChecked();
        this.choose_data = this.$refs.goodsTable.getCheckboxRecords();
      },
      // 打开批量设置弹窗
      openSet(tit, row) {
        this.is_set = true;
        this.set_tit = tit;
        if (row) {
          this.choose_data = [row];
        }
      },
      // 批量提交
      moreSubData() {
        this.checkedAll = false;
        this.isIndeterminate = false;
        if (this.set_tit === "转移分类") {
          this.updateCategory();
        }
        if (this.set_tit === "设置品牌") {
          this.setBrand();
        }
        if (this.set_tit === "虚拟销量") {
          this.setSalesNumBatch();
        }
        if (this.set_tit === "物流设置") {
          this.batchGoodsExpress();
        }
      },
      // 批量设置运费
      async batchGoodsExpress() {
        if (!this.choose_data.length) {
          this.$message.warning("请选择要操作的商品");
          return;
        }
        const idData = this.choose_data.map((item) => {
          return item.id;
        });
        this.more_sub_btn = true;
        try {
          const data = await batchGoodsExpress({
            expressType: this.set_form.expressType,
            ruleId: this.set_form.ruleId,
            expressFee: this.set_form.expressFee,
            ids: idData,
          });
          this.more_sub_btn = false;

          this.is_set = false;
          this.$message.success("操作成功");
          this.getData();
        } catch {
          this.more_sub_btn = false;
        }
      },
      // 设置虚拟销量
      async setSalesNumBatch() {
        if (!this.choose_data.length) {
          this.$message.warning("请选择要操作的商品");
          return;
        }
        if (!this.sale_num_form.minVal) {
          this.$message.warning("虚拟销量区间最小值不能为0");
          return;
        }
        if (!this.sale_num_form.maxVal) {
          this.$message.warning("虚拟销量区间最大值不能为0");
          return;
        }
        if (this.sale_num_form.maxVal <= this.sale_num_form.minVal) {
          this.$message.warning("虚拟销量区间最大值必须大于最小值");
          return;
        }
        this.more_sub_btn = true;
        try {
          const idData = this.choose_data.map((item) => {
            return item.id;
          });
          const data = await setSalesNumBatch({
            ...this.sale_num_form,
            ids: idData,
          });
          this.more_sub_btn = false;

          this.is_set = false;
          this.$message.success("操作成功");
          this.getData();
        } catch {
          this.more_sub_btn = false;
        }
      },
      //  设置品牌
      async setBrand() {
        if (!this.choose_data.length) {
          this.$message.warning("请选择要操作的商品");
          return;
        }
        if (!this.set_form.brandId) {
          this.$message.warning("请选择要操作的品牌");
          return;
        }
        const idData = this.choose_data.map((item) => {
          return item.basicGoodsId;
        });
        this.more_sub_btn = true;
        try {
          const data = await setBrand({
            id: idData,
            brandId: this.set_form.brandId,
          });
          this.more_sub_btn = false;

          this.is_set = false;
          this.$message.success("操作成功");
          this.getData();
        } catch {
          this.more_sub_btn = false;
        }
      },

      // 转移分类
      async updateCategory() {
        if (!this.choose_data.length) {
          this.$message.warning("请选择要操作的商品");
          return;
        }
        if (!this.set_form.category) {
          this.$message.warning("请选择要转移的分类");
          return;
        }
        this.more_sub_btn = true;
        try {
          const idData = this.choose_data.map((item) => {
            return item.basicGoodsId;
          });
          const data = await updateCategory({
            id: idData, // 要移动的基础商品id
            categoryId: this.set_form.category[
              this.set_form.category.length - 1
            ], // 移动至商品分类id
            categoryPath: this.set_form.category.join(","), // 新的商品分类路径
          });
          this.more_sub_btn = false;
          this.is_set = false;
          this.$message.success("操作成功");
          this.set_form.category = [];
          this.getData();
        } catch {
          this.more_sub_btn = false;
        }
      },
      change() {
        this.classifyFlag = this.checkList.some((item) => item === "商品分类");
        this.specificationFlag = this.checkList.some((item) => item === "规格");
        this.unitFlag = this.checkList.some((item) => item === "基本单位");
        this.inventoryFlag = this.checkList.some((item) => item === "总库存");
        this.virtualFlag = this.checkList.some((item) => item === "虚拟销量");
        this.trueFlag = this.checkList.some((item) => item === "真实销量");
        this.stateFlag = this.checkList.some((item) => item === "当前状态");
        this.shopFlag = this.checkList.some((item) => item === "销售店铺");
        this.timeFlag = this.checkList.some((item) => item === "创建时间");
      },
      batchSetDistribution(enableStatus) {
        let title =
          enableStatus === 4
            ? "确定要批量禁用库存销售？"
            : "确定要批量启用这些商品为负库存销售吗？";
        if (!this.choose_data.length) {
          this.$message.warning("请选择要操作的商品");
          return;
        }
        this.$confirm(title, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          this.checkedAll = false;
          this.isIndeterminate = false;
          if (!this.choose_data.length) {
            this.$message.warning("请选择要操作的商品");
            return;
          }
          const idData = this.choose_data.map((item) => {
            return item.id;
          });
          const data = await batchSetDistribution({
            ids: idData,
            isDistribution: enableStatus,
          });
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.getData();
        });
      },
      showSort(index) {
        this.goods_data.forEach((item) => (item.sort_flag = false));
        this.member_sort = this.goods_data[index].sort;
        this.goods_data[index].sort_flag = true;
      },
      async setSort(index) {
        const { data } = await setSort({
          id: this.goods_data[index].id,
          sort: this.member_sort,
        });
        this.$message.success("修改成功");
        this.goods_data[index].sort_flag = false;
        await this.getAllGoodsList();
      },
    },
  };
</script>
<style scoped lang="scss">
  .sku-btn {
    width: 71px;
    height: 22px;
    line-height: 22px;
    background: #f5f5f5;
    border-radius: 4px;
    border: 1px solid #cad0d7;
    text-align: center;
    font-size: 12px;
    cursor: pointer;
    display: inline-block;
  }
  .goods-name-view {
    width: calc(100% - 76px);
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    margin-left: 10px;
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .custom-table-checkbox {
    .el-checkbox {
      display: block !important;
      margin: 0 0 $base-padding/4 0;
    }
  }
  .virtualSalesNum-btn {
    width: 26px;
    text-align: center;
    line-height: 28px;
    height: 28px;
    vertical-align: middle;
    font-size: 12px;
    background: #f5f5f5;
    border: 1px solid #cad0d7;
    display: inline-block;
    cursor: pointer;
    border-left: 0;
  }
  .sku-ul {
    display: flex;
    flex-wrap: wrap;
    .sku-li {
      display: inline-block;
      margin-right: 10px;
      margin-bottom: 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>
