<template>
  <div class="app-container">
    <el-card >
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="礼品名称" prop="giftName">
          <el-input
            v-model="queryParams.giftName"
            placeholder="请输入礼品名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" style="width: 217px" placeholder="全部" clearable
>
            <el-option
            v-for="dict in dict.type.zhzt"
                :key="dict.label"
                :label="dict.label"
                :value="dict.label"
            />
        </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
                          <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
       </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px" >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="giftAdd"
          >新增礼品</el-button>
        </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table ref="tables"
                v-loading="loading"
                :data="dataList"
                :default-sort="defaultSort">
        <el-table-column label="分类" align="center" prop="categoryName" width="90px">
          <template slot-scope="scope">
            {{ scope.row.categoryName==null? '不分类': scope.row.categoryName}}
            </template>
        </el-table-column>
        <el-table-column label="礼品信息" align="center">
          <el-table-column label="名称" align="center" prop="giftName" width="80px"/>
          <el-table-column label="封面图" align="center" prop="coverImage" width="80px">
            <template slot-scope="scope">
              <el-image
                style="width: 50px; height: 50px"
                :src="imagePath+scope.row.coverImage"
                :preview-src-list="[imagePath + scope.row.coverImage]"
                fit="cover">
              </el-image>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="兑换信息" align="center">
          <el-table-column label="兑换方式" align="center" prop="exchangeMethod">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag v-if ="scope.row.exchangeMethod == '积分'" effect="plain" size="medium">积分</el-tag>
                <el-tag v-if ="scope.row.exchangeMethod == '金额'" effect="plain" type="success" size="medium">金额</el-tag>
                <el-tag v-if ="scope.row.exchangeMethod == '积分+金额'" effect="plain" type="danger" size="medium">积分+金额</el-tag>
                <el-tag v-if ="scope.row.exchangeMethod == '积分+加钱购'" effect="plain" type="warning" size="medium">积分+加钱购</el-tag>
              </div>
          </template>
          </el-table-column>
          <el-table-column label="兑换价格" align="center" prop="">
            <template slot-scope="scope">
              <span v-if ="scope.row.exchangeMethod == '积分'" effect="plain" size="medium">{{scope.row.exchangePoints}}积分</span>
              <span v-if ="scope.row.exchangeMethod == '金额'" effect="plain" type="success" size="medium">{{scope.row.exchangeAmount}}元</span>
              <span v-if ="scope.row.exchangeMethod == '积分+金额'" effect="plain" type="danger" size="medium">{{scope.row.exchangePoints}}积分+{{scope.row.exchangeAmount}}元</span>
              <span v-if ="scope.row.exchangeMethod == '积分+加钱购'" effect="plain" type="warning" size="medium">{{scope.row.exchangePoints}}积分+加钱购比例{{ scope.row.moneyRatio }}</span>
            </template>

          </el-table-column>
        </el-table-column>
        <el-table-column label="配送类型" align="center" >
          <el-table-column label="配送方式" align="center" prop="deliveryMethod" width="80px">
            <template slot-scope="scope">
