<template>
  <div class="productInfoList-wrap">
    <!-- 搜索条件 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchTable">
        <a-row :gutter="15">
          <a-col :md="4" :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="4" :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="4" :sm="24">
            <a-form-item label="是否促销品">
              <v-select
                code="FLAG"
                id="productInfoList-promoFlag"
                v-model="queryParam.promoFlag"
                allowClear
                placeholder="请选择是否"
              ></v-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :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="4" :sm="24">
            <a-form-item label="出库仓库">
              <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn"></chooseWarehouse>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24" style="margin-bottom: 10px;">
            <a-button type="primary" class="button-info" @click="searchTable" :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>
   
    <!-- alert -->
    <div style="margin-bottom: 10px;display: flex;align-items: center;" v-if="detailData">
      <div style="display: flex;align-items: center;">
        <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>
        <span style="margin-left: 10px;" v-if="selectedRowKeys.length">已选 {{ selectedRowKeys.length }} 项</span>
      </div>
      <div style="padding-left: 20px;">
        总销售数量：<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>；
        <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>
    </div>
    
    <a-spin :spinning="spinning" tip="Loading...">
        <ve-table
              border-y
              v-show="!showEmpty"
              :scroll-width="0"
              :max-height="tableHeight"
              :show-header="showTableHead"
              :row-style-option="{clickHighlight: true}"
              :cellSelectionOption="{enable: false}"
              :virtual-scroll-option="{enable: true}"
              :columns="columns"
              :table-data="dataSource"
              row-key-field-name="id"
              :cell-style-option="cellStyleOption"
              :cell-span-option="cellSpanOption"
              :column-width-resize-option="columnWidthResizeOption"
              :checkbox-option="checkboxOption"
            />
        <div v-show="showEmpty" class="empty-data">暂无数据</div>
    </a-spin>

  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { salesPromoQueryList } from '@/api/salesNew'
