<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:190px;float: left;margin-bottom: 8px;">
          <el-input v-model="listQuery.id" type="number" placeholder="请输入商品ID" oninput="if(value.length>9)value=value.slice(0,9)" style="width: 120px;" 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">
        <template slot-scope="{row}">
          ¥{{ row.normalPrice | toThousandFloatFilter }}
        </template>
      </el-table-column>
      <el-table-column label="成本价" align="center">
        <template slot-scope="{row}">
          ¥{{ row.costPrice | toThousandFloatFilter }}
        </template>
      </el-table-column>
      <el-table-column label="售价" align="center">
        <template slot-scope="{row}">
          <template v-if="row.ladderPriceFlag*1===1">
            <div v-for="(item, index) in row.ladderShownList" :key="row.id+'list_ladder_pri'+index">
              ¥{{ item.price | toThousandFloatFilter }}</div>
          </template>
          <template v-else>¥{{ row.retailPrice | toThousandFloatFilter }}</template>
        </template>
      </el-table-column>
      <el-table-column label="起订量" align="center" width="70">
        <template slot-scope="{row}">
          <template v-if="row.ladderPriceFlag*1===1">
            <div v-for="(item, index) in row.ladderShownList" :key="row.id+'list_ladder_pri'+index">{{ item.number }}</div>
          </template>
          <template v-else>{{ row.minBuyNumber }}</template>
        </template>
      </el-table-column>
      <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: 10,
        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
        this.list.map(row => {
          row.ladderShownList = []
          if (row.ladderPriceFlag * 1 === 1 && row.ladderPriceList != null) {
            for (let i = 0; i < row.ladderPriceList.length; i++) {
              if (row.ladderPriceList[i] && row.ladderPriceList[i].delFlag * 1 === 0) {
                let str = ''
                if (row.ladderPriceList[i + 1] && row.ladderPriceList[i + 1].delFlag * 1 === 0) {
                  str = row.ladderPriceList[i].buyNum + '-' + (row.ladderPriceList[i + 1].buyNum - 1)
                } else {
                  str = '≥' + row.ladderPriceList[i].buyNum
                }
                row.ladderShownList.push({
                  price: row.ladderPriceList[i].buyPrice,
                  number: str
                })
              }
            }
          }
        })
      })
    },
    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.$message({ message: response.msg, type: 'success', center: true })
        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>
