<template>
  <div class="productInfoList-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="productInfoList-name" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="产品编码">
              <a-input id="productInfoList-code" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="是否促销品">
              <v-select
                code="FLAG"
                id="productInfoList-promotionFlag"
                v-model="queryParam.promotionFlag"
                allowClear
                placeholder="请选择是否"
              ></v-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="类型">
              <a-select v-model.trim="queryParam.ptype" :dropdownMatchSelectWidth="false" >
                <a-select-option value="0">
                  全部产品
                </a-select-option>
                <a-select-option value="1">
                  剩余待下推数量＞0的产品
                </a-select-option>
                <a-select-option value="2">
                  可全部下推的产品
                </a-select-option>
                <a-select-option value="3">
                  不可全部下推的产品
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="出库仓库">
              <chooseWarehouse ref="warehouse" :allowClear="false" v-model="queryParam.warehouseSn"></chooseWarehouse>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
            <a-button type="primary" class="button-info" @click="$refs.table.refresh(true)" :disabled="disabled" id="productInfoList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" id="productInfoList-reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 按钮 -->
    <div class="table-operator">
      <a-button type="primary" :disabled="newLoading" class="button-info" @click="handlePlAdd">批量添加</a-button>
      <a-button type="danger" :disabled="newLoading" class="button-error" @click="handlePlCancel">批量取消</a-button>
      <!-- <a-button type="default" :disabled="newLoading" @click="handleOneDispatch">有货一键下推</a-button> -->
    </div>
    <!-- alert -->
    <a-alert type="info" style="margin-bottom: 10px;" v-if="detailData">
      <div slot="message">
        总销售数量：<strong>{{ detailData&&(detailData.totalQty || detailData.totalQty==0) ? detailData.totalQty : '--' }}</strong>；
        已取消数量：<strong>{{ detailData&&(detailData.totalCancelQty || detailData.totalCancelQty==0) ? detailData.totalCancelQty : '--' }}</strong>；
        已下推数量：<strong>{{ detailData&&(detailData.totalPushedQty || detailData.totalPushedQty==0) ? detailData.totalPushedQty : '--' }}</strong>；
        待下推数量：<strong>{{ detailData&&(detailData.totalUnpushedQty || detailData.totalUnpushedQty==0) ? detailData.totalUnpushedQty : '--' }}</strong>；<br/>
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')">总售价：<strong>{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_costPrice')">总成本：<strong>{{ detailData&&(detailData.totalCost || detailData.totalCost==0) ? toThousands(detailData.totalCost) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_costPrice')&&$hasPermissions('B_salesDispatch_salesPrice')">总毛利：<strong>{{ detailData&&(detailData.grossProfit || detailData.grossProfit==0) ? toThousands(detailData.grossProfit) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')">已取消金额：<strong>{{ detailData&&(detailData.totalCancelAmount || detailData.totalCancelAmount==0) ? toThousands(detailData.totalCancelAmount) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')">已下推金额：<strong>{{ detailData&&(detailData.totalPushedAmount || detailData.totalPushedAmount==0) ? toThousands(detailData.totalPushedAmount) :'--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')">待下推金额：<strong>{{ detailData&&(detailData.totalUnpushedAmount || detailData.totalUnpushedAmount==0) ? toThousands(detailData.totalUnpushedAmount) : '--' }}</strong>；</span>
      </div>
    </a-alert>

    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="small"
      :rowKey="(record) => record.id"
      :row-selection="{ columnWidth: 40, getCheckboxProps:record =>({props: { disabled: record.surplusQty<=0 }})}"
      @rowSelection="rowSelectionFun"
      :columns="columns"
      :showPagination="false"
      :data="loadData"
      :scroll="{ y: 300 }"
      :defaultLoadData="false"
      bordered>
      <!-- 取消数量 -->
      <template slot="nums" slot-scope="text, record">
        <div v-if="record.surplusQty>0" @dblclick.stop>
          <a-input-number
            size="small"
            v-model="record.cancelNums"
            :precision="0"
            :min="0"
            :max="record.surplusQty"
            style="width: 100%;"
            placeholder="请输入" />
        </div>
        <div v-else>--</div>
      </template>
      <!-- 产品编码 -->
      <template slot="productCode" slot-scope="text, record">
        <a-badge count="促" v-if="record.promotionFlag == 1">
          <div style="padding-right: 15px;">{{ text }}</div>
        </a-badge>
        <span v-else>{{ text }}</span>
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button
          size="small"
          type="link"
          class="button-info"
          :loading="newLoading"
          @click="handleAdd(record)"
          v-if="record.surplusQty>0"
          id="productInfoList-edit-btn">添加</a-button>
        <span v-else>--</span>
      </template>
    </s-table>

  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { salesDetailAllStockList } from '@/api/salesDetail'
import { STable, VSelect } from '@/components'
import chooseWarehouse from '@/views/common/chooseWarehouse'
export default {
  name: 'QueryPart',
  mixins: [commonMixin],
  components: { STable, VSelect, chooseWarehouse },
  props: {
    newLoading: Boolean
  },
  watch: {
    data (newValue, oldValue) {
      this.resetSearchForm()
    }
  },
  data () {
    return {
      advanced: true, // 高级搜索 展开/关闭
      showSetting: false, // 设置弹框
      productType: [],
      salesBillSn: '',
      detailData: null,
      queryParam: {
        ptype: '0', // 类型
        productCode: '', //  产品编码
        productName: '', //  产品名称
        promotionFlag: undefined, //  是否促销品
        brandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        salesBillSn: '',
        warehouseSn: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.queryParam.salesBillSn = this.salesBillSn
        return salesDetailAllStockList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            if (data) {
              // 根据类型过滤数据
              data = data.filter(item => {
                if (this.queryParam.ptype == '1') {
                  return item != null && item.surplusQty > 0
                }
                if (this.queryParam.ptype == '2') {
                  return item != null && item.surplusQty > 0 && item.surplusQty <= item.stockQty
                }
                if (this.queryParam.ptype == '3') {
                  return item != null && item.surplusQty > item.stockQty
                }
                if (this.queryParam.ptype == '0') {
                  return item != null
                }
              })
              // 增加编号
              const no = 0
              for (var i = 0; i < data.length; i++) {
                data[i].no = no + i + 1
                data[i].cancelNums = data[i].surplusQty
              }
              this.disabled = false
            }
          }
          return data
        })
      },
      rowSelectionInfo: null
    }
  },
  computed: {
    columns () {
      const arr = [
        // { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', scopedSlots: { customRender: 'productCode' }, width: '14%', align: 'center' },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '14%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productEntity.origCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '销售价', dataIndex: 'price', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '成本价', dataIndex: 'showCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '出库仓库', dataIndex: 'warehouseName', width: '8%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'productEntity.unit', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '可用库存', dataIndex: 'stockQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '销售数量', dataIndex: 'qty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '已取消', dataIndex: 'cancelQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '已下推', dataIndex: 'pushedQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '待下推数量', dataIndex: 'surplusQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '取消数量', dataIndex: 'cancelNums', scopedSlots: { customRender: 'nums' }, width: '7%', align: 'center' },
        { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      if (this.$hasPermissions('B_salesDispatch_salesPrice')) { //  售价权限
        arr.splice(3, 0, { title: '销售价', dataIndex: 'price', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      if (this.$hasPermissions('B_salesDispatch_costPrice')) {
        const ind = this.$hasPermissions('B_salesDispatch_salesPrice') ? 4 : 3
        arr.splice(ind, 0, { title: '成本价', dataIndex: 'showCost', width: '6%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 类型变化,过滤列表
    handlePtypeChange () {},
    //  重置
    resetSearchForm () {
      this.queryParam.ptype = '0'
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.promotionFlag = undefined
      this.queryParam.brandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.warehouseSn = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    pageInit (salesBillSn, detailData) {
      this.salesBillSn = salesBillSn
      this.detailData = detailData
      this.$refs.table.clearSelected()
      this.resetSearchForm()
    },
    clearTable () {
      this.rowSelectionInfo = null
      this.$refs.table.clearSelected()
    },
    // 刷新当前页面
    resetCurForm () {
      this.$refs.table.clearSelected() // 清空表格选中项
      this.$refs.table.refresh()
    },
    // 添加
    handleAdd (row) {
      if (row.stockQty > 0) { //  可用库存大于0才可添加
        this.$emit('addProduct', [row.salesBillDetailSn])
      } else {
        this.$message.warning('库存为0，不可添加！')
      }
    },
    // 批量添加
    handlePlAdd () {
      const _this = this
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        _this.$message.warning('请先选择产品！')
        return
      }
      const obj = []
      _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows.map(item => {
        if (item.stockQty > 0) {
          obj.push(item.salesBillDetailSn)
        }
      })
      if (obj.length < 1) {
        this.$message.warning('所选产品库存为0，不可添加！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '确认要批量添加到待下推列表吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.$emit('addProduct', obj)
        }
      })
    },
    // 批量取消
    handlePlCancel () {
      const _this = this
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        _this.$message.warning('请先选择产品！')
        return
      }
      const obj = []
      _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows.map(item => {
        obj.push({
          'cancelQty': item.cancelNums,
          'salesBillDetailSn': item.salesBillDetailSn,
          'salesBillSn': this.salesBillSn
        })
      })

      this.$emit('cancelProduct', obj)
    },
    // 一键下推
    handleOneDispatch () {
      this.$emit('oneDispatch')
    },
    //  产品分类  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] : ''
    }
  }
}
</script>
