<template>
  <a-card size="small" :bordered="false" class="inventoryWarningList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="pageInit(1)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="产品编码">
                <a-input id="inventoryWarningList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="原厂编码">
                <a-input id="inventoryWarningList-productOrigCode" v-model.trim="queryParam.productOrigCode" allowClear placeholder="请输入原厂编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品名称">
                <a-input id="inventoryWarningList-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="inventoryWarningList-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"
                    change-on-select
                    v-model="productType"
                    expand-trigger="hover"
                    :options="productTypeList"
                    :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
                    id="inventoryWarningList-productType"
                    placeholder="请选择产品分类"
                    allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="预警提示">
                  <v-select
                    v-model="queryParam.warnTip"
                    ref="warnTip"
                    id="inventoryWarningList-warnTip"
                    code="STOCK_WARN_TIP"
                    placeholder="请选择预警提示"
                    allowClear
                  ></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="pageInit(1)" :disabled="disabled" id="inventoryWarningList-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="inventoryWarningList-reset">重置</a-button>
              <!-- <a-button
                style="margin-left: 8px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                id="inventoryWarningList-export">导出</a-button> -->
              <a @click="advanced=!advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button type="primary" v-if="$hasPermissions('B_inventoryWarningBatchSave')" id="inventoryWarningList-update" :loading="loading" @click="handleupdate">批量更新</a-button>
        <span style="margin-left: 8px" v-if="$hasPermissions('B_inventoryWarningBatchSave')">
          <template v-if="hasSelected">{{ `已选 ${selectedRowKeys.length} 项` }}</template>
        </span>
      </div>
      <!-- 列表 -->
      <a-table
        class="sTable"
        ref="table"
        size="default"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :rowKey="(record) => record.id"
        :columns="columns"
        :dataSource="loadData"
        :scroll="{ x: 2120, y: tableHeight }"
        :pagination="paginationProps"
        bordered>
        <!-- 产品分类 -->
        <template slot="productType" slot-scope="text, record">
          <span v-if="record.productTypeName2 || record.productTypeName3">{{ record.productTypeName2 }} {{ record.productTypeName3 ? '>' : '' }} {{ record.productTypeName3 }}</span>
          <span v-else>--</span>
        </template>
        <!-- 实时库存数 -->
        <template slot="stockQty" slot-scope="text, record">
          {{ record.currentStockQty + record.freezeQty }}
          <span v-if="record.freezeQty">（冻结{{ record.freezeQty }}）</span>
        </template>
        <!-- 预警提示 -->
        <template slot="warnTip" slot-scope="text, record">
          <span v-if="record.warnTipDictValue" :class="[record.warnTip=='OVERFLOW'?'yellow':record.warnTip=='NOT_ENOUGH'?'red':record.warnTip=='LACK'?'blue':record.warnTip=='NORMAL'?'green':'']">{{ record.warnTipDictValue }}</span>
          <span v-else>--</span>
        </template>
        <!-- 在途数 -->
        <template slot="inTransit" slot-scope="text, record" >
          <div>
            <a-input-number
              id="inventoryWarningList-inTransit"
              v-model="record.inTransit"
              :precision="0"
              :min="0"
              :max="999999"
              placeholder="请输入在途数" />
          </div>
        </template>
        <!-- 最大库存数 -->
        <template slot="upperLimit" slot-scope="text, record" >
          <div>
            <a-input-number
              id="inventoryWarningList-upperLimit"
              v-model="record.upperLimit"
              :precision="0"
              :min="0"
              :max="999999"
              placeholder="请输入最大库存数" />
          </div>
        </template>
        <!-- 最小库存数 -->
        <template slot="lowerLimit" slot-scope="text, record" >
          <div>
            <a-input-number
              id="inventoryWarningList-lowerLimit"
              v-model="record.lowerLimit"
              :precision="0"
              :min="0"
              :max="record.upperLimit"
              placeholder="请输入最小库存数" />
          </div>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            type="primary"
            v-if="$hasPermissions('B_inventoryWarningSave')"
            size="small"
            class="button-info"
            @click="handleSave(record)"
            id="inventoryWarningList-add-btn">保存</a-button>
        </template>
      </a-table>
    </a-spin>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, VSelect } from '@/components'
