<template>
  <div class="app-container" style="padding: 0 20px 20px 20px;">

    <el-menu :default-active="moduleId+''" class="el-menu-demo" mode="horizontal">
      <el-menu-item v-if="moduleId===1 && modules && modules.firstModulesName" index="1">添加【{{ modules.firstModulesName }}】</el-menu-item>
      <el-menu-item v-if="moduleId===2 && modules && modules.secondModulesName" index="2">添加【{{ modules.secondModulesName }}】</el-menu-item>
      <el-menu-item v-if="moduleId===3 && modules && modules.thirdModulesName" index="3">添加【{{ modules.thirdModulesName }}】</el-menu-item>
    </el-menu>

    <div class="filter-container" style="margin-top:20px;">
      <el-form class="demo-form-inline goods-list">

        <el-form-item label="商品ID:" style="width:225px;float: left;margin-bottom: 8px;">
          <el-input v-model="listQuery.id" type="number" placeholder="请输入商品ID" maxlength="30" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="商品名称:" style="width:240px;float: left;">
          <el-input v-model="listQuery.productName" placeholder="请输入商品名称" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="供应商名称:" style="width:250px;float: left;">
          <el-input v-model="listQuery.shopName" placeholder="请输入供应商名称" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="商品分类:" style="width:200px;float: left;">
          <el-select v-model="listQuery.classifyID" placeholder="商品分类" clearable style="width: 110px" class="filter-item" value="" @change="handleFilter">
            <template v-for="item in classify">
              <el-option v-if="item.status*1 === 1" :key="item.id" :label="item.classifyName" :value="item.id" />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item style="width:100px;float: left;">
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        </el-form-item>
        <el-form-item style="width:130px;float: left;">
          <el-button class="filter-item" type="primary" icon="el-icon-check" @click="confirmChoose()">确定选择</el-button>
        </el-form-item>
        <el-form-item style="width:130px;float: left;">
          <el-button class="filter-item" type="primary" icon="el-icon-close" @click="toggleSelection()">取消选择</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      style="width:100%;margin-top:20px;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column label="商品ID" align="center" prop="id" width="70px" />
      <el-table-column label="商品图片" align="center" prop="mainImage">
        <template slot-scope="{row}">
          <img :src="row.mainImage" alt="" width="50">
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName" min-width="200px" />
      <el-table-column label="供应商" align="center" prop="shopName" min-width="120px" />
      <el-table-column label="市场价" align="center" prop="normalPrice" />
      <el-table-column label="成本价" align="center" prop="costPrice" />
      <el-table-column label="售价" align="center" prop="retailPrice" />
      <el-table-column label="起订量" align="center" prop="minBuyNumber" />
      <el-table-column label="商品分类" align="center" prop="productClassifyName" />
    </el-table>

    <pagination v-show="total>20" :total="total" :page.sync="listQuery.index" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <template>
      <el-backtop style="right: 40px; bottom: 40px;">
        <i class="el-icon-upload2" />
      </el-backtop>
    </template>
  </div>
</template>

<script>
import { getAddList, getModule, saveAddList } from '@/api/goods'
import Pagination from '@/components/Pagination'
export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      modules: null,
      classify: null,
      listLoading: true,
      total: 0,
      listQuery: {
        index: 1,
        pageSize: 20,
        organizeID: this.$store.getters.organizeID,
        id: '',
        productName: '',
        shopName: '',
        classifyID: ''
      },
      multipleSelection: []
    }
  },
  computed: {
    moduleId: function() {
      return window.location.href.split('/').reverse()[0] * 1
    },
    organizeID() {
      return this.$store.getters.organizeID
    }
  },
  created() {
    this.getModuleType()
    this.fetchData()
  },
  methods: {
    getModuleType() {
      getModule({ organizeID: this.$store.getters.organizeID }).then(response => {
        this.modules = response.data[0]
      })
    },
    fetchData() {
      this.listLoading = true
      let params = {}
      switch (this.moduleId) {
        case 1:
          params = Object.assign({ preferredProduct: 1 }, this.listQuery)
          break
        case 2:
          params = Object.assign({ preferentialProduct: 1 }, this.listQuery)
          break
        case 3:
          params = Object.assign({ commonlyProduct: 1 }, this.listQuery)
          break
      }
      getAddList(params).then(response => {
        const { productsPage, listByEffective } = response.data
        this.list = productsPage.results
        this.total = productsPage.totalRecord
        this.classify = listByEffective
        this.listLoading = false
      })
    },
    handleFilter() {
      this.fetchData()
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
        this.backToParentPath()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    confirmChoose() {
      console.log(this.multipleSelection)
      if (this.multipleSelection.length === 0) {
        this.$message({ message: '没有选择商品哦，请选择商品!', type: 'warning', center: true })
        return
      }
      const itemsList = []
      this.multipleSelection.map(item => {
        itemsList.push(item.id)
      })
      saveAddList({ itemsList: JSON.stringify(itemsList), organizeID: this.$store.getters.organizeID, modules: this.moduleId }).then(response => {
        this.$notify({
          title: response.code * 1 === 1 ? 'Success' : 'Error',
          message: response.code * 1 === 1 ? '添加成功' : response.msg,
          type: response.code * 1 === 1 ? 'success' : 'error',
          duration: 2000
        })
        this.backToParentPath()
      }).catch(() => {
        this.fetchData()
      })
    },
    backToParentPath() {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        let parentPath = ''
        switch (this.moduleId) {
          case 1:
            parentPath = '/goods/list/preferred'
            break
          case 2:
            parentPath = '/goods/list/preferential'
            break
          case 3:
            parentPath = '/goods/list/commonly'
            break
        }
        if (parentPath) {
          this.$nextTick(() => {
            this.$router.replace({ path: parentPath })
          })
        }
      })
    }
  }
}
</script>

<style scoped>
  i[type=success]{
    color:#67C23A;
  }
  .goods-list .el-form-item{
  margin-bottom: 8px;
}
</style>
