<template>
  <!-- 已选配件列表 -->
  <a-spin :spinning="spinning" tip="Loading...">
    <div :style="{position:'relative',background:'#fff'}">
      <div style="height:10px;" v-if="type!='normal'"></div>
      <ve-table
        border-y
        border-x
        border-around
        :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"
        :column-width-resize-option="columnWidthResizeOption"
        :cell-style-option="cellStyleOption"
      />
      <div v-show="showEmpty" class="empty-data"><a-empty description="暂无产品" :image="simpleImage"/></div>
    </div>
    <!-- 总计 -->
    <div v-if="countData&&activeList.length>0" style="padding:6px 0 0;text-align: right;">
      总款数：<strong>{{ countData&&(countData.totalCategory || countData.totalCategory==0) ? countData.totalCategory : 0 }}</strong>；
      总数量：<strong>{{ countData&&(countData.totalQty || countData.totalQty==0) ? countData.totalQty : 0 }}</strong>；
      <span v-if="$hasPermissions(authCode + '_salesPrice')||showPrice">总金额：<strong>{{ countData&&(countData.totalAmount || countData.totalAmount==0) ? toThousands(countData.totalAmount) : '0.00' }}</strong>；</span>
    </div>
    <!-- 活动规则详情 -->
    <detailModal :openModal="openDetailModal" pageType="salesPage" :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 { salesDetailAllList, salesDetailExtPromoList, salesDetaiCount } from '@/api/salesDetailNew'
