<template>
  <div class="mod-config">
    <el-tabs v-model="merchantId" type="card" @tab-click="changeTab">
      <el-tab-pane label="众妙之门" name="2" />
      <el-tab-pane label="灵枢教育科技" name="1" />
    </el-tabs>

    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="handleSearch"
    >
      <el-form-item label="商品名称">
        <el-input
          v-model="dataForm.productName"
          placeholder="商品名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="库存状态">
        <el-select v-model="dataForm.isAlert" placeholder="请选择" style="width: 120px">
          <el-option label="全部" :value="0" />
          <el-option label="仅预警" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dataForm.dateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearch">查询</el-button>
        <el-button type="success" :loading="exportLoading" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>

    <div class="action-bar">
      <el-button type="primary" @click="openPurchase(1)">入库</el-button>
      <el-button type="warning" @click="openPurchase(2)">出库</el-button>
      <el-button type="warning" @click="openBatchOutbound">批量出库</el-button>
    </div>

    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      height="60vh"
      style="width: 100%"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="productId" label="商品ID" width="90" align="center" />
      <el-table-column prop="productName" label="商品名称" align="center" min-width="180" />
      <el-table-column prop="merchantLabel" label="商户" width="100" align="center" />
      <el-table-column prop="purchaseTotal" label="入库总量" width="100" align="center" />
      <el-table-column prop="saleTotal" label="出库总量" width="100" align="center" />
      <el-table-column prop="remainTotal" label="剩余库存" width="100" align="center">
        <template slot-scope="scope">
          <span class="remain-total">{{ scope.row.remainTotal }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余比率" width="100" align="center">
        <template slot-scope="scope">
          {{ formatRate(scope.row.remainRate) }}
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    />

    <purchase-dialog ref="purchaseDialog" @success="getDataList" />
    <batch-outbound-dialog ref="batchOutboundDialog" @success="getDataList" />
  </div>
</template>

<script>
import PurchaseDialog from './components/purchaseDialog.vue'
import BatchOutboundDialog from './components/batchOutboundDialog.vue'

export default {
  components: {
    PurchaseDialog,
    BatchOutboundDialog
  },
  data() {
    return {
      merchantId: '2',
      dataForm: {
        productName: '',
        isAlert: 0,
        dateRange: null
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      exportLoading: false
    }
  },
  activated() {
    this.applyRouteQuery()
    this.getDataList()
  },
  methods: {
    applyRouteQuery() {
      const isAlert = this.$route.query.isAlert
      if (isAlert !== undefined && isAlert !== '') {
        this.dataForm.isAlert = Number(isAlert) || 0
      }
    },
    handleSearch() {
      this.pageIndex = 1
      this.getDataList()
    },
    changeTab() {
      this.dataForm.productName = ''
      this.pageIndex = 1
      this.getDataList()
    },
    getQueryParams() {
      const params = {
        merchantId: Number(this.merchantId),
        current: this.pageIndex,
        limit: this.pageSize,
        isAlert: this.dataForm.isAlert
      }
      if (this.dataForm.productName) {
        params.productName = this.dataForm.productName
      }
      if (this.dataForm.dateRange && this.dataForm.dateRange.length === 2) {
        params.startTime = this.dataForm.dateRange[0]
        params.endTime = this.dataForm.dateRange[1]
      }
      return params
    },
    getDataList() {
      this.dataListLoading = true
      this.$http.request({
        url: this.$http.adornUrl('/master/inventoryManagement/stockStatistics'),
        method: 'POST',
        data: this.getQueryParams(),
        header: { 'Content-Type': 'application/json' }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.result.records || []
          this.totalPage = data.result.total || 0
          this.pageIndex = data.result.current || this.pageIndex
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      }).catch(() => {
        this.dataList = []
        this.totalPage = 0
        this.dataListLoading = false
      })
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    formatRate(rate) {
      if (rate == null) return '-'
      return (Number(rate) * 100).toFixed(2) + '%'
    },
    tableRowClassName({ row }) {
      if (row.remainRate != null && Number(row.remainRate) <= 0.3) {
        return 'row-low-stock'
      }
      return ''
    },
    openPurchase(bizType) {
      this.$refs.purchaseDialog.open(bizType, Number(this.merchantId))
    },
    openBatchOutbound() {
      this.$refs.batchOutboundDialog.open(Number(this.merchantId))
    },
    handleExport() {
      this.exportLoading = true
      this.$http({
        url: this.$http.adornUrl('/master/inventoryManagement/exportStockStatistics'),
        method: 'post',
        data: this.$http.adornData(this.getQueryParams()),
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        const merchantPrefix = this.merchantId === '2' ? '众妙' : '灵枢'
        link.download = `${merchantPrefix}库存统计.xlsx`
        link.click()
        window.URL.revokeObjectURL(link.href)
        this.$message.success('导出成功')
      }).catch(() => {
        this.$message.error('导出失败')
      }).finally(() => {
        this.exportLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.action-bar {
  margin-bottom: 12px;
}
/deep/ .el-table .row-low-stock{
  td {
    background-color: #fffaf2 !important;
  }
  .remain-total {
    color: #f56c6c;
  }
}
</style>
