<template>
  <div class="productInfoList-wrap">
    <!-- 搜索条件 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchForm">
        <a-row :gutter="15">
          <a-col :md="6" :sm="24">
            <a-form-item label="出库仓库" prop="warehouseSn" required>
              <chooseWarehouse ref="warehouse" :allowClear="false" v-model="queryParam.warehouseSn" :isDefault="true" @load="loadWarehouse"></chooseWarehouse>
            </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="产品名称">
              <a-input id="productInfoList-name" 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-input id="productInfoList-origCode" v-model.trim="queryParam.productOrigCode" allowClear placeholder="请输入原厂编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品品牌">
                <ProductBrand id="productInfoList-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品分类">
                <ProductType id="productInfoList-productType" v-model="productType" @change="changeProductType"></ProductType>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
            <a-button type="primary" @click="searchForm" :disabled="disabled" id="productInfoList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" id="productInfoList-reset">重置</a-button>
            <a @click="advanced=!advanced" style="margin: 0 5px">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'"/>
            </a>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- tab选项卡 -->
    <a-tabs type="card" @change="changeTab">
      <a-tab-pane v-for="item in tabList" :key="item.val" :tab="item.text"></a-tab-pane>
    </a-tabs>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="small"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :customRow="handleClickRow"
      :scroll="{ y: tableHeight, x: 1040 }"
      :defaultLoadData="false"
      :pagination="{pageSizeOptions: ['10','20','30','50','100','300','500']}"
      :pageSize="50"
      bordered>
      <!-- 销售数量 -->
      <template slot="nums" slot-scope="text, record">
        <div @dblclick.stop>
          <a-input-number
            size="small"
            v-model="record.salesNums"
            :precision="0"
            :min="1"
            :max="99999999"
            style="width: 100%;"
            placeholder="请输入" />
        </div>
      </template>
      <!-- 价格 -->
      <template slot="productPrice" slot-scope="text, record">
        {{ text||text==0 ? toThousands(text) : '--' }} <span title="原价" v-if="promoProductClz == 'GIFT' || promoProductClz == 'DISCOUNT'">({{ record.origPrice||record.origPrice==0 ? toThousands(record.origPrice) : '--' }})</span>
      </template>
      <!-- 产品名称 -->
      <template slot="productName" slot-scope="text, record">
        <div class="ellipsisCon">
          <a-tooltip placement="rightBottom">
            <template slot="title">
              <span>{{ text }}</span>
            </template>
            <span class="ellipsisText">{{ text }}</span>
          </a-tooltip>
          <!-- <a-badge :number-style="{ backgroundColor: '#52c41a' }" count="活动" v-if="record.isJoinActivityProduct == 1"></a-badge> -->
        </div>
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button
          size="small"
          type="link"
          class="button-info"
          :loading="newLoading"
          @click="handleAdd(record)"
          v-if="promoProductClz!='GIFT' ? record.productPrice : record.origPrice"
          id="productInfoList-edit-btn">添加</a-button>
        <span v-else>--</span>
      </template>
    </s-table>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { queryPromoProductPage } from '@/api/stock'
