<template>
  <div class="mall-section-container">
    <div class="mall-content-section">
      <div class="mall-content-title">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '' }">
            <a href="/report/#/memberSummary">首页</a>
          </el-breadcrumb-item>
          <el-breadcrumb-item>积分商城</el-breadcrumb-item>
          <el-breadcrumb-item>商品</el-breadcrumb-item>
          <el-breadcrumb-item>礼品</el-breadcrumb-item>
        </el-breadcrumb>
        <h3>
          <span>礼品</span>
        </h3>
      </div>
      <div class="section">
        <!-- <div class="page-info">
          <h3><i class="el-icon-info"></i>优惠券已支持主图和图文详情，如需再发布以“微信兑换券”来配送的礼品，请直接前往优惠券中设置</h3>
        </div>-->
        <div class="search-wrap" style="display: flex;justify-content: space-between;margin-bottom: 20px;">
          <div class="left" style="display: flex;gap:10px;flex-wrap: wrap;">
            <div class="search-content-item" style="height:32px;">
              <el-input
                v-model="searchValue"
                placeholder="请输入礼品名称/编码/创建人进行搜索"
                prefix-icon="el-icon-search"
                clearable
                class="w-300"
                @keyup.enter.native="getSearchList"
                @clear="getSearchList"
              />
            </div>
            <div class="search-content-item" style="height:32px;">
              <el-select
                v-model="shelf"
                placeholder="上下架状态"
                clearable
                class="w-140"
                @change="getListCurr"
              >
                <el-option label="已上架" :value="2" />
                <el-option label="已下架" :value="1" />
                <el-option label="待上架" :value="3" />
              </el-select>
            </div>
            <div class="search-content-item" style="height:32px;">
              <el-select
                v-model="stockStatus"
                placeholder="库存状态"
                clearable
                class="w-140"
                @change="getListCurr"
              >
                <el-option label="有库存" :value="1" />
                <el-option label="无库存" :value="2" />
              </el-select>
            </div>
            <div class="search-content-item" style="height:32px;">
              <el-select
                v-model="giftType"
                placeholder="礼品类型"
                clearable
                class="w-140"
                @change="getListCurr"
              >
                <el-option label="实物礼品" :value="1" />
                <el-option label="虚拟礼品" :value="2" />
              </el-select>
            </div>
            <div class="search-content-item" style="height:32px;">
              <el-select
                v-model="ruleRelationFlag"
                placeholder="上架规则"
                clearable
                class="w-140"
                @change="getListCurr"
              >
                <el-option label="已关联上架规则" :value="1" />
                <el-option label="未关联上架规则" :value="0" />
              </el-select>
            </div>
            <div class="search-content-item" style="height:32px;">
              <el-select
                v-model="category"
                placeholder="礼品分类"
                class="w-140"
                clearable
                @change="getListCurr"
              >
                <el-option
                  v-for="(v, i) in categoryOptions"
                  :key="i"
                  :label="v.categoryName"
                  :value="v.integralMallCategoryId"
                >
                  <span class="fl">{{ v.categoryName }}</span>
                </el-option>
              </el-select><el-checkbox
                style="margin-left:10px;"
                v-model="showSelfStatus"
                label="仅看本人"
                border
                @change="getListCurr"
                v-if="showFlag"
              />
            </div>
            <div class="search-content-item" style="height:32px;" />
          </div>
          <div class="right" style="display: flex;justify-content: space-between;width:322px;padding-left:10px;box-sizing: border-box;">
            <div class="search-content-item" style="width:214px;">
              <el-select
                v-model="goodsType"
                placeholder="请选择批量操作"
                clearable
                @change="handleData"
                style="width:214px;"
              >
                <el-option
                  label="批量上架"
                  :value="0"
                  v-if="$getButtonLimit($buttonCode.giftNew)"
                  :limit-code="$buttonCode.giftNew"
                />
                <el-option
                  label="批量下架"
                  :value="1"
                  v-if="$getButtonLimit($buttonCode.giftRemove)"
                  :limit-code="$buttonCode.giftRemove"
                />
                <el-option
                  label="批量删除"
                  :value="2"
                  v-if="$getButtonLimit($buttonCode.giftDelete)"
                  :limit-code="$buttonCode.giftDelete"
                />
              </el-select>
            </div>
            <el-button
              type="primary"
              @click="addGift"
              v-if="$getButtonLimit($buttonCode.giftAdd)"
              :limit-code="$buttonCode.giftAdd"
              style="height:32px;margin-left:10px;"
            >
              新增礼品
            </el-button>
          </div>
        </div>
        <div v-loading="loading">
          <el-table
            ref="multipleTable"
            :data="tableDate"
            style="width: 100%"
            @sort-change="sortChange"
            @selection-change="handleSelectAll"
          >
            <el-table-column
              fixed
              type="selection"
              width="50"
              :selectable="selectInit"
            />
            <el-table-column fixed label="礼品信息" min-width="300px">
              <template slot-scope="scope">
                <div class="gift-info">
                  <img :src="scope.row.mainImageUrl" alt>
                  <div class="info-name">
                    <!-- integralMallProId -->
                    <el-tooltip :content="'礼品id：' + scope.row.integralMallProId" effect="dark" placement="top-start">
                      <p class="intergral-edit" :class="[scope.row.hasActivity ? 'pro-ellipsis2' : 'pro-ellipsis']">
                        {{ scope.row.proName }}
                        <i
                          class="el-icon-edit"
                          @click="editProName(scope.row)"
                          v-if="$getButtonLimit($buttonCode.giftRename)"
                          :limit-code="$buttonCode.giftRename"
                        />
                      </p>
                    </el-tooltip>
                    <p class="category-ellipsis">
                      编码：{{ scope.row.proCode }}
                    </p>
                    <div v-if="scope.row.hasActivity" style="font-size:12px;background-color:#f56c6c;color:#fff;line-height:16px;width:32px;text-align:center">
                      秒杀
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="giftCategoryName" label="礼品分类" min-width="110px">
              <template slot-scope="scope">
                {{ scope.row.giftCategoryName ? scope.row.giftCategoryName : '--' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="integralCost"
              label="积分费用"
              sortable="custom"
              min-width="110px"
            >
              <template slot-scope="scope">
                <p class="intergral-edit">
                  {{ scope.row.integralCost }}积分
                  <i
                    class="el-icon-edit"
                    @click="handleTable(scope.row, 'cash')"
                    v-if="scope.row.canEdit && $getButtonLimit($buttonCode.giftEditPointsAndCush)"
                    :limit-code="$buttonCode.giftEditPointsAndCush"
                  />
                </p>
              </template>
            </el-table-column>
            <el-table-column
              prop="cashCost"
              label="现金费用"
              sortable="custom"
              min-width="110px"
            >
              <template slot-scope="scope">
                <p class="intergral-edit">
                  {{ scope.row.cashCost }}元
                  <i
                    class="el-icon-edit"
                    v-if="scope.row.canEdit && $getButtonLimit($buttonCode.giftEditPointsAndCush)"
                    @click="handleTable(scope.row, 'cash')"
                    :limit-code="$buttonCode.giftEditPointsAndCush"
                  />
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="sortCost" label="库存" sortable="custom">
              <template #header>
                库存
                <el-popover
                  trigger="hover"
                  width="250"
                  placement="top"
                  content="该礼品在积分商城所有的库存，包括活动库存，库存分布请点击数字查看"
                >
                  <i
                    class="iconfont icon-xinxixianshi"
                    v-show="specialOrder"
                    style="margin-left:-2px"
                    slot="reference"
                  />
                </el-popover>
              </template>
              <template slot-scope="scope">
                <p class="intergral-edit">
                  <el-button v-if="specialOrder" type="text" @click="checkStockDistribute(scope.row)">
                    {{ scope.row.virtualStock }}
                  </el-button>
                  <span v-else>{{ scope.row.virtualStock }}</span>
                  <i
                    class="el-icon-edit"
                    v-if="scope.row.giftType === 1 && scope.row.canEdit && $getButtonLimit($buttonCode.giftEditStock)"
                    @click="handleTable(scope.row, 'stock')"
                    :limit-code="$buttonCode.giftEditStock"
                  />
                </p>
              </template>
            </el-table-column>
            <el-table-column
              prop="sortTimes"
              label="兑换次数"
              sortable="custom"
              min-width="110px"
            >
              <template slot-scope="scope">
                <p>{{ scope.row.allExchangeNumber }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" min-width="110px">
              <template slot-scope="scope">
                <p>{{ getTime(scope.row.createTime) }}</p>
                <p>{{ getSeconds(scope.row.createTime) }}</p>
              </template>
            </el-table-column>
            <el-table-column
              prop="creatorName"
              label="创建人"
              min-width="110px"
              v-if="openFlag"
            >
              <template slot-scope="scope">
                {{ scope.row.creatorName ? scope.row.creatorName : '--' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="sort"
              label="序号"
              sortable="custom"
              min-width="140px"
              :render-header="renderHeader"
            >
              <template slot-scope="scope">
                <p v-if="!scope.row.editStatus" class="edit-number intergral-edit">
                  {{ scope.row.sort }}
                  <i
                    class="el-icon-edit"
                    v-if="scope.row.canEdit && $getButtonLimit($buttonCode.giftNumber)"
                    :limit-code="$buttonCode.giftNumber"
                    @click="editNumber(scope.row)"
                  />
                </p>
                <div v-if="scope.row.editStatus">
                  <el-input
                    v-if="scope.row.editStatus"
                    v-model="scope.row.sort"
                    placeholder
                    size="mini"
                    class="w-180"
                    @blur="value => limitSort(value, scope.row)"
                    style="width:60px"
                  />
                  <span class="operate-span" @click="editNumSubmit(scope.row)">确定</span>
                  <span class="operate-span" @click="editNumCancel(scope.row)">取消</span>
                </div>
                <span style="display:none">{{ refash }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="shelf"
              label="状态"
              min-width="110px"
            >
              <template slot-scope="scope">
                {{ scope.row.shelf ? (scope.row.shelf == 1 ? '已下架' : scope.row.shelf == 2 ? '已上架' : '待上架') : '--' }}
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="上架规则"
              min-width="110px"
            >
              <template slot-scope="{row}">
                <p v-if="row.ruleTitle&&row.ruleTitle.length<=5">
                  {{ row.ruleTitle }}
                </p>
                <el-tooltip
                  v-if=" row.ruleTitle&& row.ruleTitle.length>5"
                  :content="row.ruleTitle"
                  effect="dark"
                  placement="top-start"
                >
                  <p>{{ row.ruleTitle.slice(0,5)+'...' }}</p>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="220px">
              <template slot-scope="scope">
                <div>
                  <el-button
                    type="text"
                    @click="getLink(scope.row)"
                    v-if="scope.row.canEdit && $getButtonLimit($buttonCode.giftPromote)"
                    :limit-code="$buttonCode.giftPromote"
                  >
                    推广
                  </el-button>
                  <el-button
                    type="text"
                    v-if="!scope.row.ruleTitle"
                    @click="relating(scope.row)"
                  >
                    关联
                  </el-button>
                  <el-button
                    type="text"
                    v-if="((scope.row.status === 2 && scope.row.canEdit && scope.row.releaseType === 2 && scope.row.isShelves === 1) || (scope.row.status === 1 && scope.row.canEdit)) && $getButtonLimit($buttonCode.giftNew) && scope.row.ruleTitle"
                    :limit-code="$buttonCode.giftNew"
                    @click="deleteList(scope.row, 2)"
                  >
                    上架
                  </el-button>
                  <el-button
                    type="text"
                    :limit-code="$buttonCode.giftRemove"
                    v-if="((scope.row.status === 2 && scope.row.canEdit && scope.row.releaseType === 1)||(scope.row.status === 2 && scope.row.canEdit && scope.row.releaseType === 2 && scope.row.isShelves === 0)) && $getButtonLimit($buttonCode.giftRemove)"
                    @click="deleteList(scope.row, 1)"
                  >
                    下架
                  </el-button>
                  <el-button
                    type="text"
                    @click="goAdd(scope.row)"
                    :limit-code="$buttonCode.giftEdit"
                    v-if="$getButtonLimit($buttonCode.giftEdit)"
                  >
                    编辑
                  </el-button>
                  <el-dropdown
                    v-if="((scope.row.changeType === '5' && scope.row.canEdit) || scope.row.isDifferentialPricing || scope.row.canEdit) && ($getButtonLimit($buttonCode.giftConversion) || $getButtonLimit($buttonCode.giftCouponCode) || $getButtonLimit($buttonCode.giftTieredPricing) || $getButtonLimit($buttonCode.giftDetail) || $getButtonLimit($buttonCode.giftDelete))"
                    style="margin-left:20px;"
                    @command="command => handleCommand(command, scope.row, scope.$index)"
                    placement="bottom-start"
                  >
                    <span class="el-dropdown-link" style="color:#1890ff;cursor: pointer;"> <i class="el-icon-more" /> </span>
                    <el-dropdown-menu slot="dropdown" style="width:110px;">
                      <el-dropdown-item command="0" v-if="$getButtonLimit($buttonCode.giftDetail)" :limit-code="$buttonCode.giftDetail">
                        查看详情
                      </el-dropdown-item>
                      <el-dropdown-item command="1" v-if="$getButtonLimit($buttonCode.giftConversion)" :limit-code="$buttonCode.giftConversion">
                        查看订单
                      </el-dropdown-item>
                      <el-dropdown-item command="2" v-if="scope.row.changeType === '5' && scope.row.canEdit && $getButtonLimit($buttonCode.giftCouponCode)" :limit-code="$buttonCode.giftCouponCode">
                        券码
                      </el-dropdown-item>
                      <el-dropdown-item command="3" v-if="scope.row.isDifferentialPricing && $getButtonLimit($buttonCode.giftTieredPricing)" :limit-code="$buttonCode.giftTieredPricing">
                        阶梯价
                      </el-dropdown-item>
                      <el-dropdown-item command="4" v-if="scope.row.canEdit && $getButtonLimit($buttonCode.giftDelete)" :limit-code="$buttonCode.giftDelete">
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
            <template slot="empty">
              <div class="no-data-wrap">
                <div class="no-data-icon">
                  <img src="../../../../static/img/no-data_icon.png">
                </div>
                <p>暂无数据</p>
              </div>
            </template>
          </el-table>
          <div class="pagination-conteiner" v-show="tableDate.length > 0">
            <div class="pagination">
              <dm-pagination
                v-if="total != 0"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pageSizes"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next"
                :total="total"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 修改礼品名称 -->
    <editName :editInfoModal="editInfoModal" @getList="getList" />
    <!-- 推广 -->
    <eqCode :modalData="modalData" :integralMallProId="integralMallProId" :saleType="saleType" />
    <!-- 新增礼品 -->
    <selectType :addModalData="addModalData" />
    <!-- 调整积分费用 -->
    <stockModal :intergralModal="intergralModal" @getList="getList" v-if="intergralModal.dialogVisible" />
    <!-- 卡券列表 -->
    <couponList
      :couponListModal="couponListModal"
      v-if="couponListModal.dialogVisible"
      @getChildSearch="getChildSearch"
      @getList="getList"
      @getClose="getClose"
    />
    <!-- 阶梯价 -->
    <gift-ladder-price
      :ladderPriceData="ladderPriceData"
      @closeUpdateLadder="closeUpdateLadder"
      v-if="ladderDialogVisible"
      @getList="getList"
    />
    <!-- 查看库存分布 -->
    <check-stock-distirbute
      :integralMallProId="integralMallProId"
      @closeStockDistirbute="closeStockDistirbute"
      v-if="stockDialog"
      @getList="getList"
    />
    <relate-pop ref="relatePop" :integralMallProId="integralMallProId" @finish="onPopFinish" />
  </div>
</template>

<script>
import qs from 'qs';
import request from '../../../service/request.js';
import getInputVal from '../../../utils/common.js';
import editName from '../../../components/editName';
import eqCode from '../../../components/eqCode';
import selectType from '../../../components/selectGoodsType';
import stockModal from '../../../components/getSkuList';
import giftLadderPrice from '../../../components/giftLadderPrice';
import checkStockDistirbute from '../../../components/checkStockDistirbute';
import copy from '../../../utils/clone.js';
import couponList from './couponList';
import relatePop from '@/components/relatePop';
export default {
  components: {
    editName,
    eqCode,
    selectType,
    stockModal,
    couponList,
    giftLadderPrice,
    checkStockDistirbute,
    relatePop,
  },
  data () {
    return {
      getTime: getInputVal.getTime,
      getSeconds: getInputVal.getSeconds,
      searchValue: '',
      shelf: '', // 上下架状态
      stockStatus: '', // 库存状态
      giftType: '', // 商品类型
      sortColumn: '',
      sortType: '',
      category: '', // 礼品分类
      showSelfStatus: false,
      showFlag: false,
      openFlag: false,
      tableDate: [],
      currentPage: 1,
      pageSizes: [20, 40, 60, 80],
      pageSize: 20,
      total: 0,
      loading: false,
      editInfoModal: {
        // 修改礼品名称
        proName: '',
        proNameLen: 0,
        mallProId: '',
        dialogVisible: false,
      },
      modalData: {
        // 推广数据
        show: false,
        imgUrl: '',
        loading: false,
      },
      selectArr: [], // 选中的数据
      addModalData: {
        dialogVisible: false,
      },
      refash: false,
      intergralModal: {
        dialogVisible: false,
        integralMallProId: '',
        headerList: [], // 头部数组
        tableSkuData: [],
        modalWidth: '',
        modalHeight: '',
        stdNum: 0,
        list: [],
        type: '',
      },
      list: [],
      giftListObj: {}, // 缓存数据
      couponListModal: {
        dialogVisible: false,
        integralMallProId: '',
        tableDate: [],
      },
      couponListSearch: '',
      couponCurrentPage: 1,
      couponPageSize: 20,
      integralMallProId: '',
      saleType: '',
      ladderPriceData: {
        data: [],
        id: '',
        // show: false
      },
      categoryOptions: [],
      ladderDialogVisible: false,
      stockDialog: false,
      enterpriseId: '',
      specialOrder: false,
      ruleRelationFlag: '',
    };
  },
  created () {
    if (localStorage.getItem('giftListObj')) {
      this.giftListObj = JSON.parse(localStorage.getItem('giftListObj'));
      this.currentPage = this.giftListObj.currentPage;
      this.pageSize = this.giftListObj.pageSize;
      this.total = this.giftListObj.total;
      this.shelf = this.giftListObj.shelf;
      this.stockStatus = this.giftListObj.stockStatus;
      this.searchValue = this.giftListObj.searchValue.trim();
      this.giftType = this.giftListObj.giftType;
      this.sortType = this.giftListObj.sortType;
      this.sortColumn = this.giftListObj.sortColumn;
      localStorage.removeItem('giftListObj'); // 使用完就清除缓存
    }
    this.getStatus();
    this.getList();
    this.getUserId();
    this.getCategoryOptions();
  },
  methods: {
    // 阶梯价定制，判断达摩测试环境与地素环境
    // 达摩测试 ff8080815dacd3a2015dacd3ef5c0000
    // 达摩生产 ff8080816a36326c016a53380d8b5f52
    // 地素 ff80808163218c030163429b47110635
    // 地素测试 ff8080816f12b5c0016f1d5896820147
    getUserId () {
      request.get('/api-integral-mall/can-differential-pricing').then(res => {
        if (res.data.errorCode === 0) {
          this.specialOrder = res.data.result == 1;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    relating (row) {
      this.integralMallProId = row.integralMallProId;
      this.$refs.relatePop.showPop();
    },
    onPopFinish () {
      this.getList();
    },
    renderHeader (h, { column, $index }, index) {
      return h('span', {}, [h('span', {}, '序号'), h('el-popover', { props: { placement: 'top-start', width: '200', trigger: 'hover', content: '礼品在小程序端的展示排序，序号越大，排序越靠前。' } }, [h('i', { slot: 'reference', class: 'iconfont icon-xinxixianshi' }, '')])]);
    },
    renderHeader2 (h, { column, $index }, index) {
      return h('span', {}, [h('span', {}, '库存'), h('el-popover', { props: { placement: 'top-start', width: '250', trigger: 'hover', content: '该礼品在积分商城所有的库存，包括活动库存，库存分布请点击数字查看' } }, [h('i', { slot: 'reference', class: 'iconfont icon-xinxixianshi' }, '')])]);
    },
    getStatus () {
      request.post('/api-integral-mall/is-show-self ').then(res => {
        if (res.data.errorCode === 0) {
          this.showFlag = res.data.result.showFlag;
          this.openFlag = res.data.result.openFlag;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 查看库存分布
    checkStockDistribute (item) {
      this.stockDialog = true;
      this.integralMallProId = item.integralMallProId;
    },
    closeStockDistirbute () {
      this.stockDialog = false;
    },
    handleCommand (command, item, index) {
      if (command == 0) {
        this.goAdd(item, 'detail');
      } else if (command == 1) {
        this.goRecord(item);
      } else if (command == 2) {
        this.getCouponList(item.integralMallProId);
      } else if (command == 3) {
        this.ladderList(item);
      } else if (command == 4) {
        this.$confirm('<div>确认删除该商品吗?</div>', '提示', {
          closeOnClickModal: false,
          showClose: false,
          type: 'warning',
          customClass: 'show-title',
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确认',
        })
          .then(() => {
            this.deleteList(item, 0, index);
          })
          .catch(() => {

          });
      }
    },
    // 跳转到兑换记录
    goRecord (item) {
      if (item.cardType === 2) {
        this.$router.push({ name: 'couponExchange', query: { integralMallProId: item.integralMallProId } });
      } else {
        this.$router.push({ name: 'giftExchange', query: { integralMallProId: item.integralMallProId } });
      }
    },
    getListCurr () {
      this.currentPage = 1;
      this.getList();
    },
    // 获取列表
    getList () {
      const params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        sortType: this.sortType,
        category: this.category,
        giftName: this.searchValue.trim(),
        giftType: this.giftType ? this.giftType : -1,
        sortColumn: this.sortColumn,
        shelf: this.shelf ? this.shelf : -1, // 上架状态
        stockStatus: this.stockStatus ? this.stockStatus : -1,
        goodsType: this.goodsType, // 商品类型
        showSelfFlag: this.showSelfStatus ? 1 : 0,
        ruleRelationFlag: this.ruleRelationFlag,
      };
      this.loading = true;
      request.post('/api-integral-mall/page-gift', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result.rows) {
            this.tableDate = res.data.result.rows;
            this.total = res.data.result.total;
          } else {
            this.tableDate = [];
            this.total = 0;
          }
          this.loading = false;
        } else {
          this.$message.error(res.data.message);
          this.loading = false;
        }
      }).finally(_ => {
        this.loading = false;
      });
    },
    // 分页设置每页的数量
    handleSizeChange (size) {
      this.pageSize = size;
      this.getList();
    },
    // 分页设置跳转到第几页
    handleCurrentChange (page) {
      this.currentPage = page;
      this.getList();
    },
    // 搜索
    getSearchList () {
      this.currentPage = 1;
      this.getList();
    },
    // 排序
    sortChange (value) {
      this.sortColumn = value.prop;
      if (value.order == 'ascending') {
        this.sortType = 'asc';
      } else if (value.order == 'descending') {
        this.sortType = 'desc';
      }
      this.getList();
    },
    // 编辑商品名称
    editProName (item) {
      this.editInfoModal.proName = item.proName;
      this.editInfoModal.dialogVisible = true;
      this.editInfoModal.proNameLen = getInputVal.getZhLen(this.editInfoModal.proName);
      this.editInfoModal.mallProId = item.integralMallProId;
    },
    ladderList (item) {
      // this.ladderPriceData.show = true;
      this.ladderPriceData.id = item.integralMallProId;
      this.ladderDialogVisible = true;
    },
    closeUpdateLadder () {
      console.log(111);
      this.ladderDialogVisible = false;
      this.getList();
    },
    // 商品链接
    getLink (item) {
      this.modalData.loading = true;
      this.integralMallProId = item.integralMallProId;
      this.saleType = 'gift';
      const params = {
        integralMallProId: item.integralMallProId,
        type: 'gift',
      };
      this.modalData.show = true;
      request.get('/api-integral-mall/get-qRCode', { params }).then(res => {
        if (res.data.errorCode === 0) {
          this.modalData.show = true;
          this.modalData.pageUrl = res.data.result.page;
          this.modalData.imgUrl = res.data.result.url;
          this.modalData.loading = false;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 获取卡券列表
    // showCouponListModal(item) {
    //   // console.log(item);
    //   this.getCouponList(item)
    //   this.couponListModal.dialogVisible = true;

    // },

    getChildSearch (val, id, couponCurrentPage) {
      this.couponListSearch = val;
      this.couponCurrentPage = couponCurrentPage;
      this.getCouponList(id);
    },
    getClose (val, search) {
      this.couponCurrentPage = val;
      this.couponListSearch = search;
    },
    // 获取文本卡券列表
    getCouponList (integralMallProId) {
      const params = {
        integralMallProId: integralMallProId,
        search: this.couponListSearch,
        currentPage: this.couponCurrentPage,
        pageSize: 10,
      };
      request.post('/api-integral-mall/page-giftcard', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result.rows) {
            this.couponListModal.tableDate = res.data.result.rows;
            this.couponListModal.total = res.data.result.total;
          } else {
            this.couponListModal.tableDate = [];
            this.couponListModal.total = 0;
          }
          this.couponListModal.dialogVisible = true;
          this.couponListModal.integralMallProId = integralMallProId;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 删除操作
    deleteList (item, type, index) {
      const params = {
        proId: item.integralMallProId,
        type: Number(type),
      };
      request.post('/api-integral-mall/delete-pro', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          const text = Number(type) === 0 ? '删除成功' : Number(type) === 1 ? '下架成功' : '上架成功';
          this.$message.success(text);
          if (Number(type) === 0) {
            this.tableDate.splice(index, 1);
            if (this.tableDate.length === 0) {
              if (this.currentPage > 1) {
                this.currentPage = this.currentPage - 1;
              }
            }
          }
          this.getList(); // 拉取列表
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 全选操作
    handleSelectAll (val) {
      this.selectArr = val;
    },
    // 批量操作
    handleData () {
      if (this.selectArr.length === 0) {
        this.$message.error('请先选择要批量操作的数据');
        this.goodsType = '';
        return false;
      }
      const shelfArr = []; // 上架的礼品id
      const soldOutArr = []; // 下架的礼品id
      const deleteArr = []; // 删除的礼品id
      let type = '';
      let proId = '';
      for (const item of this.selectArr) {
        if (item.status === 1) {
          // 下架状态（进行上架操作）
          soldOutArr.push(item.integralMallProId);
        } else if (item.status === 2) {
          // 上架状态（进行下架操作）
          shelfArr.push(item.integralMallProId);
        }
        deleteArr.push(item.integralMallProId);
      }
      if (this.goodsType === 0) {
        type = 2;
        // 批量上架
        if (soldOutArr.length === 0) {
          this.$message.error('请先选择要上架的数据');
          return false;
        } else {
          proId = soldOutArr.join(',');
        }
      } else if (this.goodsType === 1) {
        // 批量下架
        type = 1;
        if (shelfArr.length === 0) {
          this.$message.error('请先选择要下架的数据');
          return false;
        } else {
          proId = shelfArr.join(',');
        }
      } else if (this.goodsType === 2) {
        type = 0;
        // 批量删除
        if (deleteArr.length === 0) {
          this.$message.error('请先选择要删除的数据');
          return false;
        } else {
          proId = deleteArr.join(',');
        }
      }
      const params = {
        proId: proId,
        type: type,
      };
      request.post('/api-integral-mall/delete-pro', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          const text = Number(type) === 0 ? '删除成功' : Number(type) === 1 ? '下架成功' : '上架成功';
          this.$message.success(text);
          this.currentPage = 1;
          this.getList(); // 拉取列表
          this.goodsType = '';
        } else {
          this.$message.error(res.data.message);
          this.goodsType = '';
        }
      });
    },
    // 新增礼品
    addGift () {
      this.addModalData.dialogVisible = true;
    },
    // 编辑
    goAdd (item, type) {
      this.giftListObj = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        total: this.total,
        shelf: this.shelf,
        stockStatus: this.stockStatus,
        giftType: this.giftType,
        searchValue: this.searchValue.trim(),
        sortType: this.sortType,
        sortColumn: this.sortColumn,
      };
      window.localStorage.setItem('giftListObj', JSON.stringify(this.giftListObj));
      this.$router.push({ name: type === 'detail' ? 'giftDetail' : 'giftInfo', query: { type: item.giftType, giftId: item.integralMallProId, proReferId: item.proReferId, isDetail: type === 'detail' ? 1 : 0 } });
    },
    // 编辑序号
    editNumber (item) {
      item.editStatus = true;
      this.refash = !this.refash;
    },
    limitSort (value, item) {
      const reg = /^([1-9]\d*|[0]{1,1})$/; // 含0正整数
      if (!reg.test(item.sort)) {
        this.$message.error('序号必须是正整数');
        this.$nextTick(() => {
          item.sort = 0;
        });
        return false;
      }
    },
    // 确定编辑序号
    editNumSubmit (item) {
      const params = {
        integralMallProId: item.integralMallProId,
        sort: item.sort,
      };
      request.post('/api-integral-mall/update-integral-sort', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          this.$message.success('更新成功');
          item.editStatus = false;
          this.refash = !this.refash;
          this.getList(); // 拉取列表
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 取消编辑序号
    editNumCancel (item) {
      item.editStatus = false;
      this.refash = !this.refash;
    },
    // 调整库存弹框
    handleTable (item, type) {
      const params = {
        integralMallProId: item.integralMallProId,
      };

      request.post('/api-integral-mall/get-gift-sku', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          this.intergralModal.integralMallProId = item.integralMallProId;
          this.intergralModal.type = type;
          const list = copy(res.data.result);
          if (list.length) {
            // 多规格
            this.intergralModal.list = copy(res.data.result);
            this.intergralModal.stdNum = list.length;
            this.intergralModal.headerList = [];
            this.intergralModal.tableSkuData = [];
            // 有数据
            // 处理头部
            const header = JSON.parse(list[0].giftPropValues);
            for (const item of header) {
              this.intergralModal.headerList.push({
                proName: item.proName,
                proId: item.proId,
              });
            }
            if (type === 'cash') {
              // 积分现金
              this.intergralModal.headerList.push({
                proName: '积分',
                proId: '',
              });
              this.intergralModal.headerList.push({
                proName: '现金',
                proId: '',
              });
            } else if (type === 'stock') {
              // 库存
              this.intergralModal.headerList.push({
                proName: '库存',
                proId: '',
              });
            }

            // 获取表格数据
            let tem = [];
            for (const i in list) {
              tem = copy(JSON.parse(list[i].giftPropValues));
              if (type === 'cash') {
                tem.push({
                  valueName: list[i].giftProSkuIntegral, // 积分
                });
                tem.push({
                  valueName: list[i].giftProSkuCash, // 现金
                });
              } else if (type === 'stock') {
                tem.push({
                  valueName: list[i].stock, // 库存
                  currentStock: list[i].stock,
                });
              }

              this.intergralModal.tableSkuData.push(tem);
            }

            this.intergralModal.modalWidth = (this.intergralModal.tableSkuData[0].length + 1) * 120; // 根据内容设置弹框的宽度
            this.intergralModal.modalHeight = 200; // 根据内容设置弹框的宽度
          } else {
            // 单规格
            this.intergralModal.list = [];
            // 无规格
            this.intergralModal.stdNum = 0;
            this.intergralModal.headerList = [];
            this.intergralModal.tableSkuData = [];
            // let arrTem = [];
            // if (type === 'cash') {
            //   this.intergralModal.headerList.push({
            //     proName: '积分',
            //     proId: ''
            //   });

            //   this.intergralModal.headerList.push({
            //     proName: '现金',
            //     proId: ''
            //   });
            //   arrTem.push({
            //     valueName: item.integralCost,
            //     valueId: ''
            //   });
            //   arrTem.push({
            //     valueName: item.cashCost,
            //     valueId: ''
            //   });
            // } else if (type === 'stock') {
            //   this.intergralModal.headerList.push({
            //     proName: '库存',
            //     proId: ''
            //   });
            //   arrTem.push({
            //     valueName: '',
            //     valueId: ''
            //   });
            // }

            // this.intergralModal.tableSkuData.push(arrTem);
            this.intergralModal.tableSkuData = [];
            this.intergralModal.modalWidth = 450; // 根据内容设置弹框的宽度
            this.intergralModal.modalHeight = 80; // 根据内容设置弹框的宽度
          }
          this.intergralModal.integralCost = item.integralCost; // 积分
          this.intergralModal.cashCost = item.cashCost; // 现金
          this.intergralModal.proCode = item.proCode; // 编码
          this.intergralModal.virtualStock = item.virtualStock; // 库存
          this.intergralModal.dialogVisible = true;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    selectInit (row, index) {
      return row.canEdit;
    },
    // 获取礼品分类数据
    getCategoryOptions () {
      request.post('/api-integral-mall/load-category').then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result) {
            this.categoryOptions = res.data.result;
          } else {
            this.categoryOptions = [];
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
  },
};
</script>
<style scoped>

.w-300 {
  width: 300px;
}
.w-140 {
  width: 140px;
}
.gift-info img {
  width: 75px;
  height: 75px;
  border-radius: 4px;
  padding: 4px;
  border: 1px solid #dcdfe6;
  vertical-align: middle;
}
.info-name {
  display: inline-block;
  vertical-align: top;
  width: 60%;
}
.pro-ellipsis {
  color: #303133;
  height: 54px;
  line-height: 18px;
  /* width: 230px; */
  font-size: 14px;
}
.pro-ellipsis2 {
  color: #303133;
  height: 40px;
  line-height: 18px;
  /* width: 230px; */
  font-size: 14px;
}
.category-ellipsis {
  color: #909399;
  font-size: 13px;
}
.el-icon-edit {
  margin-left: 5px;
  cursor: pointer;
}
.operate-span {
  font-size: 13px;
  cursor: pointer;
}
.intergral-edit .el-icon-edit {
  display: none;
}
.intergral-edit:hover .el-icon-edit {
  display: inline-block;
}
.icon-xinxixianshi {
  margin-left: 5px;
  color: #909399;
  font-size: 14px;
  cursor: pointer;
}
.page-info {
  padding: 8px 16px;
  box-sizing: border-box;
  border-radius: 4px;
  background: #f4f4f5;
  color: #606266;
  margin-bottom: 22px;
  line-height: 1.5;
}
.page-info h3 {
  font-size: 13px;
  color: #606266;
  margin-bottom: 4px;
}
.page-info .el-icon-info {
  color: #1890ff;
  margin-right: 10px;
  font-size: 14px;
}
</style>
