<template>
    <!-- 已选配件列表 -->
    <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"
          />
        <div v-show="showEmpty" class="empty-data"><a-empty description="暂无产品" :image="simpleImage"/></div>
        <!-- 活动规则详情 -->
        <detailModal :openModal="openDetailModal" :itemSn="detailSn" @close="closeDetailModal"></detailModal>
    </a-spin>
  </template>
  
  <script>
    import { commonMixin } from '@/utils/mixin'
    import { Empty } from 'ant-design-vue';
    import detailModal from '@/views/promotionRulesManagement/dealerPromotions/detailModal.vue'
    import { salesPromoQueryList } from '@/api/salesNew'
    import { salesDetailAllList, salesPromoDetailCount, salesDetaiCount } from '@/api/salesDetailNew'
    export default {
      name: 'DetailProductList',
      mixins: [commonMixin],
      components: { detailModal },
      props: {
        newLoading: Boolean,
        detailData: {
          type: Object,
          default: function(){return null}
        },
        promo: {
          type: Object,
          default: function(){return null}
        },
        id: {
          type: String,
          default: ''
        },
        warehouseSn: {
          type: String,
          default: ''
        },
        promoFlag: {
          type: String,
          default: ''
        },
        salesBillSn: {
          type: String,
          default: ''
        },
        showCityPrice: {
            type: Boolean,
            default: false
        },
        authCode: {
          type: String,
          default: ''
        },
        maxHeight:{
          type: [String,Number],
          default: '300'
        },
        showHeader: {
            type: Boolean,
            default: true
        }
      },
      data () {
        return {
          spinning: false,
          openDetailModal: false,
          detailSn: null,
          activeList: [], // 活动列表
          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,
          },
          isCityPrice: false,
          outStockStr: '',
          showEmpty: false,
          showTableHead: true,
          colspanNums: 13,
          hasOutStockOfActive: false,
          simpleImage: Empty.PRESENTED_IMAGE_SIMPLE
        }
      },
      computed: {
        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 == 'GATE'){
              ftext = '槛'
              fcolor = '#108ee9'
            }
             
            return (
                    <div>
                        <span style="padding-right: 15px;">{data}</span>
                        {ftext?(<a-badge count={ftext} number-style={{ backgroundColor: fcolor, zoom:'80%' }}></a-badge>):''}
                        {record.convertPromoGiftsFlag == '1'?(<a-badge count="转" number-style={{ backgroundColor: '#ffaa00', zoom:'80%' }}></a-badge>):''}
                        {(Number(record.stockQty||0) < Number(record.unpushedQty||0)) && _this.showStock?(<a-badge count="缺" number-style={{ zoom:'80%' }}></a-badge>):''}
                    </div>
                )
          }
          // 编号，并且格式化活动分类行
          const noFormat = function(record,data,h){
            return (
              <div>
                {record.id.indexOf('promo-')>=0 ? (
                  <div class="active-title">
                    {record.promo?(
                      <div>
                        <strong style="font-size:14px;">{record.promo.promotion.description}</strong>
                        <span>({record.promo.promotionRule.description})</span>
                        <span style="margin-left:20px;color:#00aaff;cursor: pointer;" onClick={()=>_this.showDesc(record.promo)}>
                          <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>):('')}
                        {_this.$hasPermissions('B_salesEdit_salesPrice')&&record.promo&&record.total&&record.total.lossAmount ? (<span>优惠金额：<strong>{record.total.lossAmount}</strong>；</span>):('')}
                        {_this.$hasPermissions('B_salesEdit_salesPrice')&&record.promo&&record.total&&record.total.cgejyAmount>0 ? (<span>采购额结余：<strong>{_this.toThousands(record.total.cgejyAmount)}</strong>；</span>):('')}
                        {_this.$hasPermissions('B_salesEdit_salesPrice')&&record.promo&&record.total&&record.total.cgejyAmount<0 ? (<span>采购额超出：<strong>{_this.toThousands(record.total.cgeccAmount)}</strong>；</span>):('')}
                        {_this.$hasPermissions('B_salesEdit_salesPrice')&&record.promo&&record.total&&record.total.convertPromoGiftsAmount ? (<span>转采购额金额：<strong>{_this.toThousands(record.total.convertPromoGiftsAmount)}</strong>；</span>):('')}
                        {record.total&&record.total.expenseAccountFlag!='WAIT' ? (<span style="color:red;">{record.total.expenseAccountFlagDictValue}</span>) : ''}
                    </div>
                  </div>
                ):(<span>{data}</span>)}
              </div>
            )
          }
          // 显示折扣价
          const discountPriceFormat = function(record,data,h) {
            return (
              <div>
                {_this.toThousands(data)}
                {record.promotionFlag == 'GIFT' || record.promotionFlag == 'DISCOUNT' ? (
                  <span title="原价">（{ _this.toThousands(record.origPrice)}）</span>
                ):''}
              </div>
            )
          }

          let arr= [
                { 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: 'left',operationColumn: false,renderBodyCell: ({ row, column, rowIndex }, h) => { return codeFormat(row,row[column.field],h)} },
                { title: '产品名称', field: 'productName',key: "c", width: 250, align: 'left',operationColumn: false , ellipsis: { showTitle: true },renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--'}},
                { title: '原厂编码', field: 'productOrigCode',key: "d", width: 150, align: 'left',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 = 5
            if (this.$hasPermissions(this.authCode + '_costPrice')) { //  成本价权限
              this.colspanNums = this.colspanNums + 1
              arr.push({ title: '成本价', field: 'showCost', width: 80,key: "f", align: 'right',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row[column.field])} })
            }
            this.colspanNums = this.colspanNums + 2
            arr = arr.concat([
                { title: '单位', field: 'productOrigUnit',key: "g", width: 80, align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--'}},
                { title: '销售数量', field: 'qty', width: 80,key: "h", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} }
            ])

            if (this.$hasPermissions(this.authCode + '_provincePrice')) {
              this.colspanNums = this.colspanNums + 1
              arr.push({ title: '省级价', field: 'provincePrice', width: 80,key: "i", align: 'right',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row[column.field])} })
            }
            // 是否勾选市级价格
            if (this.isCityPrice) {
              this.colspanNums = this.colspanNums + 1
                arr.push({ title: '市级价', field: 'cityPrice', width: 80,key: "j", align: 'right',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row[column.field])} })
                if (this.$hasPermissions(this.authCode + '_salesPrice')) { //  售价权限
                  this.colspanNums = this.colspanNums + 1
                    arr.push({ title: '销售价', field: 'price', width: 100,key: "k", align: 'right',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return discountPriceFormat(row,row[column.field],h)} })
                }
            } else {
                if (this.$hasPermissions(this.authCode + '_salesPrice')) { //  售价权限
                  this.colspanNums = this.colspanNums + 1
                    arr.push({ title: '销售价', field: 'price', width: 100,key: "l", align: 'right',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return discountPriceFormat(row,row[column.field],h)} })
                }
            }

            if (this.showStock) { //  审核，需用到库存
              this.colspanNums = this.colspanNums + 1
                arr.push({ title: '库存', field: 'stockQty', width: 80,key: "m", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} })
            }
            this.colspanNums = this.colspanNums + 3
            arr = arr.concat([
                { title: '待下推数', field: 'unpushedQty', 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])} },
            ])
            
            if(this.hasConvertPromoGifts){
              arr.push({ title: '转采购额数量', field: 'convertPromoGiftsQty', width: 100,key: "z", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} })
            }
            arr.push({ title: '已取消数', field: 'cancelQty', width: 80,key: "q", align: 'center',operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field])} })
          return arr
        },
        hasConvertPromoGifts(){
          return this.detailData && this.detailData.totalConvertPromoGiftsQty
        },
        showStock(){
            return this.detailData && (this.detailData.billStatus == 'WAIT_AUDIT' || this.detailData.billStatus == 'HQ_CHANGE') && this.$hasPermissions('B_salesAudit')
        }
      },
      watch: {
        showCityPrice(newValue, oldValue){
            this.isCityPrice = newValue
        }
      },
      methods: {
        // 关闭详情弹窗
        closeDetailModal () {
          this.detailSn = null
          this.openDetailModal = false
        },
         // 合并活动分类单元格
        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,
                }
            }
          }
        },
         // 查看活动详情
        showDesc(row){
          this.detailSn = row.promoRuleSn
          this.openDetailModal = true
        },
        // 获取销售单参与的活动列表
        pageInit(){
          salesPromoQueryList({ salesBillSn: this.salesBillSn }).then(res => {
            if(res.status == 200){
              this.activeList = res.data || []
            }
            this.$nextTick(()=>{
              this.searchTable()
            })
          })
        },
        async searchTable(){
            this.dataSource = []
            this.disabled = true
            this.spinning = true
            // 参数
            const params = {
                salesBillSn: this.salesBillSn,
                showStock: this.showStock,
                warehouseSn: this.warehouseSn,
                promotionFlag: this.promoFlag == '' ? undefined : this.promoFlag
            }
            const active = this.activeList.filter(item => item.enabledFlag == 1)

            // 正常产品
            const hasSearchNormal = !params.promotionFlag || params.promotionFlag == 0
            const proList = hasSearchNormal ? await salesDetailAllList(params).then(res => res.data) : []
            const norTotal = hasSearchNormal ? await salesDetaiCount(params).then(res => res.data) : null
            // 没有活动时，表格不显示统计数据
            let listData = active.length ? (proList.length ? [{
                id: 'promo-normal',
                total: norTotal
              },...proList] : []) : proList
            
            if(params.promotionFlag != 0){  
              // 循环获取活动产品
              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 acTotal = await salesPromoDetailCount(activeParams).then(res => res.data)
                if(acTotal){
                  // 采购额结余
                  acTotal.cgejyAmount = Number(acTotal.totalPromoGiftsAmount||0) - Number(acTotal.totalUsePromoGiftsAmount||0)
                  // 采购额超出
                  acTotal.cgeccAmount = Number(acTotal.totalUsePromoGiftsAmount||0) - Number(acTotal.totalPromoGiftsAmount||0)
                }
                // 有数据时才调用接口，避免做无用的调用
                if(acTotal&&acTotal.totalQty){
                  // 获取活动产品列表
                  const aclist = await salesDetailAllList(activeParams).then(res => res.data)
                  
                  const retList = aclist.length ? [{
                    id: 'promo-'+i,
                    promo: promo,
                    total: acTotal
                  },...aclist] : []
                  // 将活动产品数据拼接
                  listData = aclist&&aclist.length ? listData.concat(retList) : listData
                }
              }
              console.log(listData)
              // 如果活动没有任何产品，不显示统计一行
              if(active.length){
                const hasAcp = listData.filter(item => item.id!='promo-normal').filter(item => item.id.indexOf("promo-")>=0)
                if(hasAcp && hasAcp.length==0){
                  listData = listData.filter(item => item.id.indexOf("promo-")<0) || []
                }
              }
            }
            console.log(listData)
            this.dataSource = listData
            
            // 格式化数据
            let f = 0
            this.outStockStr = ''
            let str = ''
            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.epushedQty = Number(item.pushedQty) - Number(item.pushQty)
              if (item.unpushedQty && (Number(item.stockQty) < Number(item.unpushedQty))) {
                  str += item.productCode + '、'
                  if(item.promotionFlag != 0){
                    this.hasOutStockOfActive = true
                  }
              }
            })
            if (str.length > 0) {
                str = str.substr(0, str.length - 1)
                this.outStockStr = '产品编号为：' + str + '的产品库存不足；'
            }
            this.showEmpty = this.dataSource.length <= 0
            this.tableHeight = (this.showEmpty ? 200 : this.maxHeight) + 'px'
            this.spinning = false
            this.disabled = false
        },
      }
    }
  </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;
    } 
    .ve-table .ve-table-container .ve-table-content-wrapper{
      border-bottom: 1px solid #ddd;
    }
  </style>