import ProductType from '@/views/common/productType.js'
import ProductBrand from '@/views/common/productBrand.js'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import { STable, VSelect } from '@/components'
export default {
  name: 'ActiveQueryPart',
  mixins: [commonMixin],
  components: { STable, VSelect, ProductBrand, ProductType, chooseWarehouse },
  props: {
    newLoading: Boolean
  },
  data () {
    return {
      advanced: false, // 高级搜索 展开/关闭
      showSetting: false, // 设置弹框
      productType: [], // 产品类型
      buyerSn: '', // 客户sn
      queryParam: { //  查询条件
        productCode: '', //  产品编码
        productName: '', //  产品名称
        productOrigCode: '', //  原厂编码
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        warehouseSn: undefined // 仓库sn
      },
      defaultWarehouseSn: undefined, // 默认仓库sn
      tableHeight: 300, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      promoProductClz: 'GATE', // 促销产品类型
      promoRuleData: null, // 促销规则数据
      tabList: [], // 促销产品选项卡
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.queryParam.dealerSn = this.buyerSn
        this.queryParam.promoProductClz = this.promoProductClz
        return queryPromoProductPage(Object.assign(parameter, this.queryParam, { onlineFalg: '1', productType3Flag: '1' })).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            data.list = data.list.filter(item => item != null)
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              data.list[i].salesNums = 1
              // 当前库存数量
              data.list[i].currentStockQty = data.list[i].currentStockQty || 0
              // 产品包装数
              const productPackQty = (data.list[i].productPackQty || data.list[i].productPackQty == 0) ? data.list[i].productPackQty : '--'
              const productUnit = data.list[i].productUnit || '--'
              const productPackQtyUnit = data.list[i].productPackQtyUnit || '--'
              data.list[i].packQtyV = productPackQty + productUnit + '/' + productPackQtyUnit
              if (data.list[i].unitType == 'SL') {
                data.list[i].unitQtyV = data.list[i].unitQty ? (data.list[i].unitQty + data.list[i].productUnit) : '--'
              } else {
                data.list[i].unitQtyV = data.list[i].productPackQty && data.list[i].unitQty ? ((data.list[i].productPackQty * data.list[i].unitQty) + data.list[i].productUnit) : '--'
              }
            }
            this.disabled = false
          }
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '产品编码', dataIndex: 'productCode', width: '140px', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', scopedSlots: { customRender: 'productName' }, align: 'left' },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '150px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '品牌', dataIndex: 'productBrandName', width: '80px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '出库仓库', dataIndex: 'warehouseName', width: '80px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '库存数量', dataIndex: 'currentStockQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'productUnit', width: '60px', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '售价', dataIndex: 'productPrice', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '包装数', dataIndex: 'packQtyV', width: '60px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '起订量', dataIndex: 'unitQtyV', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '下单数量', dataIndex: 'salesNums', scopedSlots: { customRender: 'nums' }, width: '80px', align: 'center', fixed: 'right' },
        { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '60px', align: 'center', fixed: 'right' }
      ]
      let idx = 7
      if (this.$hasPermissions('B_salesEdit_salesPrice')) { // 售价权限
        arr.splice(idx, 0, { title: '售价', dataIndex: 'productPrice', width: '70px', align: 'right', scopedSlots: { customRender: 'productPrice' } })
        arr.splice(idx + 1, 0, { title: '价格级别', dataIndex: 'priceLevelDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } })
        idx = idx + 2
      }
      arr.splice(idx + 1, 0, { title: '起订量', dataIndex: 'unitQtyV', width: '60px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      return arr
    }
  },
  watch: {
    advanced (a, b) {
      this.tableHeight = window.innerHeight - (a ? 375 : 330)
    }
  },
  methods: {
    // 加载仓库
    loadWarehouse (sn) {
      this.defaultWarehouseSn = sn
      this.queryParam.warehouseSn = sn
      if (this.buyerSn) {
        this.resetSearchForm()
      }
    },
    // 切换tab
    changeTab (e) {
      // 促销阶梯
      if (e.indexOf('GIFT-') >= 0) {
        this.promoProductClz = e.split('-')[0]
        this.queryParam.scopeLevel = e.split('-')[1]
      } else {
        this.promoProductClz = e
      }
      this.resetSearchForm()
    },
    // 双击列表添加产品
    handleClickRow (record) {
      const _this = this
      return {
        on: {
          dblclick: (event) => {
            _this.handleAdd(record)
          }
        }
      }
    },
    // 查询
    searchForm () {
      if (this.queryParam.warehouseSn) {
        this.$refs.table.refresh(true)
      } else {
        this.$message.info('请选择仓库')
      }
    },
    // 重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productOrigCode = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.productType = []
      this.queryParam.warehouseSn = this.defaultWarehouseSn
      this.$refs.table.refresh(true)
    },
    // 页面初始化
    pageInit (data, promo) {
      this.buyerSn = data.buyerSn
      this.promoRuleData = promo.promotionRule
      this.queryParam.dealerLevel = data.buyerLevel
      this.queryParam.promoRuleSn = promo.promoRuleSn
      this.queryParam.salesPromoSn = promo.salesPromoSn

      // 是否是买产品送产品
      const isMcpScp = this.promoRuleData && this.promoRuleData.promotionRuleType == 'BUY_PROD_GIVE_PROD'
      // 是否买产品送采购额
      const isMcpScge = this.promoRuleData.promotionRuleType == 'BUY_PROD_GIVE_MONEY' && this.promoRuleData.scopeFlag === '1'
      // 阶梯
      const giveRuleList = this.promoRuleData && this.promoRuleData.giveRuleList
      // 选项卡数据
      const tabList = []
      if (this.promoRuleData) {
        if (this.promoRuleData.gateFlag === '1') {
          tabList.push({ text: '门槛产品', val: 'GATE' })
        }
        if (this.promoRuleData.promotionRuleType != 'PROMO_PROD') {
          tabList.push({ text: '正价产品', val: 'REGULAR' })
        }
        if (this.promoRuleData.regularPromotionSameFlag === '0' || this.promoRuleData.scopeFlag === '0' || isMcpScge) {
          // 阶梯促销产品
          if (giveRuleList && isMcpScp) {
            giveRuleList.forEach(giveRule => {
              const levelText = '(阶梯' + giveRule.scopeLevel + ')'
              tabList.push({ text: '促销产品' + levelText, val: 'GIFT-' + giveRule.scopeLevel })
            })
          } else {
            tabList.push({ text: '促销产品', val: 'GIFT' })
          }
        }
        if (this.promoRuleData.promotionRuleType == 'PROMO_PROD') {
          tabList.push({ text: '特价产品', val: 'DISCOUNT' })
        }
      }
      this.tabList = tabList
      this.promoProductClz = tabList[0].val
      this.tableHeight = window.innerHeight - 330
      this.resetSearchForm()
    },
    // 刷新当前页面
    resetCurForm () {
      const _this = this
      _this.$nextTick(() => {
        _this.$refs.table.refresh()
      })
    },
    // 添加产品
    handleAdd (row) {
      this.$emit('add', row, this.promoProductClz)
    },
    // 选择产品分类  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>
<style lang="less" scoped>
  .productInfoList-wrap{
    /deep/ .ant-tabs-bar{
      margin-bottom: 5px!important;
    }
  }
</style>
