<template>
  <div class="cumulativeProductList-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="客户名称">
              <dealerSubareaScopeList ref="dealerSubareaScopeList" id="cumulativeProductList-buyerName" @change="custChange" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="产品编码">
              <a-input id="cumulativeProductList-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="cumulativeProductList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-item label="产品名称">
                <a-input id="cumulativeProductList-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="cumulativeProductList-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="cumulativeProductList-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品分类">
                <ProductType id="cumulativeProductList-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="cumulativeProductList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" id="cumulativeProductList-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" size="small" v-if="tabList&&tabList.length">
      <a-tab-pane v-for="item in tabList" :key="item.val" :tab="item.text"></a-tab-pane>
    </a-tabs>
    <div class="table-operator">
      <a-button type="primary" @click="handleAdd">批量添加</a-button>
      <span v-if="selectTotal" style="margin-left:10px;">已选{{ selectTotal }}项，数量合计{{ selectCount.totalNum }}个，售价小计合计{{ toThousands(selectCount.totalPrice) }}元</span>
    </div>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="small"
      :rowKey="(record) => record.borrowDetailSn"
      rowKeyName="borrowDetailSn"
      :columns="columns"
      :data="loadData"
      :row-selection="{ columnWidth: 40 }"
      @rowSelection="rowSelectionFun"
      :scroll="{ y: tableHeight, x: 1040 }"
      :pagination="{pageSizeOptions: ['10','20','30','50','100','300','500']}"
      :defaultLoadData="false"
      :pageSize="50"
      bordered>
    </s-table>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { salesDetailQueryBorrowPageList } from '@/api/salesNew'
import ProductType from '@/views/common/productType.js'
import ProductBrand from '@/views/common/productBrand.js'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import { STable, VSelect } from '@/components'
export default {
  name: 'CumulativeQueryPart',
  mixins: [commonMixin],
  components: { STable, VSelect, ProductBrand, ProductType, dealerSubareaScopeList },
  props: {
    newLoading: Boolean
  },
  data () {
    return {
      advanced: false, // 高级搜索 展开/关闭
      showSetting: false, // 设置弹框
      productType: [], // 产品类型
      buyerSn: '', // 客户sn
      queryParam: { //  查询条件
        buyerSn: undefined, //  客户名称
        productCode: '', //  产品编码
        salesBillNo: '', // 销售单号
        productName: '', //  产品名称
        productOrigCode: '', //  原厂编码
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        promoProductClz: 'GATE' // 促销产品类型
      },
      tableHeight: 300, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      promoRuleData: null, // 促销规则数据
      tabList: [], // 促销产品选项卡
      rowSelectionInfo: null, // 已选择
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return salesDetailQueryBorrowPageList(Object.assign(parameter, this.queryParam, { onlineFalg: '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
              // 产品包装数
              const productPackQty = (data.list[i].packQty || data.list[i].packQty == 0) ? data.list[i].packQty : '--'
              const productUnit = data.list[i].productEntity.unit || '--'
              const productPackQtyUnit = data.list[i].packQtyUnit || '--'
              data.list[i].packQtyV = productPackQty + productUnit + '/' + productPackQtyUnit
            }
            this.disabled = false
          }
          return data
        })
      }
    }
  },
  computed: {
    // 已选产品数量
    selectTotal () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length || 0
    },
    // 数量合计、售价小计
    selectCount () {
      let totalNum = 0
      let totalPrice = 0
      if (this.rowSelectionInfo && this.rowSelectionInfo.selectedRows.length) {
        this.rowSelectionInfo.selectedRows.forEach(item => {
          totalNum += item.qty
          totalPrice += item.totalAmount
        })
      }
      return { totalNum, totalPrice }
    },
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', dataIndex: 'borrowBillNo', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: '11%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品编码', dataIndex: 'productCode', width: '150px', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productEntity.origCode', width: '150px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '品牌', dataIndex: 'productEntity.productBrandName', width: '70px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'productEntity.unit', width: '50px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '包装数', dataIndex: 'packQtyV', width: '50px', 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 : '--') } }
      ]
      const idx = 7
      if (this.$hasPermissions('B_salesEdit_salesPrice')) { // 售价权限
        arr.splice(idx, 0, { title: '售价', dataIndex: 'price', width: '70px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(idx + 1, 0, { title: '价格级别', dataIndex: 'priceLevelDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } })
        arr.push({ title: '售价小计', dataIndex: 'totalAmount', width: '5%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  watch: {
    advanced (a, b) {
      this.tableHeight = window.innerHeight - (a ? 413 : 368)
    }
  },
  methods: {
    // 选择客户
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 切换tab
    changeTab (e) {
      this.queryParam.promoProductClz = e
      this.resetSearchForm()
      // 清空表格选中项
      this.$refs.table.clearSelected()
      // this.rowSelectionInfo = null
    },
    // 查询
    searchForm () {
      this.$refs.table.refresh(true)
    },
    // 重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.salesBillNo = ''
      this.queryParam.productOrigCode = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.productType = []
      this.queryParam.buyerSn = undefined
      this.$refs.dealerSubareaScopeList.resetForm()
      this.$refs.table.refresh(true)
    },
    // 页面初始化
    pageInit (data, promo) {
      this.promoRuleData = promo.promotionRule
      this.queryParam.salesBillSn = data.salesBillSn
      this.queryParam.salesPromoSn = promo.salesPromoSn
      this.queryParam.promoRuleSn = promo.salesPromoSn
      // 选项卡数据
      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' })
        }
      }
      this.tabList = tabList
      this.queryParam.promoProductClz = tabList && tabList.length ? tabList[0].val : ''
      this.tableHeight = window.innerHeight - 368
      this.resetSearchForm()
    },
    // 刷新当前页面
    resetCurForm () {
      const _this = this
      _this.$nextTick(() => {
        _this.$refs.table.refresh()
      })
    },
    // 添加产品
    handleAdd () {
      if (this.selectTotal == 0) {
        this.$message.warning('请先选择产品后再进行批量操作！')
        return
      }
      const chooseDataList = this.rowSelectionInfo.selectedRows = this.rowSelectionInfo.selectedRows.map(item => {
        item.borrowFlag = 1
        item.salesBillSn = this.queryParam.salesBillSn
        item.promotionFlag = this.queryParam.promoProductClz
        return item
      })
      this.$emit('add', chooseDataList, this.queryParam.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>
  .cumulativeProductList-wrap{
    /deep/ .ant-tabs-bar{
      margin-bottom: 5px!important;
    }
  }
</style>