export default {
  name: 'DetailProductList',
  mixins: [commonMixin],
  components: { detailModal },
  props: {
    newLoading: Boolean, // loading
    detailData: { // 详情信息
      type: Object,
      default: function () { return null }
    },
    // 正常 or 活动 产品列表
    type: {
      type: String,
      default: 'normal'
    },
    // 活动规则详情
    promo: {
      type: Object,
      default: function () { return null }
    },
    // 表格id
    id: {
      type: String,
      default: ''
    },
    // 仓库sn
    warehouseSn: {
      type: String,
      default: ''
    },
    // 是否促销产品
    promoFlag: {
      type: String,
      default: ''
    },
    // 销售单sn
    salesBillSn: {
      type: String,
      default: ''
    },
    // 是否显示城市价格
    showCityPrice: {
      type: Boolean,
      default: false
    },
    // 是否显示平均公斤单价
    showAveragePrice: {
      type: Boolean,
      default: false
    },
    // 权限码
    authCode: {
      type: String,
      default: ''
    },
    // 最大高度
    maxHeight: {
      type: [String, Number],
      default: '300'
    },
    // 是否显示表格头部
    showHeader: {
      type: Boolean,
      default: true
    },
    activeList: { // 参与的活动列表
      type: Array,
      default: () => []
    },
    transferQty: {// 发货经销商库存是否满足
      type: [String, Number],
      default: ''
    },
    borrowFlag: { // 是否累计产品
      type: [String, Number],
      default: ''
    },
    chooseList: { // 发货经销商库存
      type: Array,
      default: function () { return [] }
    },
    showTransferDealer: {// 显示发货经销商库存
      type: Boolean,
      default: true
    },
    // 已勾选的活动sn
    salesPromoSnSet: {
      type: Array,
      default: () => []
    },
    pageType: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      openDetailModal: false, // 活动规则详情弹框
      detailSn: null, // 活动规则详情sn
      dataSource: [], // 列表原始数据
      tableHeight: this.maxHeight, // 表格高度
      // 表格列可拖曳
      columnWidthResizeOption: {
        // default false
        enable: true,
        // column resize min width
        minWidth: 50
      },
      cellStyleOption: {
        headerCellClass: ({ column, rowIndex }) => {
          if (column.align != 'center') {
            return 'table-header-cell-center'
          }
        }
      },
      isCityPrice: false, // 是否显示市级价
      outStockStr: '', // 产品库存不足提示信息
      showEmpty: false, // 是否显示空数据图片
      showTableHead: true, // 是否显示表格头部
      hasOutStockOfActive: false, // 产品是否存在缺货
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE, // 空图片
      showStockCol: false, // 显示第三方库存
      hasJGtire: false, // 是否轮胎产品
      countData: null
    }
  },
  computed: {
    // 转单和上级审核显示价格
    showPrice () {
      return this.pageType == 'salesNewDetailTransfer' || this.pageType == 'salesNewDetaiSupLevelAudit'
    },
    columns () {
      const _this = this
      // 价格单元格
      const priceFormat = function (data) {
        return _this.toThousands(data) || '--'
      }
      // 数字单元格
      const numsFormat = function (data) {
        return data || data == 0 ? data : '--'
      }
      // 发货经销商库存
      const transferDealerInfo = function (record, data, h) {
        return (
          <div>
            {(!data || data && data * 1 < record.qty * 1) ? <span style="color:#ed1c24;">{data || '--'}</span> : <span>{data}</span>}
          </div>)
      }
      // 编码
      const codeFormat = function (record, data, h) {
        return (
          <div>
            <span style="padding-right: 10px;">{data}</span>
            {record.promotionFlag.indexOf('GIFT') >= 0 ? <a-badge count="促" numberStyle={{ backgroundColor: '#52c41a', zoom: '0.7' }}/> : ''}
            {record.convertPromoGiftsQty ? (<a-badge count="转" numberStyle={{ backgroundColor: '#ffaa00', zoom: '0.7' }}></a-badge>) : ''}
            {record.promotionFlag.indexOf('GATE') >= 0 ? <a-badge count="槛" numberStyle={{ backgroundColor: '#108ee9', zoom: '0.7' }}/> : ''}
            {record.promotionFlag.indexOf('REGULAR') >= 0 ? <a-badge count="正" numberStyle={{ backgroundColor: '#ff5500', zoom: '0.7' }}/> : ''}
            {record.promotionFlag.indexOf('DISCOUNT') >= 0 ? <a-badge count="特" numberStyle={{ backgroundColor: '#faad14', zoom: '0.7' }}/> : ''}
            {(Number(record.stockQty || 0) < Number(record.unpushedQty || 0)) && _this.showStock ? <a-badge count="缺" numberStyle={{ zoom: '0.7' }}/> : ''}
          </div>
        )
      }
      // 显示折扣价
      const discountPriceFormat = function (record, data, h) {
        return (
          <div>
            {_this.toThousands(data)}
            {record.promotionFlag.indexOf('GIFT') >= 0 || record.promotionFlag.indexOf('DISCOUNT') >= 0 ? (
              <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 row[column.field] || '--' } },
        { title: '产品编码', field: 'productCode', key: 'b', width: 120, align: 'left', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return codeFormat(row, row[column.field], h) } },
        { title: '产品名称', field: 'productName', key: 'c', width: 180, align: 'left', operationColumn: false, ellipsis: { showTitle: true }, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '原厂编码', field: 'productOrigCode', key: 'd', width: 120, 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] || '--' } }
      ]
      // 如果是活动产品列表
      if (this.type == 'active') {
        arr.splice(3, 0, {
          title: '规则数量',
          field: 'rulesNums',
          key: '4',
          width: 60,
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              row.promoRuleSnList
                ? <a-popover placement="right">
                  <template slot="content">
                    {row.promoRuleSnList.map(item => {
                      return (
                        <div
                          id={'dispacth-ruleDetail-' + row.productSn}
                          title="点击查看详情"
                          style="padding:5px 0;cursor: pointer;"
                          onClick={() => _this.showRuleDetail(item)}
                        >{ _this.activeRuleFilter(item, row) }</div>
                      )
                    })}
                  </template>
                  <a-button type="link" id={'dispacth-ruleSn-' + row.productSn} size="small" class="button-info">
                    {row.promoRuleNum}<span style="zoom:0.6;color: #666;">个∨</span>
                  </a-button>
                </a-popover> : '--'
            )
          }
        })
      }
      // 计算可合并单元格数
      if (this.$hasPermissions(this.authCode + '_costPrice') || this.showPrice) { //  成本价权限
        arr.push({ title: '成本价', field: 'showCost', width: 80, key: 'f', align: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row[column.field]) } })
      }
      arr = arr.concat([
        { title: '单位', field: 'productOrigUnit', key: 'g', width: 70, 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.showPrice) {
        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) {
        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.showPrice) { //  售价权限
          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.showPrice) { //  售价权限
          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) {
        arr.push({ title: '库存', field: 'stockQty', width: 80, key: 'm', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row.borrowFlag != '1' ? numsFormat(row[column.field]) : '--' } })
        if (this.showStockCol) {
          arr.push({ title: '第三方库存', field: 'thirdStockQty', width: 80, key: 'mm', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row.borrowFlag != '1' ? numsFormat(row[column.field]) : '--' } })
        }
      }
      if (this.showTransferDealer && this.type == 'normal') {
        arr.push({ title: '发货经销商库存', field: 'transferDealerStockQty', width: 100, key: 'tt', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return transferDealerInfo(row, row[column.field], h) } })
      }
      arr = arr.concat([
        { title: '待下推数', field: 'unpushedQty', width: 80, key: 'o', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row.borrowFlag != '1' ? numsFormat(row[column.field]) : '--' } },
        { title: '已下推数', field: 'pushedQty', width: 80, key: 'p', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row.borrowFlag != '1' ? numsFormat(row[column.field]) : '--' } }
      ])

      arr.push({ title: '已取消数', field: 'cancelQty', width: 80, key: 'q', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row.borrowFlag != '1' ? numsFormat(row[column.field]) : '--' } })
      if (this.showAveragePrice) {
        this.colspanNums = this.colspanNums + 4
        arr.push({ title: '单重（kg）', field: 'weightKg', width: 80, key: 'q1', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } })
        arr.push({ title: '合计重量（kg）', field: 'totalWeightKg', width: 98, key: 'q2', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } })
        if (this.$hasPermissions(this.authCode + '_costPrice') || this.showPrice) {
          arr.push({ title: '平均成本公斤单价', field: 'weightAvgCost', width: 105, key: 'q3', align: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } })
        }
        if (this.$hasPermissions(this.authCode + '_salesPrice') || this.showPrice) {
          arr.push({ title: '平均售价公斤单价', field: 'weightAvgPrice', width: 105, key: 'q4', align: 'right', 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
    },
    salesPromoSnSet (newValue, oldValue) {
      this.searchTable()
    }
  },
  methods: {
    // 参与规则名称
    activeRuleFilter (val, data) {
      const row = this.activeList.length && this.activeList.find(item => item.promoRuleSn == val)
      const rule = data.salesPromoDetailList.find(item => item.promoRuleSn == val)
      return row ? (row.promotionRule.promotionRuleTypeDictValue + '-' + row.promotion.description + '(' + row.promotionRule.description + ')') + (data.borrowFlag != 1 ? '，起订量：' + rule.promoUnit : '') : ''
    },
    // 查看参与规则详情
    showRuleDetail (promoRuleSn) {
      this.detailSn = promoRuleSn
      this.openDetailModal = true
    },
    // 关闭详情弹窗
    closeDetailModal () {
      this.detailSn = null
      this.openDetailModal = false
    },
    // 获取销售单参与的活动列表
    pageInit () {
      this.searchTable()
    },
    // 显示第三方库存
    showThreeStock (flag) {
      this.showStockCol = flag
      if (flag) {
        this.searchTable()
      }
    },
    // 当满足发货经销商显示条件时  查询
    transferTableData (list) {
      this.dataSource = list.filter(item => this.warehouseSn != '' ? item.warehouseSn == this.warehouseSn : true).filter(item => {
        if (this.transferQty == '0') { // 不满足
          return (!item.transferDealerStockQty || (item.transferDealerStockQty && item.transferDealerStockQty * 1 < item.qty * 1))
        } else if (this.transferQty == '1') { // 满足
          return (item.transferDealerStockQty && item.transferDealerStockQty * 1 >= item.qty * 1)
        } else {
          return true
        }
      })
    },
    // 查询表格数据
    async searchTable () {
      this.dataSource = []
      this.disabled = true
      this.spinning = true
      // 参数
      const params = {
        salesBillSn: this.salesBillSn,
        showStock: this.showStock,
        warehouseSn: this.warehouseSn,
        borrowFlag: this.borrowFlag,
        promotionFlag: this.promoFlag == '' ? undefined : this.promoFlag
      }
      // 查询正常产品
      if (this.type == 'normal') {
        // 转单时
        if (this.chooseList && this.chooseList.length) {
          this.transferTableData(this.chooseList)
        } else {
          // 查询正常产品明细列表
          if (this.promoFlag == 0 || this.promoFlag == undefined) {
            this.dataSource = await salesDetailAllList(params).then(res => res.data || [])
            if (this.activeList.length > 0) {
              this.countData = await salesDetaiCount(params).then(res => res.data)
            }
          }
        }
      } else {
        // 查询活动产品明细列表
        if (this.promoFlag !== '0') {
          this.dataSource = await salesDetailExtPromoList({ salesPromoSnSet: this.salesPromoSnSet, ...params }).then(res => res.data || [])
        }
      }
      this.$emit('hideTable', this.type, this.dataSource.length)

      // 格式化数据
      let str = ''
      this.outStockStr = ''
      this.dataSource.forEach((item, i) => {
        item.no = i + 1
        // 格式化数据，产品编码、产品名称、原厂编码、包装数单位
        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)
        const productBrand = (item.productEntity && item.productEntity.productBrandName) || (item.dealerProductEntity && item.dealerProductEntity.productBrandName)
        const productType3 = (item.productEntity && item.productEntity.productTypeName3) || (item.dealerProductEntity && item.dealerProductEntity.productTypeName3)
        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 (productBrand && productBrand.indexOf('箭冠') >= 0 && productBrand && productType3.indexOf('轮胎') >= 0) {
          this.hasJGtire = true
        }
      })
      // 是否有缺货明细
      if (str.length > 0) {
        str = str.substr(0, str.length - 1)
        this.outStockStr = '产品编号为：' + str + '的产品库存不足；'
      }

      const listLen = this.dataSource.length
      this.showEmpty = listLen <= 0
      // 高度自适应
      if (this.maxHeight == 'auto') {
        this.tableHeight = (listLen + 1) * 34
        this.tableHeight = this.tableHeight > 300 ? 300 : this.tableHeight
      } else {
        this.tableHeight = this.maxHeight
      }
      if (this.showEmpty) {
        this.tableHeight = 200
      }
      this.spinning = false
      this.disabled = false
    }
  }
}
</script>

  <style lang="less" scoped>
    .empty-data{
        color: #999;
        text-align: center;
        width: 100%;
        position: absolute;
        top: 50%;
        margin-top: -50px;
    }
    .table-header-cell-center{
      text-align: center!important;
    }
     .ant-input-number-sm input{
      text-align: center;
     }
    .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;
    }
    /deep/.ve-table-header-th{
      text-align: center !important;
    }
  </style>
