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

    <Table :data="rows" :loading="loading" :columns="columns" @on-selection-change="onSelectionChange" border />

    <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: [],
      columns: [
        { type: 'selection', width: 60 },
        { title: '分类', key: 'category_name', align: 'center', minWidth: 80 },
        { title: '物料编码', key: 'material_code', align: 'center', minWidth: 100 },
        { title: '物料名称', key: 'material_name', align: 'center', minWidth: 100 },
        { title: '单位', key: 'unit', align: 'center', minWidth: 80 },
        { title: '可用库存', key: 'available_quantity', align: 'center', minWidth: 120 }
      ]
    }
  },
  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 = Object.assign({ pageNo: this.pager.pageNo, pageSize: this.pager.pageSize }, 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; }
.text-right { text-align: right; }
</style>