import { stockWarnList, stockWarnSaveBatch } from '@/api/stockWarn'
import { dealerProductBrandQuery } from '@/api/dealerProductBrand'
import { dealerProductTypeList } from '@/api/dealerProductType'
export default {
  components: { STable, VSelect },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        productCode: '',
        productName: '',
        productOrigCode: '', // 原厂编码
        productBrandSn: undefined,
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined,
        warnTip: undefined
      },
      exportLoading: false, // 导出loading
      disabled: false, //  查询、重置按钮是否可操作
      productBrandList: [], //  产品品牌下拉数据
      productTypeList: [], //  产品类别下拉数据
      productType: [],
      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: 'productOrigCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品品牌', dataIndex: 'brandName', width: 200, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, width: 200, align: 'center' },
        { title: '实时库存数(个)', scopedSlots: { customRender: 'stockQty' }, width: 180, align: 'center' },
        { title: '在途数(个)', scopedSlots: { customRender: 'inTransit' }, width: 130, align: 'center' },
        { title: '总库存数(个)', dataIndex: 'totalStockQty', width: 130, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '最大库存数(个)', scopedSlots: { customRender: 'upperLimit' }, width: 130, align: 'center' },
        { title: '最小库存数(个)', scopedSlots: { customRender: 'lowerLimit' }, width: 130, align: 'center' },
        { title: '差异数量', dataIndex: 'differenceNum', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '预警提示', scopedSlots: { customRender: 'warnTip' }, width: 100, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center', fixed: 'right' }
      ],
      loadData: [],
      pageNo: 1, //  分页页码
      pageSize: 10, //  分页 每页多少条
      paginationProps: {
        showSizeChanger: true, //  是否可以改变 pageSize
        total: 0, //  分页总条数
        current: 1,
        onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize),
        onChange: (current) => this.changePage(current)
      },
      selectedRowKeys: [],
      selectedRows: [],
      loading: false
    }
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0
    }
  },
  methods: {
    //  分页  一页多少条change
    changePageSize (current, pageSize) {
      this.pageNo = current
      this.pageSize = pageSize
      this.pageInit()
    },
    //  分页 页码change
    changePage (current) {
      this.pageNo = current
      this.pageInit()
    },
    //  列表数据
    pageInit (pageNo) {
      if (this.tableHeight == 0) {
        this.tableHeight = window.innerHeight - 380
      }
      this.disabled = true
      this.pageNo = pageNo || this.pageNo
      const params = Object.assign({ pageNo: this.pageNo, pageSize: this.pageSize }, this.queryParam)
      stockWarnList(params).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.paginationProps.total = Number(res.data.count) || 0
          this.paginationProps.current = this.pageNo
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
          }
          this.loadData = data.list
          this.disabled = false
        } else {
          this.paginationProps.total = 0
          this.paginationProps.current = 1
          this.loadData = []
        }
      })
    },
    //  保存
    handleSave (row, isBatch) {
      const params = []
      if (isBatch) { //  批量更新
        const dataInd = []
        this.selectedRows.map((item, index) => {
          if ((!item.inTransit && item.inTransit != 0) || (!item.upperLimit && item.upperLimit != 0) || (!item.lowerLimit && item.lowerLimit != 0)) {
            dataInd.push(item.no)
          }
          params.push({
            id: item.id,
            inTransit: item.inTransit,
            upperLimit: item.upperLimit,
            lowerLimit: item.lowerLimit
          })
        })
        if (dataInd.length > 0) {
          let str = ''
          dataInd.map(item => {
            str += item + '、'
          })
          str = str.substr(0, str.length - 1)
          this.$message.warning('请完善第' + str + '行数据后再提交')
          return
        }
      } else { //  单个保存
        if (!row.inTransit && row.inTransit != 0) {
          this.$message.warning('请输入在途数')
          return
        }
        if (!row.upperLimit && row.upperLimit != 0) {
          this.$message.warning('请输入最大库存数')
          return
        }
        if (!row.lowerLimit && row.lowerLimit != 0) {
          this.$message.warning('请输入最小库存数')
          return
        }
        params.push({
          id: row.id,
          inTransit: row.inTransit,
          upperLimit: row.upperLimit,
          lowerLimit: row.lowerLimit
        })
      }
      this.spinning = true
      stockWarnSaveBatch(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.pageInit()
          this.selectedRowKeys = []
          this.selectedRows = []
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    //  重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productOrigCode = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.queryParam.warnTip = undefined
      this.pageNo = 1
      this.pageSize = 10
      this.paginationProps.total = 0
      this.paginationProps.current = 1
      this.pageInit(1)
    },
    //  批量更新
    handleupdate () {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定提交批量更新的内容吗？',
        centered: true,
        onOk () {
          _this.handleSave('', 'batch')
        }
      })
    },
    //  产品分类  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 () {
      // sysFlag不传,此处应查询所有产品
      dealerProductBrandQuery({}).then(res => {
        if (res.status == 200) {
          this.productBrandList = res.data
        } else {
          this.productBrandList = []
        }
      })
    },
    //  产品分类  列表
    getProductType () {
      dealerProductTypeList({}).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
      )
    },
    //  导出
    handleExport () {
      const params = this.queryParam
      this.exportLoading = true
      // customerBundleExportDelay(params).then(res => {
      //   this.exportLoading = false
      //   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()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.pageInit(1)
      vm.getProductType()
      vm.getProductBrand()
    })
  }
}
</script>

<style lang="less">
  .inventoryWarningList-wrap{
    .green{
      color: #19be6b;
    }
    .red{
      color: #ed1c24;
    }
    .yellow{
      color: #ff9900;
    }
    .blue{
      color: #2db7f5;
    }
  }
</style>