<!--                <span v-for="(row, index) in JSON.parse(scope.row.deliveryMethod)" :key="index">-->
                <span v-for="(row, index) in scope.row.deliveryMethod" :key="index">
                  {{row}}<br>
                </span>
            </template>
          </el-table-column>
          <el-table-column label="快递费用" align="center" prop="shippingFeeAmount">
            <template slot-scope="scope">
              <span v-if ="scope.row.expressShippingFee!= '统一运费' && scope.row.deliveryMethod && !scope.row.deliveryMethod.includes('物流配送')">--</span>
              <span v-else-if="scope.row.expressShippingFee === '包邮' && scope.row.deliveryMethod && scope.row.deliveryMethod.includes('物流配送')" effect="plain" type="warning" size="medium">包邮</span>
              <span v-else effect="plain" type="warning" size="medium">{{scope.row.shippingFeeAmount}}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="礼品类型" align="center" prop="giftType" width="80px"/>
        <el-table-column label="礼品库存信息" align="center">
          <el-table-column label="总库存" align="center" prop="totalInventory" width="80px">
            <template slot-scope="scope">
              <el-button type="text" @click="clickInventory(scope.row)">{{ scope.row.totalInventory===-1?'无限制': scope.row.totalInventory}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="已用" align="center" prop="usedInventory" width="80px">

          </el-table-column>
          <el-table-column label="可用" align="center" prop="remainingInventory" width="80px">
            <template slot-scope="scope">
              <span>{{  scope.row.totalInventory===-1?scope.row.totalInventory-scope.row.usedInventory+1: scope.row.totalInventory-scope.row.usedInventory}}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="40px"/>
        <el-table-column label="状态" align="center" prop="status" width="80px">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag v-if ="scope.row.status == '启用'" size="medium">启用</el-tag>
              <el-tag v-if ="scope.row.status == '禁用'" type="danger" size="medium">禁用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">

        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width = 70px>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog :title="title"  class="d-dialog" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="dataForm" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item label="礼品名称" prop="giftName">
              <el-input v-model="dataForm.giftName" placeholder="请输入礼品名称" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="分类" prop="categoryId">
              <el-select clearable v-model="dataForm.categoryId" placeholder="请选择礼品分类" style="width:100%">
                <el-option label="-不分类-" value=""></el-option>
                <el-option
                  v-for="option in giftCategoryList"
                  :key="option.id"

                  :label="option.categoryName"
                  :value="option.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="封面图" prop="coverImage">
              <el-upload
                   :action="uploadAction"
                   list-type="picture-card"
                   :class="{hide:hideUpload}"
                   :file-list="uploadFiles"
                   :auto-upload="true"
                   :show-file-list="false"
                   :headers="uploadHeader"
                   :on-success="handleUploadSuccessCover">
                <img
                  v-if="this.dataForm.coverImage"
                  :src="imagePath + this.dataForm.coverImage"
                  class="list-img"
                />
                <i v-if="!this.dataForm.coverImage" class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="礼品图片" >
              <el-upload
              :action="uploadAction"
                list-type="picture-card"
                :file-list="giftImages"
                :headers="uploadHeader"
                :auto-upload="true"
                :on-preview="handlePictureCardPreview"
                :on-success="handleUploadSuccessGift"
                style="height: 100px;"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
              <!-- <el-upload
                   :action="uploadAction"
                   list-type="picture-card"
                   :class="{hide:hideUpload}"
                   :file-list="uploadFiles"
                   :auto-upload="true"
                   :show-file-list="false"
                   :headers="uploadHeader"
                   :on-success="handleUploadSuccessGift">
                <img
                  v-if="this.dataForm.giftImages"
                  :src="imagePath + this.dataForm.giftImages"
                  class="list-img"
                />
                <i v-if="!this.dataForm.giftImages" class="el-icon-plus"></i>
              </el-upload> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-col :span="20">
            <el-form-item label="礼品类型" prop="giftType">
              <el-radio-group v-model="dataForm.giftType" @change="changeGiftType($event)">
                <el-radio
                  v-for="dict in dict.type.lplx"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  @change="handleIsopenSelect,changeGiftType"
                />
              </el-radio-group>
            </el-form-item>
          </el-col>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item v-if="showList.coupon" label="优惠券" prop="couponId">
              <el-select v-model="dataForm.couponId" placeholder="请选择" style="width: 202px;">
                <el-option
                  v-for="option in cardFavorableList"
                  :key="option.id"
                  :label="(option.type==0?'油品卷-':option.type==1?'商品卷-':'优惠卷-')+ option.name"
                  :value="option.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item v-if="showList.voucher" label="兑换券" prop="voucherId">
              <el-select v-model="dataForm.voucherId" placeholder="请选择" style="width: 202px;">
                <el-option
                  v-for="option in cardExchangeApiList"
                  :key="option.id"
                  :label="(option.type==0?'兑换券-':option.type==1?'洗车券-':'洗车卡-')+ option.name"
                  :value="option.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item v-if="showList.goods" label="关联商品" prop="goodsId">
                <el-input v-model="dataForm.goodsName" placeholder="" maxlength="30" style="width: 202px;" @focus="getCommodity"/>
              <!-- </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="礼品数量" prop="giftQuantity" style="width: 202px;">
              <el-input-number v-model="dataForm.giftQuantity" controls-position="right" :min="1" :max="10" label=""></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="市场价格" prop="market">
              <el-input v-model="dataForm.market" placeholder="请输入市场价格" maxlength="30" style="width: 202px;">
                <template slot="append">元</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="礼品库存" prop="totalInventory">
              <el-input v-model.number="dataForm.totalInventory" placeholder="礼品库存" maxlength="30" style="width: 202px;"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-col :span="20">
            <el-form-item label="兑换方式" prop="exchangeMethod">
              <el-radio-group v-model="dataForm.exchangeMethod" @change="changeExchange($event)">
            <el-radio
              v-for="dict in dict.type.redemptionMethod"
              :key="dict.value"
              :label="dict.label"
              @change="handleIsopenSelect"
              :value="dict.value"/>
            </el-radio-group>
            </el-form-item>
          </el-col>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col v-if="showList.jf" :span="8">
            <el-form-item v-show="showList.jf" label="兑换积分" prop="exchangePoints">
              <el-input v-model="dataForm.exchangePoints" placeholder="" maxlength="30" style="width: 202px;">
                <template slot="append">积分</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="showList.je" :span="8">
            <el-form-item label="兑换金额" prop="exchangeAmount">
              <el-input v-model="dataForm.exchangeAmount" placeholder="" maxlength="30" style="width: 202px;">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="showList.jfjq" :span="7">
            <el-form-item label="加钱比例" prop="moneyRatio" >
              <el-input v-model="dataForm.moneyRatio" placeholder="" maxlength="30" style="width: 202px;">
                <template slot="prepend">1积分=</template>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>



        <el-row :gutter="24" v-if="showList.delivery">
          <!-- <el-col :span="8">
            <el-form-item label="配送方式" prop="deliveryMethod">
              <el-checkbox v-for="item in dict.type.shippingMethod" :key="item.value" v-model="dataForm.deliveryMethod" :label="item.id">{{ item.label }}</el-checkbox>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="配送方式" prop="deliveryMethod">
              <el-checkbox v-for="item in dict.type.shippingMethod" :key="item.value" :label="item.label" :checked="dataForm.deliveryMethod != null?dataForm.deliveryMethod.includes(item.label):null" @change="changeExpress(item.label,1)">{{ item.label }}</el-checkbox>
            </el-form-item>
          </el-col>


          <el-col v-if="showList.express" :span="7">
            <el-form-item label="快递运费" prop="expressShippingFee">
              <el-radio-group v-model="dataForm.expressShippingFee" @change="changeExpress($event,2)">
                <el-radio
                  v-for="dict in dict.type.expressShippingCosts"
                  :key="dict.value"
                  :label="dict.label"
                  @change="handleIsopenSelect"
                  :value="dict.value"/>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col v-if="showList.shippingFee && showList.express" :span="7">
            <el-form-item label="运费金额" prop="shippingFeeAmount">
              <el-input v-model="dataForm.shippingFeeAmount" placeholder="" maxlength="30" style="width: 202px;" >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="兑换次数" prop="exchangeTimes">
              <el-input v-model.number="dataForm.exchangeTimes" placeholder="" maxlength="30" style="width: 202px;">
                <template slot="append">个</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="10">
            <el-form-item label="礼品排序" prop="sort" >
              <el-input-number v-model="dataForm.sort" :min="1" :max="10" label="" style="width: 202px;"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-col :span="20">
            <el-form-item label="礼品状态" prop="status">
              <el-radio-group v-model="dataForm.status">
            <el-radio
              v-for="dict in dict.type.zhzt"
              :key="dict.value"
              :label="dict.label"
              @change="handleIsopenSelect"
              :value="dict.value"/>
            </el-radio-group>
            </el-form-item>
          </el-col>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="23">
            <el-form-item label="图文详情" prop="detailedDescription">
                <editor @input="handleChildValue" :value.default="dataForm.detailedDescription" :height.default="150"></editor>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打开商品界面 -->
    <el-dialog title="选择商品" :visible.sync="openCommodity" width="1000px" append-to-body :close-on-click-modal="false">
      <el-container>
        <el-header style="">
          <el-form ref="tankForm" :model="commodityForm" label-width="80px">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="商品分类">
                    <el-select
                      v-model="commodityForm.cvsGoodId"
                      placeholder="全部"
                      clearable
                    >
                      <el-option v-for="item in cvsGoodList" :key="item.id" :label="item.name" :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
              <el-form-item label="供应商" prop="supplierId">
                <el-select
                  v-model="commodityForm.supplierId"
                  placeholder="全部"
                  clearable
                >
                  <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="详细信息">
                  <el-input v-model="commodityForm.remark" placeholder="商品名称，拼音码，条形码等信息" ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="inquire()">查询</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-header>
        <el-main>
          <el-table
            ref="tables"
            v-loading="loading"
            :data="commodityList"
            @row-click="handleRowClick"
            border
            :default-sort="defaultSort"
          >
          <el-table-column type="index" label="序号"></el-table-column>

          <!-- <el-table-column type="selection" width="55"></el-table-column> -->

            <el-table-column label="商品名称" align="center" prop="name"/>
            <el-table-column label="商品编码" align="center" prop="goodsNo"/>
            <el-table-column label="分类名称" prop="cvsGoodId" align="center">
              <template slot-scope="scope">
                <span>{{ getName(cvsGoodList, scope.row.cvsGoodId) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="供应商" prop="supplierId" align="center">
              <template slot-scope="scope">
                <span>{{ getName(supplierList, scope.row.supplierId) }}</span>
              </template>
            </el-table-column>
              <el-table-column label="单位" align="center" prop="unit"/>
            <el-table-column label="当前库存" align="center" prop="stock"/>
          </el-table>

        </el-main>
      </el-container>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addCommodity">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>


    <el-dialog title="库存变更" :visible.sync="openInventory" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="inventoryForm" :rules="rulesInventory" label-width="100px">
        <el-form-item label="当前总库存" prop="totalInventory" >
          <el-input disabled v-model="inventoryForm.totalInventory" placeholder="" maxlength="30" style="width: 270px;">
          </el-input>
        </el-form-item>
        <el-form-item label="已用库存" prop="usedInventory" >
          <el-input disabled v-model="inventoryForm.usedInventory" placeholder="" maxlength="30" style="width: 270px;">
          </el-input>
        </el-form-item>
        <el-form-item label="可用库存" prop="remainingInventory" >
          <el-input disabled v-model="inventoryForm.remainingInventory" placeholder="" maxlength="30" style="width: 270px;">
          </el-input>
        </el-form-item>
        <el-form-item  label="变更类型" prop="moneyRatio" >
          <el-radio-group :disabled="inventoryForm.flag" v-model="inventoryForm.inventoryFlag">
            <el-radio :label="0">增加库存</el-radio>
            <el-radio :label="1">减少库存</el-radio>
            <el-radio :label="2">不限库存</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="库存数量" prop="editInventory" >
          <el-input v-if="inventoryForm.inventoryFlag == 0" v-model.number="inventoryForm.editInventory" placeholder="" maxlength="30" style="width: 270px;">
            <template  slot="prepend">+</template>
          </el-input>
          <el-input v-else-if="inventoryForm.inventoryFlag == 1" v-model.number="inventoryForm.editInventory" placeholder="" maxlength="30" style="width: 270px;">
            <template  slot="prepend">-</template>
          </el-input>
          <el-input v-else="" disabled placeholder="变更为不限制库存" maxlength="30" style="width: 270px;"/>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInventory">确 定</el-button>
        <el-button @click="cancelInventory">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import {getGiftCategoryApi} from "@/api/integral/category";
import {getGiftApi,insertGiftApi,updateGiftApi ,updateGiftInventoryApi,getCardFavorableApi,getCardExchangeApi} from "@/api/integral/gift";
import { editor } from '@/components/Editor/index'
import { getToken } from '@/utils/auth'
import {listLJGoods} from "@/api/convenienceStore/ljgoods";
import {selectParentById, selectTree} from "@/api/convenienceStore/goods";


export default {

  name: "gift",
  dicts: ['zhzt','lplx','redemptionMethod','expressShippingCosts','shippingMethod'],

  data() {
    var valiNumberPass = (rule, value, callback) => {//包含小数的数字
        let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
        if (value === '') {
          callback(new Error('请输入内容'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入数字'));
        } else {
          callback();
        }
      };
    return {
      dataList: [],

      dataForm:{
        id: null,
        giftName: '', // 礼品名称
        categoryId:'', // 分类id
        goodsId:'', // 商品Id
        goodsName:'', // 商品Id
        voucherId:'', // 兑换券id
        coverImage:'', // 封面图
        giftImages: [], // 礼品图片
        giftType:"优惠券", // 礼品类型
        couponId:'',// 优惠券
        giftQuantity:'', // 礼品数量
        totalInventory:'', // 库存
        exchangeMethod:'积分', // 兑换方式
        exchangePoints:'', // 兑换积分
        exchangeTimes:'', // 兑换次数
        moneyRatio:'', // 价钱比例
        expressShippingFee:'', // 快递运费
        shippingFeeAmount:'', // 运费金额
        exchangeamount:'', // 兑换金额
        // deliveryMethod:['门店自提'], // 配送方式
        deliveryMethod:[], // 配送方式
        detailedDescription:'', // 图文详情
        categoryName: 1,
        sort: null,
        status: '启用',
        market:null
      },

      inventoryForm: {
        inventoryFlag: 0,
        remainingInventory: null,  // 剩余库存
        totalInventory: null,   //总库存
        usedInventory: null,  // 已用库存
        editInventory: null,
        flag: false,
        id:''
      },



      showList: {
        // 优惠类型展示
        coupon: true,
        voucher: false,
        goods: false,
        // 兑换方式展示
        jf:true,
        je:false,
        jfje:false,
        jfjq:false,
        // 配送方式
        delivery:false,
        express: false,
        shippingFee: false
      },
      getGiftTypeShow: '',
      // 兑换卷
      cardFavorableList:[],
      // 优惠券
      cardExchangeApiList:[],
      // 弹出框标题
      title:'',
      // 显示搜索条件
      showSearch: true,
      disableInput: false, // 默认不禁用
      // 是否显示弹出层
      // 总条数
      open: false,
      openCommodity: false,
      openInventory: false,
      total: 0,
      // 查询参数
      queryParams: {
        giftName: '',
        status: '',
        page:null,
        pageSize:null
      },
      dateRange:{},
      // 遮罩层
      loading: false,
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
      /**
       * 表单
       */
      giftCategoryList: [], // 查询分类列表

      // 批量图片
      giftImages: [],
      // 上传地址
      uploadAction: process.env.VUE_APP_SERVER_URL + 'backendApi/file/upload',
      uploadHeader: { 'Access-Token' : getToken() },
      // 隐藏上传
      hideUpload: false,
      // 上传文件列表
      uploadFiles: [
        {name:"nihao",
      url:'http://localhost:8008/static/uploadImages/20231103/ffbbe7d3ee1441fdaf706802fa0f176a.png'}
      ],
      // 图片根目录
      imagePath: process.env.VUE_APP_SERVER_URL,

      dialogImageUrl: "",
      dialogVisible: false,
      rulesInventory: {},
      rules: {
        deliveryMethod: [
          { type: 'array', required: true, message: '请至少选择一个配送方式', trigger: 'change' }
        ],
        giftName: [
          { required: true, message: "礼品名称不能为空", trigger: "blur" },
        ],
        coverImage: [
          { required: true, message: "封面不能为空", trigger: "blur" },
        ],
        giftType: [
          { required: true, message: "礼品类型不能为空", trigger: "change" },
        ],
        couponId: [
          { required: true, message: "请选择优惠券", trigger: "blur" },
        ],
        voucherId: [
          { required: true, message: "请选择兑换券", trigger: "blur" },
        ],
        goodsId: [
          { required: true, message: "请选择关联商品", trigger: "change" },
        ],
        giftQuantity: [
          { required: true, message: "礼品数量不能为空", trigger: "blur" },
        ],
        totalInventory: [
          { required: true, message: "礼品库存不能为空", trigger: "blur" },
        ],
        exchangeMethod: [
          { required: true, message: "兑换方式不能为空", trigger: "blur" },
        ],
        exchangePoints: [
        { required: true, validator:valiNumberPass, trigger: "blur" },
        ],
        exchangeAmount: [
        { required: true, validator:valiNumberPass, trigger: "blur" },
        ],
        moneyRatio: [
        { required: true, validator:valiNumberPass, trigger: "blur" },
        ],
        expressShippingFee: [
          { required: true, message: "快递运费不能为空", trigger: "change" },
        ],
        shippingFeeAmount: [
        { required: true, validator:valiNumberPass, trigger: "blur" },
        ],
        market: [
          { required: true, validator:valiNumberPass, trigger: "blur" },
        ],
        exchangeTimes: [
          { required: true, message: "兑换次数不能为空", trigger: "change" },
        ],
        sort: [
          { required: true, message: "礼品排序不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择礼品状态", trigger: "change" },
        ],

      },
      commodityList: [],

      commodityForm:{
        cvsGoodId: "",
        cvsGood: "",
        supplierId: "",
        supplier: "",
        detailed: "",
        remark: "",
        page: 1,
        pageSize: 1000,
        isRecovery:0,
      },


      cvsGoodList:[],
      // 供应商列表
      supplierList:[],


    }
  },

  watch: {
    getGiftTypeShow: function(newVal) {
    }
  },

  async created() {
    await this.getList();
  },
  methods: {
    getList() {
      getGiftApi(this.queryParams).then(res=>{
        this.dataList = res.data.records
        this.dataList.forEach(res=>{
          res.deliveryMethod = JSON.parse(res.deliveryMethod)
        })
        this.total = res.data.total
      })
    },

    submitForm: function() {
      let this_ = this
      // if (this.dataForm.deliveryMethod.length === 0) {
      //     this.$message.warning('请至少选择一个配送方式');
      //     return;
      //   }
      this_.$refs["form"].validate(valid => {
        if (valid) {
          if (Array.isArray(this_.dataForm.giftImages)) {
            this_.dataForm.giftImages = JSON.stringify(this_.dataForm.giftImages);
          }
          if (this_.dataForm.deliveryMethod != null && Array.isArray(this_.dataForm.deliveryMethod)) {
            this_.dataForm.deliveryMethod = JSON.stringify(this.dataForm.deliveryMethod);
          }
          this_.dataForm.remainingInventory = this_.dataForm.totalInventory

          if (this_.dataForm.id == null) {
            // 判断是否是新增还是修改
            insertGiftApi(this_.dataForm).then(res => {
            this_.getList(),
            this_.open = false
          })
          } else {
            // 判断是否是新增还是修改
            updateGiftApi(this_.dataForm).then(res => {
              this_.getList()
              this_.open = false
          })
        }
      }})
    },

    submitInventory: function(){
      if (this.inventoryForm.inventoryFlag === 1) {
        this.inventoryForm.editInventory = - this.inventoryForm.editInventory
      } else if(this.inventoryForm.inventoryFlag === 2) {
        this.inventoryForm.editInventory = -this.inventoryForm.totalInventory - 1
      }
      if (this.inventoryForm.totalInventory == '无限制') {
        this.inventoryForm.editInventory = this.inventoryForm.editInventory+1
      }
      updateGiftInventoryApi(this.inventoryForm).then(res=>{

        this.getList();
      })

      this.openInventory = false

      this.resInventoryForm()

    },

    resInventoryForm() {
      this.inventoryForm = {
        inventoryFlag: 0,
        remainingInventory: null,  // 剩余库存
        totalInventory: null,   //总库存
        usedInventory: null,  // 已用库存
        editInventory: null,
        flag: false,
        id:''
      }
    },

    // 新增
    giftAdd() {
      this.reset();
      this.open = true
      this.title = '添加礼品'
      this.changeGiftType("优惠券")
      this.selectGiftCategory();
      this.cardFavorableApi();
      this.cardExchangeApi();
      this.$forceUpdate();

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelInventory() {
      this.openInventory = false;
      this.resInventoryForm()
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 修改按钮
    async handleUpdate(data) {

      await this.cardFavorableApi();
      await this.cardExchangeApi();
      await this.selectGiftCategory();

      // 处理图片
      // let fileList = JSON.parse(data.giftImages);
      // this.giftImages = [],
      // this.giftImages = fileList;
      // this.giftImages.forEach(image=>{
      //   let sp = image.url.split('//')
      //   image.url = this.imagePath + '/'+sp[2]
      // })
      //

      this.giftImages = []
      data.giftImages = JSON.parse(data.giftImages);
      data.giftImages.forEach(res=> {
        let newImage = {
          url: this.imagePath + res,
          fileName: res
        }
        this.giftImages.push(newImage);
      }),

      // data.deliveryMethod = JSON.parse(data.deliveryMethod);

        console.log("data",data)
      this.dataForm = data;
      this.changeGiftType(this.dataForm.giftType)
      this.changeExchange(this.dataForm.exchangeMethod)
      this.changeExpressEDIT()


      console.log(" this.dataForm", this.dataForm)

      this.open = true;
      this.getList();
    },

    cardFavorableApi () {
      getCardFavorableApi().then(res=>{
        this.cardFavorableList = res.data.records
      })
    },

    cardExchangeApi () {
      getCardExchangeApi().then(res=>{
        this.cardExchangeApiList =res.data.records
      })
    },

    resetQuery() {
      this.queryParams= {
        giftName: '',
        status: '',
        page:null,
        pageSize:null
      },
      this.getList()
    },
    reset(){
      this.dataForm={
        giftName: '', // 礼品名称
        categoryId:'', // 分类id
        goodsId:'', // 商品Id
        goodsName:'', // 商品Id
        voucherId:'', // 兑换券id
        coverImage:'', // 封面图
        giftImages: [], // 礼品图片
        giftType:"优惠券", // 礼品类型
        couponId:'',// 优惠券
        giftQuantity:'', // 礼品数量
        totalInventory:'', // 库存
        exchangeMethod:'积分', // 兑换方式
        exchangePoints:'', // 兑换积分
        exchangeTimes:'', // 兑换次数
        moneyRatio:'', // 价钱比例
        expressShippingFee:'', // 快递运费
        shippingFeeAmount:'', // 运费金额
        exchangeamount:'', // 兑换金额
        // deliveryMethod:['门店自提'], // 配送方式
        deliveryMethod:[], // 配送方式
        detailedDescription:'', // 图文详情
        categoryName: 1,
        sort: null,
        status: '启用',
        market:null
      }

      this.showList = {
        // 优惠类型展示
        coupon: true,
        voucher: false,
        goods: false,
        // 兑换方式展示
        jf:true,
        je:false,
        jfje:false,
        jfjq:false,
        // 配送方式
        delivery:false,
        express: false,
        shippingFee: false
      },
      this.giftImages=[]

    },

    clickInventory(data) {
      this.resInventoryForm()

      this.openInventory = true
      this.inventoryForm.id = data.id

      if (data.usedInventory == null || data.usedInventory == undefined) {
        this.inventoryForm.usedInventory = 0
      }else {
        this.inventoryForm.usedInventory = data.usedInventory
      }
      if (data.totalInventory == 0) {
        this.inventoryForm.totalInventory = 0
        this.inventoryForm.remainingInventory = 0
      }else if (data.totalInventory === -1) {
        this.inventoryForm.flag = true
        this.inventoryForm.totalInventory = '无限制'
        this.inventoryForm.remainingInventory = '无限制'
      } else {
        this.inventoryForm.totalInventory = data.totalInventory
        this.inventoryForm.remainingInventory = data.totalInventory - data.usedInventory
      }





      // inventoryForm: {
      //   inventoryFlag: 0,
      //   remainingInventory: null,  // 剩余库存
      //   totalInventory: null,   //总库存
      //   usedInventory: null,  // 已用库存
      //   editInventory: null,

      //   id:''
      // },
    },



    /**
     * 表单
     */

    // 表单初始化
    initializeForm() {

    },

    // 分类查询
    selectGiftCategory() {
      let queryParams = {pageSize : 1000}
      getGiftCategoryApi(queryParams).then(response => {
        this.giftCategoryList = response.data.records;
      })

    },
    // 选择礼品类型
    changeGiftType(newVal) {
      let this_ = this
      if (newVal == '优惠券') {
        this_.showList.coupon = true
        this_.showList.voucher = false
        this_.showList.goods = false
        this_.showList.delivery = false
      } else if (newVal == '兑换券') {
        this_.showList.coupon = false
        this_.showList.voucher = true
        this_.showList.goods = false
        this_.showList.delivery = true
      } else if(newVal == '实物商品') {
        this_.showList.coupon = false
        this_.showList.voucher = false
        this_.showList.goods = true
        this_.showList.delivery = true
      }
    },
    // 兑换方式
    changeExchange(newVal){
      let this_ = this
      if (newVal == '积分') {
        this_.showList.jf = true
        this_.showList.je = false
        this_.showList.jfjq = false
      } else if (newVal == '金额') {
        this_.showList.jf = false
        this_.showList.je = true
        this_.showList.jfjq = false
      } else if (newVal == '积分+金额') {
        this_.showList.jf = true
        this_.showList.je = true
        this_.showList.jfjq = false
      } else if (newVal == '积分+加钱购') {
        this_.showList.jf = true
        this_.showList.je = false
        this_.showList.jfjq = true
      }
    },
    // 快递（处理选择）
    changeExpress(data,flag){
      let this_ = this
      // express: false,
      // shippingFee: false
      if(flag === 1) {
        if (!this.dataForm.deliveryMethod) {
              this.dataForm.deliveryMethod = [];
              this.showList.express= false
            }
            if (!Array.isArray(this.dataForm.deliveryMethod)) {
              this.dataForm.deliveryMethod = JSON.parse(this.dataForm.deliveryMethod);

            }
            // const jsonArray = JSON.parse(this.dataForm.deliveryMethod);
            // const index = jsonArray.indexOf(data);
            const index = this.dataForm.deliveryMethod.indexOf(data);
            if (index === -1) {
              this.dataForm.deliveryMethod.push(data);
              // const jsonArray = JSON.parse(this.dataForm.deliveryMethod);
              // jsonArray.push(data)
              // this.dataForm.deliveryMethod = jsonArray

              if(data == '物流配送') {
                this.showList.express= true
              }
            } else {
              this.dataForm.deliveryMethod.splice(index, 1)
              // const jsonArray = JSON.parse(this.dataForm.deliveryMethod);
              // jsonArray.splice(index, 1);
              // this.dataForm.deliveryMethod = JSON.stringify(jsonArray)

              if(data == '物流配送') {
                this.showList.express= false
              }
            }
      } else {
          if (data == '包邮') {
            this.showList.shippingFee= false
          } else if (data == '统一运费') {
            this.showList.shippingFee= true
          }
      }
    },
    // 快递 修改时处理
    changeExpressEDIT(){
      if (!this.dataForm.deliveryMethod) {
        this.dataForm.deliveryMethod = [];
        this.showList.express= false
      }
      if(!this.dataForm.expressShippingFee) {
        this.dataForm.expressShippingFee= ''
        this.showList.shippingFee= false
      }
      let this_ = this
      if (!Array.isArray(this_.dataForm.deliveryMethod)) {
        this_.dataForm.deliveryMethod = JSON.parse(this_.dataForm.deliveryMethod);
      }
      if (this_.dataForm.deliveryMethod && this_.dataForm.deliveryMethod.includes("物流配送")) {
        this.showList.express= true

      }
      if (this_.dataForm.expressShippingFee == "统一运费") {
        this.showList.shippingFee= true
      }

    },


    // 点击按钮处理
    handleIsopenSelect() {
      this.$forceUpdate()
    },
    // 上传封面
    handleUploadSuccessCover(file) {
      this.dataForm.coverImage = file.data.fileName;
    },
    // 上传详情图
    handleUploadSuccessGift(file) {
      let newImage = {
        url: process.env.VUE_APP_SERVER_URL + file.data.fileName,
        fileName: file.data.fileName
      }
      if (this.giftImages == undefined) {
        this.giftImages = [];
      }
      this.giftImages.push(newImage);
      this.dataForm.giftImages.push(file.data.fileName);


      console.log("this.giftImage",this.giftImages)
      console.log(" this.dataForm.giftImages", this.dataForm.giftImages)
    },


    handleRemove(file, fileList) {

      console.log(file, fileList)
      this.giftImages.forEach((image, index) => {
        if (file.url === image.url) {
          this.giftImages.splice(index, 1);
        }
      });

      this.dataForm.giftImages.forEach((image, index) => {
        if (file.fileName === image) {
          this.dataForm.giftImages.splice(index, 1);
        }
      })
      console.log("this.giftImage",this.giftImages)
      console.log(" this.dataForm.giftImages", this.dataForm.giftImages)    },
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },



    handleChildValue(value) {
      this.dataForm.detailedDescription = value
    },




    // 商品列表

    getCommodityList() {
      let this_ = this
      listLJGoods(this_.commodityForm).then(res=>{
        this_.commodityList = res.data.records;
        // this_.sumMethod(res.data.records);
        // this.total = response.data.total;
      })
    },
    // 查询商品
    inquire() {
      this.getCommodityList();
    },
    // 表格选择器
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleRowClick(row) {
      this.openCommodity = false
      this.$refs.tables.clearSelection(); // 清除当前选中的行
      this.$refs.tables.toggleRowSelection(row); // 选中当前点击的行
      // 处理选中的行数据
      console.log("row",row)
      // stock
      this.dataForm.totalInventory = row.stock
      this.dataForm.market = row.retailPrice
      this.dataForm.goodsName = row.name
      this.dataForm.goodsId = row.id

    },
    getCommodity() {
      this.getQueryList()
      this.openCommodity = true

    },
     // 查询搜索列表信息
     getQueryList(){
      selectTree().then(response => {
        this.cvsGoodList = response.data.records
      });
      // listSupplier().then(response => {
      //   this.supplierList = response.data.records
      // })
    },
    addCommodity () {

    }
  }
}
</script>

<style scoped>

.app-container{
  width: 100%;
  height: 100%;
  background: #f6f8f9;
}

.d-dialog >>> .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.d-dialog >>> .avatar-uploader .el-upload {
  width: 100px;
  height: 100px;
}
.d-dialog >>> .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}

.list-img{
  width: 98px;
  height: 98px;
}
</style>
