<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>商品列表
    </h2>
    <div class="m-core">
      <el-button class="btn-primary"
                 @click="onShopOperation('create')"
                 v-permission="'/shopOperation'">添加</el-button>
      <el-upload v-permission="'import/goods'"
                 style="display: inline-block; margin: 0 10px;"
                 action="/api-web/import/goods"
                 :show-file-list="false"
                 :before-upload="beforeUpload"
                 accept=".xlsx,.xls"
                 :headers="headers"
                 :on-error="handleError"
                 :on-success="handleSuccess">
        <el-button class="btn-primary">商品导入</el-button>
      </el-upload>
      <el-button class="btn-primary"
                 @click="onDownload"
                 v-permission="'import/downloadTemplate'">下载模板</el-button>
      <el-button class="btn-primary"
                 permission="'goods/update'"
                 @click="onShopComAdd">添加组合商品</el-button>
      <!-- 搜索类型 -->
      <el-form :inline="true"
               class="searchForm"
               v-model.trim="searchForm">
        <el-form-item>
          <el-input v-model.trim="searchForm.search"
                    placeholder="商品编号/货号/商品名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.type"
                     clearable
                     placeholder="商品类型">
            <el-option v-for="(item, index) in goodsType"
                       :key="index"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.goodsCategoryId"
                     clearable
                     placeholder="商品分类">
            <el-option v-for="(item, index) in categoryList"
                       :key="index"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.status"
                     clearable
                     placeholder="是否是上架">
            <el-option label="是"
                       value="1"></el-option>
            <el-option label="否"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.groupGoods"
                     clearable
                     placeholder="是否是组合商品">
            <el-option label="是"
                       value="1"></el-option>
            <el-option label="否"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.clientShow"
                     clearable
                     placeholder="学生端是否是展示">
            <el-option label="是"
                       value="1"></el-option>
            <el-option label="否"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.educationalShow"
                     clearable
                     placeholder="教务端是否是展示">
            <el-option label="是"
                       value="1"></el-option>
            <el-option label="否"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.musicGroupShow"
                     clearable
                     placeholder="乐团是否是展示">
            <el-option label="是"
                       value="1"></el-option>
            <el-option label="否"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-date-picker v-model.trim="orderDate" style="width:410px;" type="daterange" value-format="yyyy-MM-dd"
            @change="searchOrderDate" range-separator="至" :picker-options="{ firstDayOfWeek: 1 }" start-placeholder="开始日期"
            end-placeholder="结束日期"></el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button type="danger"
                     @click="onSearch">搜索</el-button>
          <el-button type="primary"
                     @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table :data='tableList'
                  :header-cell-style="{background:'#EDEEF0',color:'#444'}">
          <el-table-column align='center'
                           prop="id"
                           label="商品编号">
          </el-table-column>
          <el-table-column align='center'
                           prop="sn"
                           label="货号">
          </el-table-column>
          <el-table-column align='center'
                           prop="brand"
                           label="品牌">
          </el-table-column>
          <el-table-column align='center'
                           prop="name"
                           label="商品名称">
          </el-table-column>
          <el-table-column align='center'
                           label="是否组合商品">
            <template slot-scope="scope">
              {{ scope.row.complementGoodsIdList ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="学员是否展示">
            <template slot-scope="scope">
              {{ scope.row.clientShow ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="教务端是否展示">
            <template slot-scope="scope">
              {{ scope.row.educationalShow ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="乐团是否展示">
            <template slot-scope="scope">
              {{ scope.row.musicGroupShow ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="是否库存预警">
            <template slot-scope="scope">
              <span v-if="!scope.row.complementGoodsIdList">
                {{ scope.row.stockWarning ? '是' : '否' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="商品类型">
            <template slot-scope="scope">
              {{ scope.row.type | shopType }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="goodsCategoryName"
                           label="商品分类">
          </el-table-column>
          <el-table-column align='center'
                           prop="specification"
                           label="具体型号">
            <template slot-scope="scope">
              <span style="max-height: 64px; display: block;">{{ scope.row.specification }}</span>
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="stockCount"
                           label="内部库存">
            <template slot-scope="scope">
              <!-- 先判断是否是组合商品 -->
              <span v-if="scope.row.complementGoodsIdList">
                {{ scope.row.stockCount ? scope.row.stockCount : '' }}
              </span>
              <span v-else>{{ scope.row.stockCount }}</span>
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="taxStockCount"
                           label="税务库存">
            <template slot-scope="scope">
              <!-- 先判断是否是组合商品 -->
              <span v-if="scope.row.complementGoodsIdList">
                {{ scope.row.taxStockCount ? scope.row.taxStockCount : '' }}
              </span>
              <span v-else>{{ scope.row.taxStockCount }}</span>
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="stockType"
                           label="库存类型">
            <template slot-scope="scope">
              {{ scope.row.stockType | stockTypeStatus }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="marketPrice"
                           label="市场价(元)">
            <template slot-scope="scope">
              {{scope.row.marketPrice|moneyFormat}}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="marketPrice"
                           label="零售价(元)">
            <template slot-scope="scope">
              {{scope.row.discountPrice|moneyFormat}}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="groupPurchasePrice"
                           label="商品团购价(元)">
            <template slot-scope="scope">
              {{scope.row.groupPurchasePrice|moneyFormat}}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           cell-style="padding: 0"
                           label="商品缩略图">
            <template slot-scope="scope">
              <img class="shopImage"
                   :src="scope.row.image"
                   alt=""
                   srcset="">
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="商品描述">
            <template slot-scope="scope">
              <Tooltip :content="scope.row.brief" />
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="商品详情">
            <template slot-scope="scope">
              <Tooltip :content="scope.row.desc" />
            </template>
          </el-table-column>
          <el-table-column align='center'
                           width="180px"
                           label="操作"
                           fixed="right">
            <template slot-scope="scope">
              <!-- 组合商品没有进货清单按钮 v-permission="'/purchaseLlist'" -->
              <el-button v-if="!scope.row.complementGoodsIdList && permission('/purchaseLlist')"
                         @click="onPurchaseList(scope.row)"
                         type="text">进货清单</el-button>
              <!-- <el-popconfirm title="你是否上架该商品？"
                             @confirm="onUpdate(scope.row)"
                             v-if="scope.row.status == 0"
                             v-permission="'goods/updateGoodsStatus'">
                <el-button slot="reference"
                           type="text">上架</el-button>
              </el-popconfirm> -->
              <!-- v-permission="'goods/updateGoodsStatus'" -->
              <el-button v-if="scope.row.status == 0 && permission('goods/updateGoodsStatus')"
                         @click="onUpdate(scope.row, 0)"
                         type="text">上架</el-button>
              <el-button v-if="scope.row.status == 1 && permission('goods/updateGoodsStatus')"
                         @click="onUpdate(scope.row, 1)"
                         type="text">下架</el-button>
              <!-- <el-popconfirm title="你是否下架该商品？"
                             @confirm="onUpdate(scope.row)"
                             v-if="scope.row.status == 1"
                             v-permission="'goods/updateGoodsStatus'">
                <el-button slot="reference"
                           type="text">下架</el-button>
              </el-popconfirm> -->
              <!-- {{ scope.row.status }} -->
              <!-- v-permission="scope.row.complementGoodsIdList ? 'goods/update' : '/shopOperation'" -->
              <el-button v-if="scope.row.status == 0 && permission(scope.row.complementGoodsIdList ? 'goods/update' : '/shopOperation')"
                         @click="onShopOperation('update', scope.row)"
                         type="text">修改</el-button>
              <el-button v-if="scope.row.status == 1 && permission(scope.row.complementGoodsIdList ? 'goods/update' : '/shopOperation')"
                         @click="onShopOperation('look', scope.row)"
                         type="text">查看</el-button>
              <!-- <el-button v-if="scope.row.status == 0"
                         v-permission="'goods/del'"
                         @click="onDelete(scope.row)"
                         type="text">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="pageInfo.total"
                    :page.sync="pageInfo.page"
                    :limit.sync="pageInfo.limit"
                    :page-sizes="pageInfo.page_size"
                    @pagination="getList" />
      </div>
    </div>

    <el-dialog :title="addString[addType] + '组合商品'"
               destroy-on-close
               :visible.sync="routeShopStatus"
               @close="onFormClose('ruleForm')"
               width="600px">
      <el-form :model="form"
               :rules="rules"
               ref="ruleForm">
        <el-form-item label="商品名称"
                      prop="name"
                      :label-width="formLabelWidth">
          <el-input placeholder="请输入商品名称"
                    type="text"
                    :disabled="addDisabled"
                    v-model.trim="form.name"></el-input>
        </el-form-item>
        <el-form-item label="货号"
                      prop="sn"
                      :label-width="formLabelWidth">
          <el-input placeholder="请输入货号"
                    type="text"
                    :disabled="addDisabled"
                    v-model.trim="form.sn"></el-input>
        </el-form-item>
        <el-form-item label="品牌"
                      prop="brand"
                      :label-width="formLabelWidth">
          <el-input v-model.trim="form.brand"
                    :disabled="addDisabled"
                    placeholder="请输入品牌"></el-input>
        </el-form-item>
        <el-form-item label="商品类型"
                      prop="type"
                      :label-width="formLabelWidth">
          <el-select v-model.trim="form.type"
                      :disabled="addDisabled"
                     placeholder="请选择商品类型">
            <el-option v-for="(item, index) in goodsType"
                       :key="index"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类"
                      prop="goodsCategoryId"
                      :label-width="formLabelWidth">
          <el-select v-model.trim="form.goodsCategoryId"
                     placeholder="请选择商品分类"
                     :disabled="addDisabled"
                     filterable>
            <el-option v-for="item in categoryList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品型号"
                      prop="specification"
                      :label-width="formLabelWidth">
          <el-input v-model.trim="form.specification" :disabled="addDisabled"
                    placeholder="请输入商品型号"></el-input>
        </el-form-item>

        <div v-for="(goodsList, index) in form.goodsList"
             :key="index">
          <el-form-item :label="'商品' + (index + 1)"
                        :label-width="formLabelWidth"
                        style="display: inline-block;"
                        :prop="'goodsList.' + index + '.id'"
                        :rules="[{ required: true, message: '请选择商品', trigger: 'change' }]">
            <el-select v-model.trim="goodsList.id"
                       @change="onGoodsChange"
                       filterable
                       :disabled="addDisabled"
                       placeholder="请选择商品">
              <el-option v-for="(item,index) in selectGoodsList"
                         :key="index"
                         :disabled="item.disabled"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <div v-if="!addDisabled" style="display: inline-block;">
            <el-button icon="el-icon-minus"
                      v-if="form.goodsList.length > 1"
                      @click.prevent="removeGoodsList(goodsList)"
                      circle></el-button>
            <el-button icon="el-icon-plus"
                      @click.prevent="addGoodsList"
                      circle
                      style="margin-left: 5px;"></el-button>
          </div>
        </div>

        <el-form-item label="市场价"
                      prop="marketPrice"
                      :label-width="formLabelWidth">
          <el-input type="number"
                    placeholder="请输入市场价"
                    :disabled="addDisabled"
                    @mousewheel.native.prevent
                    v-model.trim="form.marketPrice"></el-input>
        </el-form-item>
        <el-form-item label="零售价"
                      prop="discountPrice"
                      :label-width="formLabelWidth">
          <el-input type="number"
                    placeholder="请输入零售价"
                    :disabled="addDisabled"
                    @mousewheel.native.prevent
                    v-model.trim="form.discountPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品团购价"
                      prop="groupPurchasePrice"
                      :label-width="formLabelWidth">
          <el-input type="number"
                    placeholder="请输入商品团购价"
                    :disabled="addDisabled"
                    @mousewheel.native.prevent
                    v-model.trim="form.groupPurchasePrice"></el-input>
        </el-form-item>
        <el-form-item label="学员是否展示"
                      prop="clientShow"
                      :label-width="formLabelWidth">
          <el-select v-model="form.clientShow"
                     placeholder="请选择学员是否展示">
            <el-option label="是"
                       :value="1"></el-option>
            <el-option label="否"
                       :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教务端是否展示"
                      prop="educationalShow"
                      :label-width="formLabelWidth">
          <el-select v-model="form.educationalShow"
                     placeholder="请选择教务端是否展示">
            <el-option label="是"
                       :value="1"></el-option>
            <el-option label="否"
                       :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="乐团是否展示"
                      prop="musicGroupShow"
                      :label-width="formLabelWidth">
          <el-select v-model="form.musicGroupShow"
                     placeholder="请选择乐团是否展示">
            <el-option label="是"
                       :value="1"></el-option>
            <el-option label="否"
                       :value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否库存预警" prop="stockWarning" :label-width="formLabelWidth">
          <el-select v-model="form.stockWarning" placeholder="请选择是否库存预警">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="商品图片"
                      prop="image"
                      :label-width="formLabelWidth">
          <upload v-model="form.image"
                  :imageWidthM='400'
                  :disabled="addDisabled"
                  :imageHeightM='400'></upload>
        </el-form-item>

        <el-form-item label="商品描述"
                      prop="brief"
                      :label-width="formLabelWidth">
          <el-input type="textarea" :disabled="addDisabled"
                    v-model.trim="form.brief"></el-input>
        </el-form-item>
        <el-form-item label="商品详情"
                      prop="desc"
                      :label-width="formLabelWidth">
          <el-input type="textarea" :disabled="addDisabled"
                    v-model.trim="form.desc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" v-if="!addDisabled"
            class="dialog-footer">
        <el-button @click="routeShopStatus = false">取 消</el-button>
        <el-button @click="onShopSubmit('ruleForm')"
                   type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pagination from '@/components/Pagination/index'
import Upload from '@/components/Upload/index'
import {
  categoryListTree,
  goodsQuery,
  goodsAdd,
  goodsUpdate,
  goodsDelete,
  updateGoodsStatus
} from '@/api/businessManager'
import cleanDeep from 'clean-deep'
import store from '@/store'
import Tooltip from '@/components/Tooltip/index'
import {
  Export
} from '@/utils/downLoadFile'
import {
  getToken
} from "@/utils/auth";
import {
  goodsType
} from '@/utils/searchArray'
import load from '@/utils/loading'
import { permission } from "@/utils/directivePage";
let validPrice = (rule, value, callback) => {
  if (value == '' && typeof value == 'string' || value == null) {
    callback(new Error('请输入金额'))
  } else if (value < 0) {
    callback(new Error('输入金额必须大于或等于0'))
  } else if (value >= 100000) {
    callback(new Error('输入金额必须小于100000'))
  } else {
    callback()
  }
}
let validStock = (rule, value, callback) => {
  if (value == '' && typeof value == 'string' || value == null) {
    callback(new Error('请输入库存'))
  } else if (value < 0) {
    callback(new Error('库存数量必须大于或等于0'))
  } else {
    callback()
  }
}
export default {
  components: {
    pagination,
    Tooltip,
    Upload
  },
  name: 'shopList',
  data () {
    return {
      goodsType: goodsType,
      categoryList: [],
      goodsLoading: false,
      organId: null,
      orderDate: null,
      searchForm: {
        search: null,
        groupGoods: null,
        type: null,
        status: null,
        goodsCategoryId: null,
        startTime: null,
        endTime: null,
        status: null,
        clientShow: null,
        educationalShow: null,
        musicGroupShow: null
      },
      headers: {
        Authorization: getToken()
      },
      searchLsit: [],
      tableList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      formLabelWidth: "120px",
      routeShopStatus: false,
      addType: 'create',
      addString: {
        'create': '添加',
        'update': '修改',
        'look': '查看',
      },
      addDisabled: false,
      form: {
        sn: null,
        brand: null,
        supplyChannel: null,
        name: null,
        type: null,
        goodsCategoryId: null,
        specification: null,
        marketPrice: null,
        discountPrice: null,
        groupPurchasePrice: null,
        clientShow: null,
        educationalShow: null,
        musicGroupShow: null,
        stockWarning: null,
        image: null,
        complementGoodsIdList: null,
        goodsList: [{
          id: null
        }],
        brief: null,
        desc: null
      },
      goodsTree: [], // 选择商品列表
      rules: {
        sn: [{
          required: true,
          message: '请输入商品货号',
          trigger: 'blur'
        }],
        brand: [{
          required: true,
          message: '请输入品牌',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 30,
          message: '长度在 2 到 30 个字符',
          trigger: 'blur'
        }
        ],
        supplyChannel: [{
          required: true,
          message: '请输入备查货号',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入商品名称',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 30,
          message: '长度在 2 到 30 个字符',
          trigger: 'blur'
        }
        ],
        type: [{
          required: true,
          message: '请选择商品分类',
          trigger: 'change'
        }],
        goodsCategoryId: [{
          required: true,
          message: '请选择商品类型',
          trigger: 'change'
        }],
        specification: [{
          required: true,
          message: '请输入商品型号',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 30,
          message: '长度在 2 到 30 个字符',
          trigger: 'blur'
        }
        ],
        marketPrice: [{
          required: true,
          validator: validPrice,
          trigger: 'blur'
        }],
        discountPrice: [{
          required: true,
          validator: validPrice,
          trigger: 'blur'
        }],
        groupPurchasePrice: [{
          required: true,
          validator: validPrice,
          trigger: 'blur'
        }],
        clientShow: [{
          required: true,
          message: '请选择学员是否展示',
          trigger: 'change'
        }],
        educationalShow: [{
          required: true,
          message: '请选择教务端是否展示',
          trigger: 'change'
        }],
        musicGroupShow: [{
          required: true,
          message: '请选择乐团是否展示',
          trigger: 'change'
        }],
        stockWarning: [{
          required: true,
          message: '请选择是否库存预警',
          trigger: 'change'
        }],
        image: [{
          required: true,
          message: '请选择图片',
          trigger: 'blur'
        }],
        brief: [{
          required: true,
          message: '请输入商品描述',
          trigger: 'blur'
        }],
        desc: [{
          required: true,
          message: '请输入商品详情',
          trigger: 'blur'
        }]
      },
      selectGoodsList: []
    }
  },
  created () {
    this.init()
  },
  activated () {
    this.init()
  },
  mounted () {

  },
  methods: {
    permission (str) {
      return permission(str);
    },
    init () {
      if (this.$route.query.searchForm) {
        this.$route.query.searchForm instanceof Object ? this.searchForm = this.$route.query.searchForm : this.searchForm =
          JSON.parse(this.$route.query.searchForm);
      }
      if (this.$route.query.pageInfo) {
        this.$route.query.pageInfo instanceof Object ? this.pageInfo = this.$route.query.pageInfo : this.pageInfo =
          JSON.parse(this.$route.query.pageInfo);
      }
      this.getList()
      this.getCategory()
    },
    getCategory () {
      let params = {
        delFlag: 0,
        rows: 9999
      }
      categoryListTree(params).then(res => {
        let result = res.data
        if (res.code == 200) {
          let tempArray = []
          result.rows.forEach(row => {
            tempArray.push({
              label: row.name,
              value: row.id
            })
          })
          this.categoryList = tempArray
        }
      })
    },
    async onUpdate (row, type) {
      let title = type == 1 ? '你是否下架该商品？' : '你是否上架该商品？'
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await updateGoodsStatus({
          goodsId: row.id,
          status: row.status ? 0 : 1
        }).then(res => {
          this.messageTips(row.status ? '下架' : '上架', res)
        })
      }).catch(() => {
      });
    },
    onPurchaseList (row) {
      let pageInfo = JSON.stringify(this.pageInfo)
      let search = JSON.stringify(this.searchForm)
      this.$router.push({
        path: '/shopManager/purchaseLlist',
        query: {
          name: row.name,
          goodsId: row.id,
          pageInfo,
          search
        }
      })
    },
    onDelete (row) {
      this.$confirm('您确定删除该商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        goodsDelete(row.id).then(res => {
          this.messageTips('删除', res)
        })
      }).catch(() => { })

    },
    searchOrderDate (value) {
      if (value) {
        this.searchForm.startTime = value[0];
        this.searchForm.endTime = value[1];
      } else {
        this.searchForm.startTime = null;
        this.searchForm.endTime = null;
      }
    },
    messageTips (title, res) {
      if (res.code == 200) {
        this.$message.success(title + '成功')
        this.typeStatus = false
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
    },
    getList () {
      let params = Object.assign({}, this.searchForm)
      params.organId = this.organId
      params.rows = this.pageInfo.limit
      params.page = this.pageInfo.page
      goodsQuery(params).then(res => {
        if (res.code == 200 && res.data) {
          this.tableList = res.data.rows
          this.pageInfo.total = res.data.total
        }
      })
    },
    getAllGoodsList () { // 获取所有商品
      goodsQuery({
        rows: 9999,
        page: 1,
        groupGoods: 0,
        status: 1
      }).then(res => {
        if (res.code == 200 && res.data) {
          this.selectGoodsList = res.data.rows
        }
      })
    },
    onSearch () {
      this.pageInfo.page = 1
      this.getList()
    },
    onReset () { // 重置
      this.searchForm = {
        search: null,
        groupGoods: null,
        type: null,
        status: null,
        goodsCategoryId: null,
        startTime: null,
        endTime: null
      }
      this.getList()
    },
    onShopComAdd () {
      this.form = {
        sn: null,
        brand: null,
        supplyChannel: null,
        name: null,
        type: null,
        goodsCategoryId: null,
        specification: null,
        marketPrice: null,
        discountPrice: null,
        groupPurchasePrice: null,
        clientShow: null,
        educationalShow: null,
        musicGroupShow: null,
        stockWarning: null,
        image: null,
        complementGoodsIdList: null,
        goodsList: [{
          id: null
        }],
        brief: null,
        desc: null
      }
      this.onValidGoodsStatus()
      this.routeShopStatus = true
      this.addType = 'create'
      this.addDisabled = false
      if (this.$refs['ruleForm']) {
        this.$refs['ruleForm'].resetFields();
      }
      // 获取所有商品
      this.getAllGoodsList()
    },
    onValidGoodsStatus () { // 更新商品选择状态
      let goodsList = this.form.goodsList
      let tempIds = []
      goodsList.forEach(item => {
        tempIds.push(item.id)
      })
      this.selectGoodsList.forEach(item => {
        item.disabled = false
        if (tempIds.includes(item.id)) {
          item.disabled = true
        }
      })
    },
    onShopOperation (type, row) { // 添加或修改
      let params = {
        type: type
      }
      if (row) {
        params.id = row.id
      }
      let pageInfo = JSON.stringify(this.pageInfo)
      let searchForm = JSON.stringify(this.searchForm)
      let paramInfo = JSON.stringify(params)
      this.addType = type
      this.addDisabled = type == 'look' ? true : false
      // 判断是否是修改组合商品
      if ((type == 'update' || type == 'look') && row.complementGoodsIdList) {
        this.routeShopStatus = true

        let form = this.form
        for (let i in form) {
          form[i] = row[i]
        }
        let ids = row.complementGoodsIdList.split(',')
        let goodsList = []
        ids.forEach(item => {
          goodsList.push({
            id: Number(item)
          })
        })
        form.goodsList = goodsList
        form.id = row.id

        this.onValidGoodsStatus()
        this.getAllGoodsList()
      } else {
        this.$router.push({
          path: '/shopManager/shopOperation',
          query: {
            searchForm,
            paramInfo,
            pageInfo
          }
        })
      }
    },
    beforeUpload (file) {
      // console.log(file.type)
      // const isJPG = file.type === '.xlsx' || file.type === '.xls';
      // // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // return isJPG;
      // this.goodsLoading = true
      load.startLoading()
    },
    handleSuccess (response, file, fileList) { // 导入商品
      // 报表导出
      load.endLoading()
      if (response.code == 200) {
        this.$message.success('导入成功')
        this.getList()
      } else {
        this.$message.error(response.msg)
      }
    },
    handleError (err, file, fileList) {
      load.endLoading()
      console.log(err, file, fileList)
    },
    onDownload () { // 下载模板
      // // 报表导出
      Export(this, {
        url: "/api-web/import/downloadTemplate",
        params: {
          templateType: 'GOODS'
        },
        fileName: '商品导入模板.xlsx'
      })
    },
    onFormClose (formName) {
      // 关闭弹窗重置验证
      this.$refs[formName].resetFields();
    },
    onGoodsChange () {
      let selectGoodsList = this.selectGoodsList
      let goodsList = this.form.goodsList
      let tempIds = []
      goodsList.forEach(item => {
        if (item.id) {
          tempIds.push(item.id)
        }
      })
      selectGoodsList.forEach(item => {
        if (tempIds.includes(item.id)) {
          item.disabled = true
        } else {
          item.disabled = false
        }
      })

      this.calcPrice()
    },
    removeGoodsList (item) {
      let tempId = item.id
      let selectGoodsList = this.selectGoodsList
      selectGoodsList.forEach(item => {
        if (item.id == tempId) {
          item.disabled = false
        }
      })

      const index = this.form.goodsList.indexOf(item)
      if (index !== -1) {
        this.form.goodsList.splice(index, 1)
      }

      this.calcPrice()
    },
    addGoodsList () {
      this.form.goodsList.push({
        id: null
      })
    },
    onShopSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = Object.assign({}, this.form)
          let tempIds = []
          form.goodsList.forEach(item => {
            if (item.id) {
              tempIds.push(item.id)
            }
          })
          form.complementGoodsIdList = tempIds.join(',')
          form.goodsList = null
          if (this.addType == 'create') {
            if (this.form.id) { // 判断有没有Id，如果有则删除
              delete this.form.id
            }
            form.status = 'NO' // 默认上架
            goodsAdd(cleanDeep(form)).then(res => {
              this.messageTips('添加', res)
            })
          } else if(this.addType == 'update') {
            goodsUpdate(cleanDeep(form)).then(res => {
              this.messageTips('修改', res)
            })
          }
        } else {
          return false
        }
      })
    },
    messageTips (title, res) {
      if (res.code == 200) {
        this.$message.success(title + '成功')
        this.getList()
        this.routeShopStatus = false
      } else {
        this.$message.error(res.msg)
      }
    },
    calcPrice () {
      let selectGoodsList = this.selectGoodsList
      let form = this.form
      let goodsList = form.goodsList
      let tempIds = []
      goodsList.forEach(item => {
        if (item.id) {
          tempIds.push(item.id)
        }
      })
      let groupPurchasePrice = 0,
        marketPrice = 0,
        discountPrice = 0
      selectGoodsList.forEach(item => {
        if (tempIds.includes(item.id)) {
          groupPurchasePrice += item.groupPurchasePrice
          marketPrice += item.marketPrice
          discountPrice += item.discountPrice
        }
      })

      form.groupPurchasePrice = Number(groupPurchasePrice.toFixed(2))
      form.discountPrice = Number(discountPrice.toFixed(2))
      form.marketPrice = Number(marketPrice.toFixed(2))
    }
  }
}
</script>
<style lang="scss">
.shopImage {
  width: 60px;
  height: 60px;
}
.shopDesc {
  max-height: 70px;
  overflow: hidden;
}
</style>