import { salesDetailAllList, salesPromoDetailCount, salesDetaiCount } from '@/api/salesDetailNew'
import { STable, VSelect } from '@/components'
import chooseWarehouse from '@/views/common/chooseWarehouse'
export default {
  name: 'QueryPart',
  mixins: [commonMixin],
  components: { STable, VSelect, chooseWarehouse },
  props: {
    newLoading: {
        type: Boolean,
        default: false
    },
    maxHeight:{
          type: [String,Number],
          default: '300'
        },
    showHeader: {
        type: Boolean,
        default: true
    }
  },
  data () {
    return {
      advanced: true, // 高级搜索 展开/关闭
      productType: [],
      salesBillSn: '',
      detailData: null,
      queryParam: {
        ptype: '0', // 类型
        productCode: '', //  产品编码
        productName: '', //  产品名称
        promoFlag: undefined, //  是否促销品
        brandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        salesBillSn: '',
        warehouseSn: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      activeList: [], // 活动列表
      spinning: false,
      dataSource: [],
      tableHeight: this.maxHeight,
      cellStyleOption: {
        bodyCellClass: ({ row, column, rowIndex }) => {
            if (row.id.indexOf('promo-')>=0 && column.field === "no") {
                return "table-body-cell-no";
            }
        },
      },
      columnWidthResizeOption: {
          // default false
          enable: true,
          // column resize min width
          minWidth: 50
      },
      cellSpanOption: {
          bodyCellSpan: this.bodyCellSpan,
      },
      showEmpty: false,
      showTableHead: true,
      disableSelectedRowKeys: [],
      selectedRowKeys: [],
      colspanNums: 16
    }
  },
  computed: {
    checkboxOption () {
      return {
          disableSelectedRowKeys: this.disableSelectedRowKeys,
          selectedRowKeys: this.selectedRowKeys,
          // 行选择改变事件
          selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
            this.selectedRowChange({ row, isSelected, selectedRowKeys })
          },
          // 全选改变事件
          selectedAllChange: ({ isSelected, selectedRowKeys }) => {
            this.selectedAllChange({ isSelected, selectedRowKeys })
          },
      }
    },
    columns () {
      const _this = this
          const priceFormat = function(data){
            return _this.toThousands(data) || '--'
          }
          const numsFormat = function(data){
            return data || data == 0 ? data : '--'
          }
          const codeFormat = function(record,data,h){
            let ftext = ''
            let fcolor = ''
            if(record.promotionFlag == 'GIFT'){
              ftext = '促'
              fcolor = '#52c41a'
            }
            // if(record.promotionFlag == 'REGULAR'){
            //   ftext = '正'
            //   fcolor = '#108ee9'
            // }
            if(record.promotionFlag == 'DISCOUNT'){
              ftext = '特'
              fcolor = '#faad14'
            }
            return (
                    <div>
                        <span style="padding-right: 15px;">{data}</span>
                        {ftext?(<a-badge count={ftext} number-style={{ backgroundColor: fcolor, zoom:'80%' }}></a-badge>):''}
                        {Number(record.stockQty||0) < Number(record.unpushedQty||0)?(<a-badge count="缺" number-style={{ zoom:'80%' }}></a-badge>):''}
                    </div>
                )
          }
      // 输入框
      const inputFormat = function(record,data,h) {
        if(record.surplusQty>0){
          return (
            <div>
              <a-input-number
                size="small"
                value={record.cancelNums}
                onChange={e => _this.cancelNumsChange(e,record)}
                precision={0}
                min={0}
                max={record.surplusQty}
                style="width: 100%;"
                placeholder="请输入" />
            </div>
          )
        }
        return '--'
      }
      // 操作按钮
      const actionFormat = function(record,data,h) {
        if(record.surplusQty>0){
          return (
            <div>
               <a-button
                size="small"
                type="link"
                class="button-info"
                onClick={()=>_this.handleAdd(record)}
                >添加</a-button>
            </div>
          )
        }
        return '--'
      }
      // 编号，并且格式化活动分类行
      const noFormat = function(record,data,h){
        return (
          <div>
            {record.id.indexOf('promo-')>=0 ? (
              <div class="active-title">
                {record.promo?(
                  <div>
                    <strong style="margin-right:10px;font-size:14px;">{record.promo.promotion.title} ({record.promo.promotionRule.description})</strong>
                    <span style="margin-left:10px;color:#00aaff;cursor: pointer;" onClick={()=>_this.showDesc(record)}>
                      <a-icon title="查看活动详情" type="eye"/> 活动详情
                    </span>
                  </div>
                ):(<div></div>)}
                <div>
                    款数：<strong>{record.total&&record.total.totalCategory||'--'}</strong>；
                    数量：<strong>{record.total&&record.total.totalQty||'--'}</strong>；
                    {_this.$hasPermissions('B_salesEdit_salesPrice') ? (<span>总金额：<strong>{record.total&&record.total.totalAmount||'--'}</strong>；</span>):('')}
                </div>
              </div>
            ):(<span>{data}</span>)}
          </div>
        )
      }

      let arr= [
            { title: "", field: "", key: "acheck", type: "checkbox", align: "center" },
            { title: '序号', field: 'no',key: "a", width: 50, align: 'center', operationColumn: false,renderBodyCell: ({ row, column, rowIndex }, h) => { return noFormat(row,row[column.field],h)} },
            { title: '产品编码', field: 'productCode',key: "b", width: 150, align: 'center',operationColumn: false,renderBodyCell: ({ row, column, rowIndex }, h) => { return codeFormat(row,row[column.field],h)} },
            { title: '产品名称', field: 'productName',key: "c", width: 250, align: 'center',operationColumn: false , ellipsis: { showTitle: true },renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--'}},
            { title: '原厂编码', field: 'productOrigCode',key: "d", width: 150, align: 'center',operationColumn: false,ellipsis: { showTitle: true },renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--'} },
            { title: '出库仓库', field: 'warehouseName',key: "e", width: 100, align: 'center',operationColumn: false,renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--'}}
        ]
      this.colspanNums = 6
      if (this.$hasPermissions('B_salesDispatch_salesPrice')) { //  售价权限
        this.colspanNums = this.colspanNums + 1
        arr.push({ title: '销售价', field: 'price', width: 80,key: "f", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row[column.field])} })
      }
      if (this.$hasPermissions('B_salesDispatch_costPrice')) {
        this.colspanNums = this.colspanNums + 1
        arr.push({ title: '成本价', field: 'showCost', width: 80,key: "g", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row[column.field])} })
      }    
      this.colspanNums = this.colspanNums + 8
      arr = arr.concat([
          { title: '单位', field: 'productOrigUnit',key: "i", width: 80, align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--'}},
          { title: '可用库存', field: 'stockQty', width: 80,key: "j", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} },
          { title: '销售数量', field: 'qty', width: 80,key: "k", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} },
          { title: '已取消', field: 'cancelQty', width: 80,key: "o", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} },
          { title: '已下推', field: 'pushedQty', width: 80,key: "p", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} },
          { title: '待下推', field: 'surplusQty', width: 80,key: "q", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} },
          { title: '取消数量', field: 'surplusQty', width: 80,key: "r", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return inputFormat(row,row[column.field],h)} },
          { title: '操作', field: 'action', width: 80,key: "s", align: 'center',fixed: 'right',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return actionFormat(row,row[column.field],h)} },
        ])
      
      return arr
    }
  },
  methods: {
    //  产品分类  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] : ''
    },
    // 合并活动分类单元格
    bodyCellSpan({ row, column, rowIndex }) {
      if (row.id.indexOf('promo-')>=0) {
        if(column.field=='no'){
          return {
                    rowspan: 1,
                    colspan: this.colspanNums,
                };
        }else{
          return {
                rowspan: 0,
                colspan: 0,
            }
        }
      }
    },
    cancelNumsChange(v,record){
      record.cancelNums = v
      this.dataSource.splice()
    },
    // 选择单元格
    selectedRowChange({ row, isSelected, selectedRowKeys }){
      // console.log(row, isSelected, selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    // 全选行
    selectedAllChange({ isSelected, selectedRowKeys }){
      // console.log(isSelected, selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    // 获取销售单参与的活动列表
    getActiveList(){
      salesPromoQueryList({ salesBillSn: this.salesBillSn }).then(res => {
        if(res.status == 200){
          this.activeList = res.data || []
        }
        this.$nextTick(()=>{
          this.searchTable()
        })
      })
    },
    async searchTable(){
        this.selectedRowKeys = []
        this.disableSelectedRowKeys = []
        this.dataSource = []
        this.disabled = true
        this.spinning = true
        this.queryParam.salesBillSn = this.salesBillSn
        this.queryParam.showStock = true
        const params = this.queryParam
        // 正常产品
        const proList = await salesDetailAllList(params).then(res => res.data)
        const norTotal = await salesDetaiCount(params).then(res => res.data)
        let listData = [{
            id: 'promo-normal',
            total: norTotal
          },...proList]
        
        // 循环获取活动产品
        const active = this.activeList
        for(let i=0;i<active.length;i++){
          const promo = active[i]
          const activeParams = {
            promoRuleSn: promo.promoRuleSn,
            promoSn: promo.promoSn,
            salesPromoSn: promo.salesPromoSn,
            ...params
          }
          
          // 获取活动产品列表
          const aclist = await salesDetailAllList(activeParams).then(res => res.data)
          // 获取活动产品统计
          const acTotal = await salesPromoDetailCount(activeParams).then(res => res.data)
          const retList = [{
            id: 'promo-'+i,
            promo: promo,
            total: acTotal
          },...aclist]
          listData = aclist&&aclist.length ? listData.concat(retList) : listData
        }

        console.log(listData)
        this.dataSource = listData

        // 格式化数据
        let f = 0
        this.dataSource.map((item,i) => {
          if(item.id.indexOf('promo-')>=0){f = f - 1}
          item.no = i + 1 + f
          const productCode = (item.productEntity && item.productEntity.code) || (item.dealerProductEntity && item.dealerProductEntity.code)
          const productName = (item.productEntity && item.productEntity.name) || (item.dealerProductEntity && item.dealerProductEntity.name)
          const productOrigCode = (item.productEntity && item.productEntity.origCode) || (item.dealerProductEntity && item.dealerProductEntity.origCode)
          const productOrigUnit = (item.productEntity && item.productEntity.unit) || (item.dealerProductEntity && item.dealerProductEntity.unit)
          item.productCode = productCode || '--'
          item.productName = productName || '--'
          item.productOrigCode = productOrigCode == ' ' ? '--' : productOrigCode
          item.productOrigUnit = productOrigUnit || '--'
          item.cancelNums = item.surplusQty
          // 库存为0或待下推数为0，不可添加
          if(!item.surplusQty || item.surplusQty<0){
            this.disableSelectedRowKeys.push(item.id)
          }
        })
        this.showEmpty = this.dataSource.length <= 0
        this.tableHeight = (this.showEmpty ? 200 : this.maxHeight) + 'px'
        this.spinning = false
        this.disabled = false
    },
    //  重置
    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.dataSource = []
      this.clearSelectTable()
      this.searchTable()
    },
    pageInit (salesBillSn, detailData) {
      this.salesBillSn = salesBillSn
      this.detailData = detailData
      // 获取活动列表
      this.getActiveList()
    },
    // 清空选项
    clearSelectTable () {
       this.selectedRowKeys = []
    },
    // 添加
    handleAdd (row) {
      if (row.stockQty > 0) { //  可用库存大于0才可添加
        this.$emit('addProduct', [row.salesBillDetailSn])
      } else {
        this.$message.warning('库存为0，不可添加！')
      }
    },
    // 批量添加
    handlePlAdd () {
      const _this = this
      const chooseList = this.selectedRowKeys
      if (chooseList.length == 0) {
        _this.$message.warning('请先选择产品！')
        return
      }
      const chooseRow = this.dataSource.filter(item => chooseList.includes(item.id) && item.id.indexOf('promo-')<0)
      const obj = []
      chooseRow && chooseRow.map(item => {
        if (item.stockQty > 0) {
          obj.push(item.salesBillDetailSn)
        }
      })
       
      this.$confirm({
        title: '提示',
        content: '确认要批量添加到待下推列表吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.$emit('addProduct', obj)
        }
      })
    },
    // 批量取消
    handlePlCancel () {
      const _this = this
      const chooseList = this.selectedRowKeys
      if (chooseList.length == 0) {
        _this.$message.warning('请先选择产品！')
        return
      }
      const chooseRow = this.dataSource.filter(item => chooseList.includes(item.id) && item.id.indexOf('promo-')<0)
      const obj = []
      chooseRow && chooseRow.map(item => {
        obj.push({
          'cancelQty': item.cancelNums,
          'salesBillDetailSn': item.salesBillDetailSn
        })
      })

      this.$emit('cancelProduct', obj)
    }
  }
}
</script>
<style lang="less">
    .empty-data{
        color: #999;
        text-align: center;
        padding: 20px;
    }
  .ve-table-body-td{
    .active-title{
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      background: #f3f8fa;
    }
  }
  .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-body-tr td.table-body-cell-no, 
  .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-expand-tr td.table-body-cell-no{
    padding: 0;
  } 
</style>