<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入门店名称" />
      <el-select v-model="listQuery.channelId" clearable style="width: 200px" class="filter-item" placeholder="请选择所属渠道">
        <el-option v-for="type in channels" :key="type.id" :label="type.name" :value="type.id" />
      </el-select>
      <el-button v-permission="['GET /admin/shop/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/shop/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="商品编码" prop="sno" sortable />
      <el-table-column align="left" width="450" label="名称" prop="name" />
      <el-table-column align="center" label="渠道" prop="channelId">
        <template slot-scope="scope">
          <el-tag type="primary">{{ scope.row.channelId | channelsFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="品类" prop="category">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.category }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="成本价" prop="priceCost" />
      <el-table-column align="center" label="销售价" prop="priceSale" />
      <el-table-column align="center" label="状态" prop="deleted">
        <template slot-scope="scope">
          <span v-if="scope.row.deleted == true">已停用</span>
          <span v-else>正常</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/goods/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/goods/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="名称" prop="name">
          <el-input v-model="dataForm.name" style="width:500px" placeholder="商品名称" />
        </el-form-item>

        <el-form-item label="商品编号" prop="sno">
          <el-input v-model="dataForm.sno" placeholder="商品所在平台的编号" />
        </el-form-item>

        <el-form-item label="成本价" prop="priceCost">
          <el-input v-model="dataForm.priceCost" style="width:200px" type="number">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="销售价" prop="priceSale">
          <el-input v-model="dataForm.priceSale" style="width:200px" type="number">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="商品分类" prop="category">
          <el-select v-model="dataForm.category" clearable style="width:200px" class="filter-item" placeholder="请选择商品分类">
            <el-option v-for="type in cateOptions" :key="type.label" :label="type.name" :value="type.label" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属渠道" prop="channelId">
          <el-select v-model="dataForm.channelId" style="width:200px" clearable class="filter-item" placeholder="请选择渠道">
            <el-option v-for="type in channels" :key="type.id" :label="type.name" :value="type.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="dataForm.remark" placeholder="简单商品描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listGoods, createGoods, updateGoods, deleteGoods } from '@/api/goods'
import { allChannel } from '@/api/channel'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

let vm

export default {
  name: 'Goods',
  components: { Pagination },
  filters: {
    channelsFilter(value) {
      const rs = vm.channels.filter((item) => {
        return item.id === value
      })

      if (rs != null && rs.length > 0) { return rs[0].name }
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        name: undefined,
        channelId: undefined,
        page: 1,
        limit: 20,
        sort: 'create_time',
        order: 'desc'
      },
      channels: [],
      dataForm: {
        id: undefined,
        name: '',
        channelId: 0,
        remark: '',
        category: '保洁',
        price_sale: 0,
        price_cost: 0,
        deleted: false
      },
      cateOptions: [{
        value: '保洁',
        label: '保洁'
      }, {
        value: '保姆',
        label: '保姆'
      }, {
        value: '品类',
        label: '品类'
      }, {
        value: '中介',
        label: '中介'
      }],
      deletedOptions: [{
        value: false,
        label: '正常'
      }, {
        value: true,
        label: '删除'
      }],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        sno: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        channelId: [{ required: true, message: '渠道不能为空', trigger: 'blur' }],
        category: [{ required: true, message: '分类不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  beforeCreate() {
    vm = this
  },
  created() {
    this.getList()
    allChannel().then(res => {
      this.channels = res.data.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      listGoods(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: '',
        remark: '',
        category: '保洁',
        price_sale: undefined,
        price_cost: undefined,
        channelId: undefined,
        deleted: false
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createGoods(this.dataForm).then(response => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify.success({
              title: '成功',
              message: '创建成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateGoods(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify.success({
              title: '成功',
              message: '更新成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteGoods(row).then(response => {
        this.$notify.success({
          title: '成功',
          message: '删除成功'
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    }
  }
}
</script>
