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

    <el-menu :router="true" default-active="/goods/list" class="el-menu-demo" mode="horizontal">
      <el-menu-item index="/goods/list">全部商品</el-menu-item>
      <el-menu-item v-if="modules && modules.firstModulesName" index="/goods/list/preferred">{{ modules.firstModulesName }}</el-menu-item>
      <el-menu-item v-if="modules && modules.secondModulesName" index="/goods/list/preferential">{{ modules.secondModulesName }}</el-menu-item>
      <el-menu-item v-if="modules && modules.thirdModulesName" index="/goods/list/commonly">{{ modules.thirdModulesName }}</el-menu-item>
    </el-menu>

    <div class="filter-container" style="padding: 20px 0;">
      <el-form class="demo-form-inline goods-list">
        <el-form-item label="商品ID:" style="width:225px;float: left;">
          <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:190px;float: left;">
          <el-select v-model="listQuery.validFlag" placeholder="商品状态" clearable style="width: 110px" class="filter-item" value="" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="已上架" value="1" />
            <el-option label="已下架" value="2" />
          </el-select>
        </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 v-if="modules && modules.firstModulesName" :label="modules.firstModulesName+':'" style="width:180px;float: left;">
          <el-select v-model="listQuery.preferredProduct" placeholder="请选择" clearable style="width: 90px" class="filter-item" value="" @change="handleFilter">
            <!-- <el-option label="全部" value="" /> -->
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="modules && modules.secondModulesName" :label="modules.secondModulesName+':'" style="width:180px;float: left;">
          <el-select v-model="listQuery.preferentialProduct" placeholder="请选择" clearable style="width: 90px" class="filter-item" value="" @change="handleFilter">
            <!-- <el-option label="全部" value="" /> -->
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="modules && modules.thirdModulesName" :label="modules.thirdModulesName+':'" style="width:200px;float: left;">
          <el-select v-model="listQuery.commonlyProduct" placeholder="请选择" clearable style="width: 90px" class="filter-item" value="" @change="handleFilter">
            <!-- <el-option label="全部" value="" /> -->
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </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>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      style="width:100%;margin-top:20px;"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <el-table-column align="center" label="序号" width="35">
        <template slot-scope="scope">
          <span style="white-space:nowrap">{{ ((pageNum-1)*listQuery.pageSize)+scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品ID" align="center" prop="id" width="50" />
      <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="200" />
      <el-table-column label="供应商" align="center" prop="shopName" min-width="110" />
      <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" width="70" />
      <el-table-column v-if="modules && modules.firstModulesName" :label="modules.firstModulesName" align="center" prop="preferredProduct" width="50">
        <template slot-scope="{row}">
          <!--<el-tag :type="row.preferredProduct | statusFilter">{{ row.preferredProduct*1 === 1 ? '启用' : '停用' }}</el-tag>-->
          <i v-if="row.preferredProduct*1 === 1" class="el-icon-success" type="success" />
        </template>
      </el-table-column>
      <el-table-column v-if="modules && modules.secondModulesName" :label="modules.secondModulesName" align="center" prop="preferentialProduct" width="50">
        <template slot-scope="{row}">
          <!--<el-tag :type="row.preferentialProduct | statusFilter">{{ row.preferentialProduct*1 === 1 ? '启用' : '停用' }}</el-tag>-->
          <i v-if="row.preferentialProduct*1 === 1" class="el-icon-success" type="success" />
        </template>
      </el-table-column>
      <el-table-column v-if="modules && modules.thirdModulesName" :label="modules.thirdModulesName" align="center" prop="commonlyProduct" width="50">
        <template slot-scope="{row}">
          <!--<el-tag :type="row.commonlyProduct | statusFilter">{{ row.commonlyProduct*1 === 1 ? '启用' : '停用' }}</el-tag>-->
          <i v-if="row.commonlyProduct*1 === 1" class="el-icon-success" type="success" />
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="商品状态" align="center" prop="validFlag">
        <template slot-scope="{row}">
          <el-tag :type="row.validFlag | statusFilter">{{ row.validFlag*1 === 1 ? '已上架' : '已下架' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="productClassifyName" width="100" />
      <el-table-column align="center" label="添加时间" prop="addTime">
        <template v-if="row.addTime" slot-scope="{row}">
          <span>{{ row.addTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" style="width: 70px;margin:5px 0 0 0;" @click="handleEdit(row)">编辑</el-button>
          <el-button :type="row.validFlag*1 === 1 ? 'danger' : 'success'" size="mini" style="width: 70px;margin:5px 0 0 0;" @click="handleSwitch(row)">{{ row.validFlag*1 === 1 ? '下架' : '上架' }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>20" :total="total" :page.sync="listQuery.index" :limit.sync="listQuery.pageSize" @pagination="fetchData" />

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dialog" label-position="left" label-width="220px" style="width:360px; margin:0 auto;">
        <el-form-item label="商品分类" prop="classifyID">
          <el-select v-model="dialog.classifyID" placeholder="商品分类" :label="dialog.productClassifyName" clearable class="filter-item" :value="dialog.classifyID*1">
            <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 :label="'市场价(' + dialog.normalPrice + ')，修改为：'" prop="normalPrice">
          <el-input v-model="dialog.normalPrice" />
        </el-form-item>
        <el-form-item :label="'成本价(' + dialog.costPrice + ')，修改为：'" prop="costPrice">
          <el-input v-model="dialog.costPrice" />
        </el-form-item>
        <el-form-item :label="'售价(' + dialog.retailPrice + ')，修改为：'" prop="retailPrice">
          <el-input v-model="dialog.retailPrice" />
        </el-form-item>
        <el-form-item :label="'起订量(' + dialog.minBuyNumber + ')，修改为：'" prop="minBuyNumber">
          <el-input v-model="dialog.minBuyNumber" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="updateGoods">
          确认
        </el-button>
      </div>
    </el-dialog>
    <template>
      <el-backtop style="right: 40px; bottom: 40px;">
        <i class="el-icon-upload2" />
      </el-backtop>
    </template>
  </div>
</template>

<script>
import { getList, getModule, switchGoods, saveGoods } 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: function() {
    return {
      pageNum: 0,
      activeIndex: '0',
      list: null,
      modules: null,
      classify: null,
      listLoading: true,
      total: 0,
      listQuery: {
        index: 1,
        pageSize: 20,
        organizeID: this.$store.getters.organizeID,
        id: '',
        productName: '',
        shopName: '',
        classifyID: '', // 商品分类
        validFlag: '', // '商品状态,1已上架,2已下架',
        preferredProduct: '', // 是否是优选商品：0不是优选,1优选商品',
        commonlyProduct: '', // 是否是常用商品：0不是常用,1常用商品',
        preferentialProduct: '', // 是否是星范精品：0不是精品,1星范精品商品',
        productClassifyName: '' // '对应cm_mall_products_classify商品分类表id',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogTitle: '编辑',
      dialog: {
        id: '',
        classifyID: 0,
        normalPrice: '',
        costPrice: '',
        retailPrice: '',
        minBuyNumber: '',
        productClassifyName: ''
      },
      rules: {
        classifyID: [{ required: true, message: '请选择分类', trigger: 'change' }],
        normalPrice: [{ required: true, message: '市场价不能为空', trigger: 'blur' }],
        costPrice: [{ required: true, message: '成本价不能为空', trigger: 'blur' }],
        retailPrice: [{ required: true, message: '售价不能为空', trigger: 'blur' }],
        minBuyNumber: [{ required: true, message: '起订量不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    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
      getList(this.listQuery).then(response => {
        const { organizeProductsPage, listByEffective } = response.data
        this.pageNum = organizeProductsPage.index
        this.list = organizeProductsPage.results
        this.total = organizeProductsPage.totalRecord
        this.classify = listByEffective
        this.listLoading = false
      })
    },
    handleFilter() {
      this.fetchData()
    },
    handleSwitch(row) {
      if (row.validFlag === '1') {
        this.$confirm('确定下架该商品吗？下架后该商品将不会出现在小程序商城。', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handSwithGoods(row)
        })
      } else {
        this.$confirm('确定上架该商品吗？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handSwithGoods(row)
        })
      }
    },
    handSwithGoods(row) {
      switchGoods({ id: row.id }).then(() => {
        this.fetchData()
      }).catch(() => {
        this.fetchData()
      })
    },
    handleEdit(row) {
      this.dialog = Object.assign({}, row)
      this.dialog.classifyID = this.dialog.classifyID * 1
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateGoods() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveGoods(this.dialog).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.fetchData()
            this.dialogFormVisible = false
          })
        }
      })
    }
  }
}
</script>

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

