<template>
  <el-main class="bg_white">
    <div style="display: contents;" class="stocklist">
      <el-col :span="30" style="margin-top:40px;display: contents;margin-left: 10px;">
        <el-form ref="form" :model="filter" label-width="130px" style="margin-top: 20px;">
          <el-row>
            <el-col :span="4">
              <el-form-item class="label-sku" label="规格型号（SKU）">
                <el-input v-model="form_requst.sku" placeholder="请输入规格型号（SKU）"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="物料名称">
                <el-input v-model="form_requst.name" placeholder="请输入物料名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="物料编码">
                <el-input v-model="form_requst.fnumber" placeholder="请输入物料编码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="批号">
                <el-input v-model="form_requst.bn" placeholder="请输入批号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="2" style="display: flex; align-items: center;">
              <el-button type="primary" size="mini" @click="search">搜索</el-button>
              <el-button type="primary" size="mini" @click="reset">重置</el-button>
              <el-button type="primary" size="mini" @click="batchExport">导出</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </div>
    <!--表格-->
    <div class="m-t-10 table_90 p-b-20 border-r-10 text-black f-12" style="display: flex;flex-direction: column;">
      <vxe-table border resizable show-overflow ref="xTable" height="650" :scroll-x="{ enabled: false }" :scroll-y="{ enabled: false }" :header-cell-style="header_style" :data="tableData">
        <vxe-column field="fnumber" title="物料编码"  header-align="center" align="center"></vxe-column>
        <vxe-column field="sku" title="规格型号（SKU）" header-align="center" align="left"></vxe-column>
        <vxe-column field="name" title="物料名称"  header-align="center" align="left"></vxe-column>
        <vxe-column field="bn" title="批号"   header-align="center" align="center"></vxe-column>
        <vxe-column field="factory_price" title="出厂价（¥）"    header-align="center" align="center"></vxe-column>
        <vxe-column field="FDate" title="入库日期" header-align="center" align="center"></vxe-column>

      </vxe-table>
        <el-pagination
          :current-page="form_requst.page"
          :page-sizes="[20, 60, 100]"
          :page-size="form_requst.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
          class="m-t-10 m-b-20 table_90"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
  
    </div>
  </el-main>
</template>

<script>
import { mapState } from 'vuex'
import { mapActions } from 'vuex'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'

export default {
  data() {
    return {
      loading: null,
      header_style: {
        'background-color': '#F5F7FA',
        color: '#606266',
        fontSize: '10px',
        fontWeight: '600',
        textAlign: 'center'
      },
      form_requst: {
        page: 1,
        size: 20,
        sku: '',
        name: '',
        fnumber: '',
        bn: '',
        stock: '',
        stock_sub: '',
        org: '',
        FSTOCKID: '',
        available_stock:-1
      },
      tableData: [],
      dataCount: { total_inventory_num: 0, total_available_num: 0, total_inventory_price: 0.0 },
      stocklist: [],
      orglist: [],
      count: '',
      available_stock:-1
    }
  },

  computed: {
    ...mapState({
      // 取出页面标签
      userInfo: state => state.user.userInfo
    })
  },
  deactivated () {
    console.log('activated')
    window.removeEventListener('keydown', this.keyDown)
  },
  activated() {
    window.addEventListener('keydown', this.keyDown)
    console.log('activated')
    this.getList()
  },
  methods: {
    ...mapActions({
      // 关闭标签及页面
      handleCloseTag: 'topNavTag/removeNavTag'
    }),
    //列表
    getList() {
      const listLoading = ElLoading.service({
        lock: true
      })
      this.$http
        .get('admin/stock/group_list', this.form_requst)
        .then(res => {
          if (res.errno == 200) {
            console.log(res)
            this.tableData = res.data.list.data
            this.count = res.data.list.total
            this.dataCount = res.data.count
            this.orglist = res.data.org_list
            this.stocklist = res.data.stock
          } else {
            ElMessage({
              type: 'error',
              message: res.errmsg
            })
          }
        })
        .finally(() => {
          listLoading.close()
        })
    },
    //回车监听事件
    keyDown(e) {
      if (e.keyCode == 13 || e.keyCode == 100) {
        this.getList()
      }
    },
    //搜索
    search() {
      this.form_requst.page = 1
      this.getList()
    },
    // 重置
    reset() {
      this.form_requst = {
        page: 1,
        size: 20,
        sku: '',
        name: '',
        fnumber: '',
        bn: '',
        stock: '',
        stock_sub: '',
        org: '',
        FSTOCKID: ''
      }
      this.getList()
    },

    //分页
    handleSizeChange(new_size) {
      this.form_requst.size = new_size
      this.getList()
    },
    handleCurrentChange(new_page) {
      this.form_requst.page = new_page
      this.getList()
    },

    //批量导出
    batchExport() {
      console.log(this.userInfo.isall)
      this.loading = ElLoading.service({
        lock: true,
        text: '此操作需要一段时间请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      axios
        .get(process.env.VUE_APP_API_BASEURL + '/admin/stock/exportAll?sku='+this.form_requst.sku+
        "&name="+this.form_requst.name+"&fnumber="+this.form_requst.fnumber+'&bn='+this.form_requst.bn+"&available_stock="+this.form_requst.available_stock+
        '&stock='+this.form_requst.stock+'&stock_sub='+this.form_requst.stock_sub+'&org='+this.form_requst.org+"&FSTOCKID="+this.form_requst.FSTOCKID, {
          responseType: 'blob',
          headers: {
            /*'X-Token': getToken(),*/
            'Content-Type': 'application/json;charset=utf-8'
          },
          withCredentials: true
        })
        .then(res => {
          if (!res) {
            this.$message.error('导出失败')
            return false
          }
          const stream = res.data // 后端用stream返回Excel文件
          const blob = new Blob([stream])
          // 前端获取业务码，成功执行正常业务
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          const timeStamp = new Date().toString()
          const nameStr = decodeURI(escape(JSON.parse(res.headers['content-disposition'].split(';')[1].split('=')[1])))
          downloadElement.download = decodeURI(nameStr) // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
          this.loading.close()
        })
    },
    cancel() {
      this.handleCloseTag()
    }
  }
}
</script>
<style scoped>
/*新样式*/
.vxe-table--render-default {
  font-size: 12px;
}
::v-deep(.vxe-header--column, .vxe-table--render-default) {
  padding: 5px 0 !important;
}
::v-deep(.vxe-table--render-default .vxe-cell) {
  padding-left: 2px;
  padding-right: 2px;
}
::v-deep(.el-input__inner) {
  width: 100% !important;
}
::v-deep(.stocklist label) {
  font-size: 12px !important;
}
::v-deep(.stocklist .el-form-item) {
  margin-bottom: 5px !important;
}

::v-deep(.stocklist .el-input__inner) {
  height: 32px;
  line-height: 32px;
  font-size: 12px;
}
</style>
