<template>
  <a-card size="small" :bordered="false" class="inventoryQueryList-wrap">
    <!-- 搜索条件 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
        <a-row :gutter="15">
          <a-col :md="6" :sm="24">
            <a-form-item label="产品编码">
              <a-input id="inventoryQueryList-productCode" v-model="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="原厂编码">
              <a-input id="inventoryQueryList-productOrigCode" v-model.trim="queryParam.productOrigCode" allowClear placeholder="请输入原厂编码"/>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-item label="产品名称">
              <a-input id="inventoryQueryList-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-item label="产品品牌">
                <a-select
                  placeholder="请选择产品品牌"
                  id="inventoryQueryList-productBrandSn"
                  allowClear
                  v-model="queryParam.productBrandSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in productBrandList" :key="item.brandSn" :value="item.brandSn">{{ item.brandName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品分类">
                <a-cascader
                  @change="changeProductType"
                  expand-trigger="hover"
                  change-on-select
                  :options="productTypeList"
                  :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
                  id="inventoryQueryList-productType"
                  placeholder="请选择产品分类"
                  allowClear
                  v-model="productType" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="库存情况">
                <a-select placeholder="请选择库存情况" id="inventoryQueryList-zeroQtyFlag" allowClear v-model="queryParam.zeroQtyFlag">
                  <a-select-option v-for="item in zeroQtyData" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="7" :sm="24">
            <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryQueryList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="inventoryQueryList-reset">重置</a-button>
            <a-button
              type="primary"
              style="margin-left: 5px"
              class="button-warning"
              @click="handleExport"
              :disabled="disabled"
              :loading="exportLoading"
              id="inventoryQueryList-export">导出</a-button>
            <a @click="advanced=!advanced" style="margin-left: 5px">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'"/>
            </a>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 合计 -->
    <a-alert type="info" showIcon style="margin-bottom:15px">
      <div class="ftext" slot="message">现有库存总数量（个）：<strong>{{ stockQty }}</strong>；现有库存总成本(￥)：<strong>{{ stockCost }}</strong>。</div>
    </a-alert>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :scroll="{ x: 1450, y: tableHeight }"
      bordered>
      <!-- 现有库存数量 -->
      <template slot="currentStockQty" slot-scope="text, record">
        {{ (record.currentStockQty + record.freezeQty) || 0 }}
        <span v-if="record.freezeQty">（冻结{{ record.freezeQty }}）</span>
      </template>
      <template slot="currentStockCost" slot-scope="text, record">
        {{ ((Number(record.currentStockCost)*1000 + Number(record.freezeCost)*1000)/1000).toFixed(2) || 0 }}
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button size="small" type="link" class="button-success" @click="goDetail(record)" id="inventoryQueryList-detail-btn">库存详情</a-button>
        <a-button size="small" type="link" class="button-warning" @click="goWarehouseDetail(record)" id="inventoryQueryList-warehouseDetail-btn">出入库明细</a-button>
      </template>
    </s-table>
    <!-- 库存详情 -->
    <inventory-query-detail-modal :openModal="openModal" :itemId="itemId" @close="closeModal" />
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, VSelect } from '@/components'
import inventoryQueryDetailModal from './detailModal.vue'
import { productBrandQuery } from '@/api/productBrand'
import { productTypeQuery } from '@/api/productType'
import { stockList, stockCount, stockExport } from '@/api/stock'
export default {
  components: { STable, VSelect, inventoryQueryDetailModal },
  data () {
    return {
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        productCode: '', //  产品编码
        productName: '', //  产品名称
        productOrigCode: '', //  原厂编码
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品分类1
        productTypeSn2: '', //  产品分类2
        productTypeSn3: '', //  产品分类3
        zeroQtyFlag: undefined //  库存数量是否为0
      },
      productType: [],
      exportLoading: false, // 导出loading
      disabled: false, //  查询、重置按钮是否可操作
      productBrandList: [], //  品牌下拉数据
      productTypeList: [], //  分类下拉数据
      zeroQtyData: [ //  库存情况
        { name: '库存数量为0', id: '1' },
        { name: '库存数量不为0', id: '0' }
      ],
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '最后入库时间', dataIndex: 'lastStockTime', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productUnit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品品牌', dataIndex: 'productBrandName', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '库存数量(个)', dataIndex: 'currentStockQty', scopedSlots: { customRender: 'currentStockQty' }, width: 165, align: 'center', sorter: true },
        { title: '库存成本(￥)', dataIndex: 'currentStockCost', scopedSlots: { customRender: 'currentStockCost' }, width: 165, align: 'center', sorter: true },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 200, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        if (this.tableHeight == 0) {
          this.tableHeight = window.innerHeight - 370
        }
        // 排序
        if (parameter.sortField == 'currentStockQty') {
          parameter.sortField = 'qty'
          parameter.sortAlias = ''
        }
        if (parameter.sortField == 'currentStockCost') {
          parameter.sortField = 'currentStockCost'
          parameter.sortAlias = 'stock'
        }
        return stockList(Object.assign(parameter, this.queryParam)).then(res => {
          const data = res.data
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
          }
          this.disabled = false
          // 总计
          this.getTotal(Object.assign(parameter, this.queryParam))
          // 产品分类
          if (this.productTypeList.length == 0) {
            this.getProductType()
          }
          // 产品品牌
          if (this.productBrandList.length == 0) {
            this.getProductBrand()
          }
          return data
        })
      },
      openModal: false, //  查看库存详情  弹框
      itemId: '', //  当前库存记录id
      currentStock: null
    }
  },
  computed: {
    stockQty () { //  库存总数量 合计
      const currentStockQty = this.currentStock && this.currentStock.currentStockQty ? Number(this.currentStock.currentStockQty) : 0
      const freezeQty = this.currentStock && this.currentStock.freezeQty ? Number(this.currentStock.freezeQty) : 0
      return currentStockQty + freezeQty
    },
    stockCost () { //  库存总成本 合计
      const currentStockCost = this.currentStock && this.currentStock.currentStockCost ? Number(this.currentStock.currentStockCost) : 0
      const freezeCost = this.currentStock && this.currentStock.freezeCost ? Number(this.currentStock.freezeCost) : 0
      return ((currentStockCost * 1000 + freezeCost * 1000) / 1000).toFixed(2)
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.productCode = ''
      this.queryParam.productOrigCode = ''
      this.queryParam.productName = ''
      this.queryParam.zeroQtyFlag = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    // 合计
    getTotal (param) {
      stockCount(param).then(res => {
        if (res.status == 200 && res.data) {
          this.currentStock = res.data
        } else {
          this.currentStock = null
        }
      })
    },
    //  库存详情
    goDetail (row) {
      this.itemId = row.stockSn
      this.openModal = true
    },
    //  关闭弹框
    closeModal () {
      this.itemId = ''
      this.openModal = false
    },
    //  出入库明细
    goWarehouseDetail (row) {
      this.$router.push({ path: `/inventoryManagement/inventoryQuery/warehouseDetail/${row.productSn}` })
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      this.exportLoading = true
      stockExport(params).then(res => {
        this.exportLoading = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          this.download(res)
        }
      })
    },
    download (data) {
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const a = moment().format('YYYYMMDDHHmmss')
      const fname = '库存查询' + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    },
    //  递归函数
    recursionFun (data) {
      if (data) {
        data.map((item, index) => {
          if (item.children && item.children.length == 0) {
            delete item.children
          } else {
            this.recursionFun(item.children)
          }
        })
      }
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  产品品牌  列表
    getProductBrand () {
      productBrandQuery({}).then(res => {
        if (res.status == 200) {
          this.productBrandList = res.data
        } else {
          this.productBrandList = []
        }
      })
    },
    //  产品分类  列表
    getProductType () {
      productTypeQuery({}).then(res => {
        if (res.status == 200) {
          this.productTypeList = res.data
        } else {
          this.productTypeList = []
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  }
}
</script>
