<template>
  <!-- 商品管理页面 -->
  <div>
    <div class="cardBox">
      <div class="searchBox">
        <div class="row">
          <span>商品名称：</span>
          <el-input v-model="form.goods_title" @keyup.enter.native="handleChoose" placeholder="商品名称" clearable></el-input>
        </div>
        <div class="row">
          <span>商品品种/品类：</span>
          <treeselect
            :options="treeList"
            style="width: 200px;"
            :disable-branch-nodes="true"
            :show-count="true"
            :normalizer="normalizer"
            placeholder="请选择品种"
            v-model="form.type_id">
            <div slot="value-label" slot-scope="{ node }">{{ parseLabel(node) }}</div>
          </treeselect>
        </div>
        <div class="row">
          <span>商品编码：</span>
          <el-input v-model="form.external_sku_id" @keyup.enter.native="handleChoose" placeholder="商品编码" clearable></el-input>
        </div>
        <div class="row">
          <span>商品状态：</span>
          <el-select v-model="form.status" placeholder="商品状态" clearable @change="handleChoose()">
            <el-option v-for="item in options" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="row">
          <span>创建时间：</span>
          <el-date-picker
            v-model="filterTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
            style="width: 250px;"
            @change="handleChoose()">
          </el-date-picker>
        </div> 
        <div class="row">
          <span>剩余库存≠：</span>
          <el-input v-model="form.neq_stock" @keyup.enter.native="handleChoose" placeholder="剩余库存" clearable></el-input>
        </div>
        <div class="row">
          <span>在售库存≠：</span>
          <el-input v-model="form.neq_sale_stock" @keyup.enter.native="handleChoose" placeholder="在售库存" clearable></el-input>
        </div>
        <div class="row">
          <el-button type="primary" @click="handleChoose()" icon="el-icon-search">筛选</el-button>
          <el-button plain @click="handleReChoose" icon="el-icon-refresh">重置筛选</el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div>
        <!-- 表格头部操作 -->
        <div style="display: flex;align-items: center;justify-content: space-between;">
            <div style="display: flex;flex-wrap: wrap;">
              <span style="margin-right: 20px;">全部商品(共{{ total }}条)</span>
              <div v-if="sum" style="color: #f00;">销量{{ sum.goods_number }}，实际库存{{ sum.real_stock }}，剩余库存{{ sum.stock }}</div>
            </div>
            <div class="btn">
              <el-button @click="resetOrderCount" icon="el-icon-refresh">订单重置</el-button>
              <el-button type="primary" @click="petchEditStock" icon="el-icon-edit" :disabled="!chooseList.length">批量更新在售库存</el-button>
              <el-button type="primary" v-if="is_admin" @click="addNewgoods" icon="el-icon-plus">新增商品</el-button>
              <el-button type="primary" plain v-if="is_admin" @click="handleImport" icon="el-icon-upload2">在售库存导入</el-button>
              <el-button type="warning" @click="handleTypeExport" icon="el-icon-download">选择类型导出</el-button>
              <el-button type="warning" @click="handleExport" icon="el-icon-download">数据导出</el-button>
            </div>
        </div>

        <!-- 表格 -->
        <el-table v-loading="loading" ref="multipleTable" border :data="tableData" class="table" tooltip-effect="dark"
            style="width: 100%" @selection-change="handleSelectionChange" @sort-change="sortChange">
            <!-- 多选框 -->
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="商品信息" width="300">
              <template slot-scope="scope">
                <div class="goodBox flex">
                  <img v-if="scope.row.goods && scope.row.goods.img_url" :src="scope.row.goods.img_url" class="Img" />
                  <div>
                    <div class="tit">{{ scope.row.name }}</div>
                    <p>{{ scope.row.external_sku_id }}</p>
                    <p>{{ scope.row.created_at }}</p>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="cost" label="成本" align="center">
              <template slot-scope="scope">
                <div class="flex" style="justify-content: center;">
                  <div v-if="isShow">
                    <el-input v-model="scope.row.cost"></el-input>
                  </div>
                  <span v-else>{{ scope.row.cost ||  0 }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="order_goods_num" sortable="custom" label="销量" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.order_goods_num }}</span>
                <el-popover placement="right-start" trigger="hover"
                  v-if="scope.row.order_detail.length !== 0">
                  <div>
                    <span v-for="(j, index) in scope.row.order_detail" :key="index">
                      <div>{{ j.shop.name }}:{{ j.number }}</div>
                    </span>
                  </div>
                  <i class="el-icon-view" slot="reference" style="padding-left: 5px;"></i>
                </el-popover>
              </template>
            </el-table-column>

            <el-table-column prop="yesterday_num" label="实际库存" align="center"></el-table-column>
            <el-table-column prop="sale_stock" label="可售库存" sortable="custom" width="160">
              <template slot-scope="scope">
                <div class="titBox" v-if="scope.row.edit">
                  <el-input v-model="scope.row.sale_stock" placeholder="可售库存" size="mini" style="width: 100%;"></el-input>
                  <span @click="cancelEdit(scope.row, scope.$index)" style="color: #666;cursor: pointer;font-size: 18px;margin-left: 5px;"><i class="el-icon-close"></i></span>
                  <span @click="confirmEdit(scope.row, scope.$index)" style="color: #409eff;cursor: pointer;font-size: 18px;margin-left: 5px;"><i class="el-icon-check"></i></span>
                </div>
                <div v-else>{{scope.row.sale_stock}}
                  <span style="color: #409eff;margin-left: 5px;cursor: pointer;font-size: 15px;"
                    @click="openSaleEdit(scope.row, scope.$index)">
                    <i class="el-icon-edit"></i>
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="剩余库存" sortable="custom" align="center" prop="stock">
              <template slot-scope="scope">
                <span :class="scope.row.stock * 1 < 0 ? 'red' : ''">{{ scope.row.stock }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="120" v-if="is_admin">
              <template slot-scope="scope">
                <el-button type="text" @click="handleEdit(scope.row.id)">编辑</el-button>
              </template>
            </el-table-column>
        </el-table>
      </div>

        <!-- 底部按钮 -->
        <div class="footerBtn" v-show="isShow || stock">
          <el-button type="primary" class="confirmbtn" @click="cancel()">取消</el-button>
          <el-button type="primary" class="confirmbtn" @click="onSubmit()">保存</el-button>
        </div>

        <div class="page-pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="current_page"
            :page-sizes="[10, 30, 50, 100, 200]"
            :page-size="per_page"
            layout="total, sizes, prev, pager, next, jumper"
            :total="Paginationdata.total">
          </el-pagination>
        </div>
    </el-card>

    <!-- 点击库存按钮弹出框 -->
    <el-dialog title="库存修改" :visible.sync="ejectstock1" width="30%" :close-on-click-modal="false">
      <el-table :data="ommodityInventory" tooltip-effect="dark" style="width: 100%">
        <el-table-column prop="two_days_ago_num" label="2天前库存">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.two_days_ago_num" :disabled="true"></el-input>
              <el-input v-model="scope.row.two_days_ago_num"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="yesterday_num" label="1天前库存">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.yesterday_num" :disabled="true"></el-input>
              <el-input v-model="scope.row.yesterday_num"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column sortable label="今日到货">
          <template slot-scope="scope">
            <div>
              <el-input v-model="scope.row.daily.arrived_today_num" :disabled="true"></el-input>
              <el-input v-model="scope.row.daily.arrived_today_num"></el-input>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelStock()">取 消</el-button>
        <el-button type="primary" @click="oldStock()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 参考售价弹出确认框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible3" width="20%" :close-on-click-modal="false">
      <span>确定要修改售价吗?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="referencePriceRequest()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 目标去化率弹出框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible5" width="20%" :close-on-click-modal="false">
      <span>确定要修改目标去化率吗?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelGoal">取 消</el-button>
        <el-button type="primary" @click="confirmGoal()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击表格导出弹出框 -->
    <el-dialog title="表格导出" :visible.sync="Tableexport" width="30%" :close-on-click-modal="false">
      <div>
        <span>选择：</span>
        <template>
          <el-select v-model="value" placeholder="盘点表/成本表/周数据">
            <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </template>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Tableexport = false">取 消</el-button>
        <el-button type="primary" @click="derivation()">确 定</el-button>
        <!-- <a href="/goods_skus/export">确定</a> -->
      </span>
    </el-dialog>

    <!-- 点击商品文件导入弹出框 -->
    <el-dialog title="在售库存导入" :visible.sync="docImportDrawer" direction="rtl" custom-class="demo-drawer" ref="drawer"
      width="450px" @close="importForm.imFileList = []" :close-on-click-modal="false">
      <div class="demo-drawer__content">
        <el-upload class="upload-demo" action="" :limit="1" drag ref="aupload"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :file-list="importForm.fileList" :auto-upload="false" :on-change="importFileChange">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <div class="import-right">
        <el-button size="medium" type="text">
          <a :href="`/goods/import/template`">下载模板</a>
        </el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="docImportDrawer = false">取 消</el-button>
        <el-button type="primary" @click="saveUpload">上 传</el-button>
      </span>
    </el-dialog>

    <el-dialog title="可售库存" :visible.sync="showUpdate" width="600px">
      <div class="">
        <el-table :data="chooseList" border style="width: 100%">
          <el-table-column label="商品信息">
            <template slot-scope="scope">
              <div class="goodBox flex">
                <img v-if="scope.row.goods && scope.row.goods.img_url" :src="scope.row.goods.img_url" class="Img" />
                <div>
                  <div class="tit">{{ scope.row.name }}</div>
                  <p>{{ scope.row.external_sku_id }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="可售库存" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sale_stock"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showUpdate = false">取 消</el-button>
        <el-button type="primary" @click="commitPetchStock()" :loading="commitLoading">更 新</el-button>
      </span>
    </el-dialog>

    <!-- 新增商品 -->
    <add-goods :show="showAdd" @close="showAdd = false" @complete="refreshList"></add-goods>

    <!-- 编辑商品 -->
    <edit-goods :show="showEdit" :id="curId" @close="showEdit = false" @complete="refreshList"></edit-goods>

  </div>
</template>

<script>
  import axios from 'axios'
  import { goods_types } from '@/api/rankingData.js'
  import { goods, update, singleUpdate, getStockNum, updateSaleStock } from '@/api/goods'
  import { orderRest } from "@/api/shop"
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import addGoods from "@/components/Goods/add.vue"
  import editGoods from "@/components/Goods/edit.vue"

  export default {
    components: { Treeselect, addGoods, editGoods },
    data() {
      return {
        editPriceId: '', //参考售价的id
        editGoalId: '',
        total: 0, // 总条数
        rose_num: 0, // 玫瑰数量
        other_num: 0, // 其它数量
        radio: '', // 损耗选择的原因
        brand: [], // 品牌列表
        treeList: [], // 种类列表
        loading: false,
        tableData: [], // 商品列表
        shopsData: [], //店铺传参数组
        sku_code: {}, //店铺传参对象
        options: [
          { id: 1, label: '在售' },
          { id: 2, label: '预警' },
          { id: 0, label: '下架' }
        ],
        options2: [
          { value: 'inventory', label: '盘点表' },
          { value: 'cost', label: '成本表' },
          { value: 'week_data', label: '周数据' }
        ],
        value: '',
        options3: [
          { value: 'stock', label: '库存' },
          { value: 'cost', label: '成本' },
          { value: 'loss_num', label: '损耗' },
          { value: 'reserve', label: '预留' }
        ],
        form: {
          external_sku_id: '',
          neq_stock: '',
          neq_sale_stock: '',
          goods_title: '', // 商品名称
          type_id: null, // 商品种类id
          brand_id: '', // 商品品牌id
          sku_title: '', // 商品规格
          status: '', // 商品状态
          keyword_type: "stock", //筛选类型
          keyword_value: '' //日期筛选
        },
        Paginationdata: {}, //分页相关数据
        current_page: 1, //当前页
        per_page: 10, //每页显示数量
        updateType: '', //更新类型，newest-上新, inventory-库存盘点, stock-库存
        stock: false, //点击库存显示输入框变量
        isShow: false, // 点击上新显示输入框
        ejectstock1: false, //点击库存按钮弹出框变量
        Importgoods: false, //导入商品变量
        Tableexport: false, //表格导出变量
        isShow1: false, //文件传输弹出变量
        //表格导入相关变量
        importForm: {
          fileList: []
        },
        docImportDrawer: false,
        improtRules: {
          fileList: [
            { required: true, message: "请导入Excel文件", trigger: "change" },
            {
              validator: (rule, value, callback) => {
                if (!value.length) {
                  callback(new Error("请导入Excel文件"))
                } else {
                  callback()
                }
              },
              trigger: "change"
            }
          ]
        },
        // 文件模板手添加到根目录下
        publicPath: process.env.BASE_URL, // public文件夹路径
        excelTemplatePath: '', // 数据导入Excel模板下载地址 - 调接口获取
        visible: false,
        updateField: '', //reference_price-参考售价, reserve-预留量, loss_num-损耗, status-状态
        reserveShow: false, //预留量-input显示变量
        ommodityInventory: [], //单个商品库存
        dialogVisible: false, //上新按钮弹出框变量
        dialogVisible2: false, //库存盘点弹出框变量
        dialogVisible3: false, //参考售价弹出框变量
        dialogVisible5: false,
        publicId: '',
        lastVal: 0,
        nowVal: 0,
        loadingModule: '',
        noRow: {},
        chooseList: [],
        showUpdate: false,
        commitLoading: false,
        is_admin: false,
        showAdd: false,
        showEdit: false,
        curId: 0,
        filterTime: [],
        sort_field: '',
        sort_value: '',
        sum: null
      }
    },
    methods: {
      // 库存详情
      getStockInfo() {
        getStockNum().then((res) => {
          this.rose_num = res.data.rose_num
          this.other_num = res.data.other_num
        })
      },
      // 列表编辑
      handleEdit(id) {
        this.curId = id
        this.showEdit = true
      },

      // 获取商品列表
      getList() {
        this.loading = true
        let params = {
          ...this.form,
          page: this.current_page,
          per_page: this.per_page,
          create_time_start: this.filterTime ? this.filterTime[0] : '',
          create_time_end: this.filterTime ? this.filterTime[1] : '',
          sort_field: this.sort_field || 'id',
          sort_value: this.sort_value || 'desc'
        }
        params.type_id = params.type_id || ''
        goods(params).then((res) => {
          this.tableData = res.data.data
          this.tableData = this.tableData.map((item) => {
            item = {
              ...item,
              arrived_today_num11: 0
            }
            return item
          })
          this.total = res.data.meta.total;
          this.Paginationdata = res.data.meta;
          this.shopsData = this.tableData.map((item) => {
            item = item.goods && item.goods.goods_code + "_" + item.sku_code
            return item
          })
          this.sku_code = {
            sku_code: this.shopsData
          }
          this.is_admin = res.data.manage && res.data.manage.is_admin
          this.sum = params.goods_title ? res.data.sum : null
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },

      // 筛选
      handleChoose() {
        this.current_page = 1
        this.getList()
      },

      // 重置筛选
      handleReChoose() {
        this.form = {
          external_sku_id: '',
          goods_title: '',
          type_id: null,
          brand_id: '',
          sku_title: '',
          status: '',
          neq_stock: '',
          neq_sale_stock: ''
        }
        this.filterTime = []
      },

      // 导入商品按钮
      handleImport() {
        this.importForm.fileList = []
        this.docImportDrawer = true
        this.$nextTick(function () {
          this.$refs.aupload.clearFiles()
        })
      },
      // 导出商品按钮
      handleTypeExport() {
        this.Tableexport = true
      },
      // 订单重置计数
      resetOrderCount() {
        this.$confirm('确定重置订单计数?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          orderRest().then((res) => {
            this.$message({
              type: 'success',
              message: res.data.message
            })
            this.getList()
          })
        }).catch(() => {
          
        })
      },
      // 点击上新
      update() {
        this.isShow = true
        this.stock = false
        this.updateType = 'newest'
      },
      // 复选框按钮
      handleSelectionChange(val) {
        this.chooseList = JSON.parse(JSON.stringify(val))
      },
      addNewgoods() {
        this.showAdd = true
      },
      refreshList() {
        this.handleChoose()
      },

      //分页功能
      handleSizeChange(val) {
        this.per_page = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.current_page = val
        this.getList()
      },

      //取消上新or库存盘点
      cancel() {
        this.current_page = 1
        this.getList()
        this.isShow = false
        this.stock = false
      },

      handleExport() {
        let params = {
          exportType: 'goods_sku',
          external_sku_id: this.form.external_sku_id,
          goods_title: this.form.goods_title,
          neq_stock: this.form.neq_stock,
          neq_sale_stock: this.form.neq_sale_stock,
          type_id: this.form.type_id || '',
          status: this.form.status,
          keyword_type: 'stock',
          create_time_start: this.filterTime ? this.filterTime[0] : '',
          create_time_end: this.filterTime ? this.filterTime[1] : ''
        }
        window.open("/goods_skus/export?" + this.objectToQueryString(params))
      },

      objectToQueryString(obj) {
        return Object.keys(obj)
              .map(key => encodeURIComponent(key) + '=' + (obj[key] ? encodeURIComponent(obj[key]) : ''))
              .join('&');
      },
      sortChange(column) {
        this.sort_field = column.order ? column.prop : ''
        this.sort_value = column.order ? (column.order == 'descending' ? 'desc' : 'asc') : ''
        this.current_page = 1
        this.getList()
      },
      // 点击上新or库存盘点后确认
      onSubmit() {
        //判断点击的是上新，再发送上新请求
        if (this.updateType === "newest") {
          let skus = this.tableData.map((item) => {
            return [
              {
                id: item.id,
                cost: item.cost,
                arrived_today_num: item.arrived_today_num11
              }
            ]
          })
          let patchdata = {
            updateType: this.updateType,
            skus: skus.flat()
          }
          // 上新请求
          update(patchdata).then((res) => {
            this.$message({
              message: "上新成功！",
              type: "success"
            })
          })
        }

        //判断点击的是库存盘点，再发送库存盘点请求
        if (this.updateType === "inventory") {
          let skus = this.tableData.map((item) => {
            return [
              {
                id: item.id,
                inventory: item.daily.inventory
              }
            ]
          })
          let patchdata = {
            updateType: this.updateType,
            skus: skus.flat()
          }
          // 上新请求
          update(patchdata).then((res) => {
            this.$message({
              message: "库存盘点成功！",
              type: "success"
            })
          })
        }
        this.isShow = false
        this.stock = false
        this.handleChoose(this.current_page)
      },

      // 点击库存盘点
      onCount() {
        this.dialogVisible2 = false
        this.isShow = false
        this.stock = true
        this.updateType = "inventory"
      },

      // 点击库存弹出框
      ejectstock(row) {
        this.ommodityInventory = []
        this.ejectstock1 = true
        this.updateType = "stock"
        this.ommodityInventory.push(row)
      },

      //库存弹出框取消
      cancelStock() {
        this.handleChoose(this.current_page)
        this.ejectstock1 = false
      },

      // 库存弹出框确认
      oldStock() {
        this.ejectstock1 = false
        //判断点击的是库存，再发送库存请求
        if (this.updateType === "stock") {
          let skus = [
            {
              id: this.ommodityInventory[0].id,
              yesterday_num: this.ommodityInventory[0].yesterday_num,
              two_days_ago_num: this.ommodityInventory[0].two_days_ago_num,
              arrived_today_num: this.ommodityInventory[0].daily.arrived_today_num
            }
          ]
          let stockpatch = {
            updateType: this.updateType,
            skus: skus
          }
          // 库存请求
          update(stockpatch).then((res) => {
            this.handleChoose(this.current_page);
            this.$message({
              message: "库存更新成功！",
              type: "success"
            })
          })
        }
      },

      // 商品导入
      importFile() {
        this.docImportDrawer = true
      },
      // 数据导入-上传Excel
      async importFileChange(file, fileList) {
        this.importForm.fileList = fileList // 检验上传文件是否为空
      },
      // 确定上传
      saveUpload() {
        if(!this.importForm.fileList.length) {
          this.$message.error("请先上传文件")
          return
        }
        this.isLoadingDialog = true
        const params = new FormData()
        params.append("saleStockFile", this.importForm.fileList[0].raw)
        let token = localStorage.getItem("token")
        axios.post("/api/goods_skus/saleStockImport", params, {
          headers: {
            Authorization: `Bearer ${token}`
          }
        }).then((res) => {
          if (res.status === 200) {
            this.$message.success("导入成功")
            this.current_page = 1
            this.getList()
            this.commitloading = false
            this.docImportDrawer = false
          } else {
            this.isLoadingDialog = false
          }
        }).catch(() => {
          this.isLoadingDialog = false
        })
      },

      // 数据导入-获取Excel模板地址
      getExcelTemplatePath() {
        this.$requestInternet.get("/api/xxx").then((res) => {
          this.excelTemplatePath = res
        })
      },
      // 表格导出
      derivation() {
        window.open("/goods_skus/export?exportType=" + this.value)
      },
      //参考价格弹出框确认修改请求
      referencePriceRequest() {
        let reference_priceData = {
          updateField: this.updateField,
          reference_price: this.reference_price
        }
        singleUpdate(this.publicId, reference_priceData).then((res) => {
          this.editPriceId = ''
          this.dialogVisible3 = false
          this.$message({
            message: "参考售价修改成功！",
            type: "success"
          })
        })
      },
      cancelGoal() {
        this.dialogVisible5 = false
        this.updateField = "goal_rate"
        this.editGoalId = this.publicId
        this.noRow.goal_rate = this.lastVal
      },
      confirmGoal() {
        let data = {
          updateField: 'goal_rate',
          goal_rate: this.nowVal
        }
        singleUpdate(this.publicId, data).then((res) => {
          this.editGoalId = ''
          this.dialogVisible5 = false
          this.$message({
            message: "目标去化率修改成功！",
            type: "success"
          })
        })
      },
      // 获取商品种类
      getgoodsType() {
        let param = {
          per_page: 99999
        }
        goods_types(param).then((res) => {
          this.treeList = JSON.parse(JSON.stringify(res.data.data).replace(/name/g, "label"))
        })
      },
      petchEditStock() {
        this.showUpdate = true
      },
      commitPetchStock() {
        this.commitLoading = true
        let skus = []
        this.chooseList.forEach((item) => {
          skus.push({
            id: item.id,
            sale_stock: item.sale_stock
          })
        })
        let params = {
          updateType: 'saleStock',
          skus: skus
        }
        updateSaleStock(params).then((res) => {
          this.commitLoading = false
          this.$refs.multipleTable.clearSelection()
          this.$message({ message: '更新成功', type: "success" })
          this.getList()
          this.showUpdate = false
        }).catch(() => {
          this.commitLoading = false
        })
      },
      openSaleEdit(row, index) {
        this.$set(this.tableData[index], 'edit', true)
        this.$set(this.tableData[index], 'sale_stock_old', row.sale_stock)
      },
      cancelEdit(row, index) {
        this.$set(this.tableData[index], 'sale_stock', row.sale_stock_old)
        this.$set(this.tableData[index], 'edit', false)
      },
      confirmEdit(row, index) {
        let params = {
          updateType: 'saleStock',
          skus: [{
            id: row.id,
            sale_stock: row.sale_stock
          }]
        }
        updateSaleStock(params).then((res) => {
          this.$message({ message: '更新成功', type: "success" })
          this.$set(this.tableData[index], 'edit', false)
        })
      },
      normalizer(node) {
        if ((!node.children || (node.children && node.children.length == 0)) && node.level == 1) {
          node.isDisabled = true
        }
        return node
      },
      parseLabel(node) {
        console.log(node)
        let text = ''
        text += node.parentNode ? node.parentNode.label + ' / ' : ''
        text += node.raw ? node.raw.label : ''
        return text
      }
    },
    watch: {
      $route(to, from) {
        window.location.reload() //监测到路由发生跳转时刷新一次页面
      }
    },
    mounted() {
      this.getList()
      this.getStockInfo()
      this.getgoodsType()
    }
}
</script>

<style lang="scss" scoped>
  .table {
    margin-top: 20px;
    position: relative;
  }
  .btn {
    float: right;
  }
  .flex{
    display: flex;
    align-items: center;
  }
  .goodBox{
    .Img {
      width: 50px;
      height: 50px;
      margin-right: 12px;
      border-radius: 4px;
    }
    .tit{
      color: #000;
      font-size: 13px;
    }
  }
  
  .confirmbtn {
    width: 114px;
    height: 44px;
    border-radius: 3px;
    margin-top: 21px;
    margin-bottom: 8px;
  }
  .import-right {
    margin-top: 30px;
    a {
      color: #409EFF;
    }
  }
  ::v-deep .btn11 {
    padding: 0;
    width: 14px;
    height: 14px;
  }
  ::v-deep .btn11 img {
    width: 100%;
    height: 100%;
  }
  .page {
    margin-top: 20px;
  }
  .searchBox{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    white-space: nowrap;
    .row{
      font-size: 14px;
      margin-bottom: 20px;
      margin-right: 15px;
      display: flex;
      align-items: center;
    }
  }
  .titBox{
    display: flex;
    align-items: center;
  }
  .red{
    color: #f00
  }
</style>
