<template>
  <a-modal
    centered
    :footer="null"
    :maskClosable="false"
    title="促销品列表"
    v-model="isShow"
    @cancle="cansel"
    width="80%">
    <a-card size="small" :bordered="false" class="productInfoList-wrap">
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onChange,
          onSelect: onSelectChange,
          onSelectAll: onSelectAllChange,
          getCheckboxProps: record => ({
            props: {
              disabled: record.cost == undefined||record.cost==0||record.productPrice==0||record.productPrice==undefined, // Column configuration not to be checked
            }
          })
        }"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :defaultLoadData="false"
        :scroll="{ x: 900, y: 350 }"
        bordered>
        <!-- 销售数量 -->
        <template slot="salesNums" slot-scope="text, record">
          <a-input-number
            size="small"
            :max="999999"
            :min="1"
            v-model="record.qty"
            :precision="0"
            :step="1"
          />
        </template>
      </s-table>
      <div style="display: flex;justify-content: center;padding: 10px 0;">
        <a-button
          size="large"
          type="primary"
          :loading="newLoading"
          class="button-primary"
          @click="handleSubmit"
          style="padding: 0 60px;">
          确定
        </a-button>
        <a-button size="large" :loading="newLoading" style="padding: 0 60px;margin-left: 15px;font-size: 12px;" @click="cansel">
          取消
        </a-button>
      </div>
    </a-card>
  </a-modal>
</template>

<script>
import { STable, VSelect } from '@/components'
import { getPromoGoodsList } from '@/api/salesDetail'
export default {
  name: 'ChooseProduct',
  components: { STable, VSelect },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    newLoading: Boolean
  },
  data () {
    return {
      isShow: this.openModal,
      selectedRowKeys: [], // Check here to configure the default column
      selectedRows: [],
      spinning: false,
      list: [],
      salesBillDetailSn: null,
      buyerSn: '',
      nowData: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        return getPromoGoodsList(Object.assign(parameter, { salesBillDetailSn: this.nowData.salesBillDetailSn || undefined, buyerSn: this.buyerSn })).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            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].qty = 1
              data.list[i].promotionSourceSn = this.nowData.salesBillDetailSn
            }
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '产品编码', dataIndex: 'code', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'name', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '原售价', dataIndex: 'productPrice', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '促销价', dataIndex: 'promoRuleGoods.goodsPrice', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '数量', dataIndex: 'qty', scopedSlots: { customRender: 'salesNums' }, width: 100, align: 'center' },
        { title: '单位', dataIndex: 'unit', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '促销类型', dataIndex: 'promoRuleGoods.promoRuleTypeName', width: 100, align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (this.$hasPermissions('B_isShowCost')) { // 成本价权限
        arr.splice(2, 0, { title: '成本价', dataIndex: 'cost', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      if (this.$hasPermissions('B_isShowPrice')) { // 售价权限
        const ind = this.$hasPermissions('B_isShowCost') ? 3 : 2
        arr.splice(ind, 0, { title: '原售价', dataIndex: 'productPrice', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(ind + 1, 0, { title: '促销价', dataIndex: 'promoRuleGoods.goodsPrice', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  methods: {
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelectChange (record, selected, selectedRows, nativeEvent) {
      if (selected) { //  选择
        this.selectedRows.push(record)
      } else { //  取消
        this.selectedRows = selectedRows
      }
    },
    // 本页全选/取消全选
    onSelectAllChange (selected, selectedRows, changeRows) {
      const _this = this
      if (selected) { //  选择
        this.selectedRows = [...this.selectedRows, ...changeRows]
      } else { //  取消
        const arrId = []
        this.selectedRows.map((item, index) => {
          this.selectedRows.map((subItem, ind) => {
            if (item.id == subItem.id) {
              arrId.push(index)
            }
          })
        })
        arrId.map((item, index) => {
          _this.selectedRows = _this.selectedRows.slice(item, item + 1)
        })
      }
    },
    // 选择产品
    handleSubmit () {
      const _this = this
      if (_this.selectedRowKeys.length < 1) {
        _this.$message.warning('请选择促销品！')
        return
      }
      const obj = []
      _this.selectedRows.map(item => {
        obj.push({
          showCost: item.cost,
          price: item.promoRuleGoods.goodsPrice,
          origPrice: item.productPrice,
          packQty: item.packQty,
          productSn: item.productSn,
          promotionSourceSn: item.promotionSourceSn,
          promotionActivitySn: item.promoRuleGoods.promoActiveSn,
          promotionActivityName: item.promoRuleGoods.promoActiveName,
          promotionRules: item.promoRuleGoods.promoRuleSn,
          promoGoodsType: item.promoRuleGoods.promoGoodsType,
          qty: item.qty,
          promotableFlag: 0, // 可促销标记 有活动的传1，没活动的传0
          promotionFlag: 1 // 促销标记 正品传0，促销品传1
        })
      })
      _this.$emit('ok', obj)
    },
    cansel () {
      this.$emit('close')
    },
    getData (data, buyerSn) {
      const _this = this
      _this.buyerSn = buyerSn
      _this.nowData = data
      setTimeout(() => (
        _this.$refs.table.refresh(true)
      ), 300)
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.selectedRows = []
        this.selectedRowKeys = []
        this.$emit('close')
      }
    }
  }
}
</script>
