<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="filter.name"
        size="medium"
        placeholder="请输入商品名称"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="refresh"
        />
      </el-input>
      <el-input
        v-model="filter.consumerName"
        size="medium"
        placeholder="请输入客户名称"
        class="filter-input"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="refresh"
        />
      </el-input>
      <el-button
        type="primary"
        plain
        size="medium"
        class="add-button"
        @click="add"
      >
        新增
      </el-button>
    </div>
    <ScrollList
      ref="scrollList"
      v-slot="slotProps"
      :load-method="loadList"
      :total-pages="totalPages"
    >
      <GoodsItem
        v-for="item in slotProps.list"
        :key="item.id"
        :item="item"
        @edit="edit(item)"
        @remove="remove(item)"
        @detail="detail(item)"
      />
    </ScrollList>
  </div>
</template>

<script>
import GoodsItem from './components/GoodsItem'
import goodsApi from '@/api/goods'
import ScrollList from '@/components/ScrollList'
import AddDialog from '@/views/goods/components/AddDialog'
import EditDialog from '@/views/goods/components/EditDialog'
import DetailDialog from '@/views/goods/components/DetailDialog'

export default {
  components: {
    ScrollList,
    GoodsItem
  },
  data() {
    return {
      totalPages: null,
      filter: {
        name: null,
        consumerName: null
      }
    }
  },
  methods: {
    refresh() {
      this.$refs.scrollList.refresh()
    },
    async loadList(params) {
      console.log('params', params)
      const query = {
        ...params,
        p: {
          ...this.filter
        },
        apiUser: localStorage.getItem('apiUser'),
        checkSum: localStorage.getItem('checkSum')
      }
      console.log('查询商品列表', query)
      const response = await goodsApi.find(query)
      console.log('商品列表查询成功', response)
      this.totalPages = response.data.totalPage || 0
      return response.data?.list ?? []
    },
    add() {
      AddDialog.show(this.$refs.scrollList.refresh)
    },
    edit(row) {
      EditDialog.show({ ...row }, this.$refs.scrollList.refresh)
    },
    detail(row) {
      DetailDialog.show(row)
    },
    remove(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        goodsApi.remove(row.id).then(() => this.$message.success('删除成功')).finally(this.$refs.scrollList.refresh)
      }).catch(() => {
      })
    }
  }
}
</script>

<style
  scoped
  lang="scss"
>
@import "../../../styles/mobile-page";

.filter-input {
  margin-top: 5px;
}
</style>
