<template>
  <Modal v-model="visible" title="选择物料" width="900" :mask-closable="false">
    <div class="search-div">
      <Row type="flex" :gutter="16" align="middle">
        <Col :span="6">
          <span>分类：</span>
          <Select v-model="filters.category_id" clearable style="width: 100%">
            <Option v-for="c in categoryOptions" :key="c.id" :value="c.id">{{ c.category_Name }}</Option>
          </Select>
        </Col>
        <Col :span="6">
          <span>物料编码：</span>
          <Input v-model="filters.material_code" placeholder="物料编码" />
        </Col>
        <Col :span="8">
          <span>物料名称：</span>
          <Input v-model="filters.material_name" placeholder="物料名称" />
        </Col>
        <Col :span="4" class="text-right">
          <Button type="primary" class="mr10" @click="handleSearch">搜索</Button>
          <Button @click="handleReset">重置</Button>
        </Col>
      </Row>
    </div>

    <Table :data="rows" :loading="loading" @on-selection-change="onSelectionChange" border>
      <TableColumn type="selection" width="60"></TableColumn>
      <TableColumn prop="material_code" title="物料编码" align="center" />
      <TableColumn prop="material_name" title="物料名称" align="center" />
      <TableColumn prop="unit" title="单位" align="center" width="80" />
      <TableColumn prop="available_quantity" title="可用库存" align="center" width="120" />
      <TableColumn prop="category_Name" title="分类" align="center" />
    </Table>

    <Page class="page_style" :total="pager.totalRecord" :current="pager.pageNo" :page-size="pager.pageSize" show-total show-sizer
      @on-change="pageChange" @on-page-size-change="sizeChange" />

    <div slot="footer">
      <Button @click="handleCancel">取消</Button>
      <Button type="primary" :loading="confirming" @click="handleConfirm">确定</Button>
    </div>
  </Modal>
</template>

<script>
import { getMaterialList, getMaterialCategoryList } from '@/api/key-dm'

export default {
  name: 'material-selector',
  props: {
    // v-model: value 控制显示
    value: { type: Boolean, default: false },
    // 初始已选项（array of objects）
    selected: { type: Array, default: () => [] }
  },
  data () {
    return {
      visibleInternal: false,
      filters: { category_id: '', material_code: '', material_name: '' },
      rows: [],
      loading: false,
      pager: { pageNo: 1, pageSize: 10, totalRecord: 0 },
      selectedRows: [],
      confirming: false,
      categoryOptions: []
    }
  },
  computed: {
    visible: {
      get () { return this.value },
      set (v) { this.$emit('input', v) }
    }
  },
  watch: {
    visible (v) {
      if (v) {
        // 初始化
        this.pager.pageNo = 1
        this.loadCategories()
        this.fetchList()
        // restore selected
        this.selectedRows = Array.isArray(this.selected) ? this.selected.slice() : []
      }
    }
  },
  methods: {
    async loadCategories () {
      try {
        const ret = await getMaterialCategoryList({ pageNo: 1, pageSize: 1000, params: {} })
        if (ret.data && ret.data.errcode === 0) {
          this.categoryOptions = ret.data.data.results || []
        }
      } catch (e) { console.error(e) }
    },
    fetchList () {
      this.loading = true
      const payload = { pageNo: this.pager.pageNo, pageSize: this.pager.pageSize, params: this.filters }
      getMaterialList(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || {}
          this.rows = data.results || []
          this.pager.totalRecord = data.totalRecord || 0
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data && ret.data.errmsg })
        }
      }).finally(() => { this.loading = false })
    },
    handleSearch () {
      this.pager.pageNo = 1
      this.fetchList()
    },
    handleReset () {
      this.filters = { category_id: '', material_code: '', material_name: '' }
      this.pager.pageNo = 1
      this.fetchList()
    },
    pageChange (pageNo) {
      this.pager.pageNo = pageNo
      this.fetchList()
    },
    sizeChange (size) {
      this.pager.pageSize = size
      this.pager.pageNo = 1
      this.fetchList()
    },
    onSelectionChange (list) {
      this.selectedRows = list || []
    },
    handleCancel () {
      this.$emit('cancel')
      this.$emit('input', false)
    },
    handleConfirm () {
      this.confirming = true
      // emit selected rows to parent
      this.$emit('on-ok', this.selectedRows)
      this.$emit('input', false)
      this.confirming = false
    }
  }
}
</script>

<style scoped>
.search-div { border: 1px solid #dce1e7; padding: 12px; margin-bottom: 12px; background-color: #f8fbff; }
.mr10 { margin-right: 10px; }
.page_style { margin-top: 12px; text-align: right; }
</style>


