<template>
  <a-drawer
    :zIndex="zIndex"
    title="选择产品"
    placement="right"
    :visible="isShow"
    width="80%"
    :get-container="false"
    :wrap-style="{ position: 'absolute' }"
    :headerStyle="{ padding: '10px' }"
    @close="onClose"
    wrapClassName="chooseProducts-modal">
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="products-con">
        <!-- 搜索条件 -->
        <div class="table-page-search-wrapper">
          <a-form-model
            ref="ruleForm"
            class="form-model-con"
            layout="inline"
            :model="queryParam"
            id="chooseProducts-form"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol">
            <a-row :gutter="15">
              <a-col :md="8" :sm="24">
                <a-form-model-item label="产品编码">
                  <a-input id="chooseProducts-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-model-item label="原厂编码">
                  <a-input id="chooseProducts-origCode" v-model.trim="queryParam.origCode" allowClear placeholder="请输入原厂编码"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-model-item label="产品名称">
                  <a-input id="chooseProducts-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-model-item label="产品分类">
                  <productTypeAll placeholder="请选择产品分类" @change="changeProductType" v-model="queryParam.productType" id="chooseProducts-productType"></productTypeAll>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-model-item label="产品品牌">
                  <ProductBrand id="chooseProducts-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="$refs.table.refresh()" :disabled="disabled" id="chooseProducts-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetData" :disabled="disabled" id="chooseProducts-reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <div style="margin-bottom: 10px">
          <a-button type="primary" ghost id="chooseProducts-add-btn" :loading="loading" @click="handleSave">批量添加</a-button>
          <span style="margin-left: 5px">
            <template v-if="selectCount"> {{ `已选 ${selectCount} 项` }} </template>
          </span>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.productSn"
          rowKeyName="productSn"
          :row-selection="{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: !record.terminalPrice } })}"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :pagination="{pageSizeOptions: ['20','50','100','200','500']}"
          :data="loadData"
          :defaultLoadData="false"
          style="max-height:700px;"
          :scroll="{ y: 550 }"
          bordered>
          <!-- 产品分类 -->
          <template slot="productType" slot-scope="text, record">
            <span v-if="record.productTypeName2 || record.productTypeName3">{{ record.productTypeName2 }} {{ record.productTypeName3 ? '>' : '' }} {{ record.productTypeName3 }}</span>
            <span v-else>--</span>
          </template>
          <!-- 包装数 -->
          <template slot="productQty" slot-scope="text, record">
            <span v-if="record.packQty">
              {{ record.packQty }}{{ record.unit }}/{{ record.packQtyUnit?record.packQtyUnit:'--' }}
            </span>
            <span v-else>--</span>
          </template>
        </s-table>
      </div>
    </a-spin>
  </a-drawer>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable } from '@/components'
import ProductBrand from '@/views/common/productBrand.js'
import productTypeAll from '@/views/common/productTypeAll.js'
// 接口
import { queryWaitingProductPage } from '@/api/promoActive'
export default {
  name: 'ChooseProductsModal',
  components: { STable, ProductBrand, productTypeAll },
  mixins: [commonMixin],
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    chooseData: {// 隐藏选择的产品
      type: Array,
      default: () => {
        return []
      }
    },
    chooseType: {// 选中的分类
      type: Array,
      default: () => {
        return []
      }
    },
    chooseProduct: {// 当前行选中的数据
      type: Array,
      default: () => {
        return []
      }
    },
    itemSn: {// 活动sn
      type: String,
      default: ''
    },
    zIndex: { // 层级
      type: [String, Number],
      default: 1000
    }
  },
  data () {
    const _this = this
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      // form 表单中label布局
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      //  查询条件
      queryParam: {
        productName: '', // 产品名称
        productCode: '', //  产品编码
        origCode: '', // 原厂编码
        productBrandSn: undefined, //  产品品牌
        productType: [], // 产品分类
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        hideProductSnList: [], // 已选中产品数据
        productTypeSnList: []// 已选中分类数据
      },
      disabled: false, //  查询、重置按钮是否可操作
      loading: false, //  表格加载中
      columns: [// 表头
        { title: '序号', dataIndex: 'no', width: 60, align: 'center' },
        { title: '产品编码', dataIndex: 'code', align: 'center', width: '12%' },
        { title: '产品名称', dataIndex: 'name', align: 'left', width: '18%', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'origCode', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '终端价', dataIndex: 'terminalPrice', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        // { title: '市级价', dataIndex: 'cityPrice', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        // { title: '特约价', dataIndex: 'specialPrice', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '品牌', dataIndex: 'productBrandName', align: 'center', width: '8%', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, align: 'center' },
        { title: '包装数', scopedSlots: { customRender: 'productQty' }, width: '6%', align: 'center' },
        { title: '单位', dataIndex: 'unit', align: 'center', width: '6%', ellipsis: true, customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        params.hideProductSnList = this.chooseData
        params.productTypeSnList = this.chooseType
        params.promoActiveSn = this.itemSn
        return queryWaitingProductPage(params).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
            }
            this.disabled = false
            const _this = this
            // 选中回显
            if (_this.chooseProduct && _this.chooseProduct.length > 0) {
              const selectedRows = []
              let selectedRowKeys = []
              data.list.forEach(item => {
                const flag = _this.chooseProduct.includes(item.productSn)
                if (flag) {
                  selectedRows.push(item)
                }
              })
              selectedRowKeys = _this.chooseProduct
              _this.$nextTick(() => { // 页面渲染完成后的回调
                _this.$refs.table.setTableSelected(selectedRowKeys, selectedRows) // 设置表格选中项
              })
            }
          }
          _this.spinning = false
          return data
        })
      },
      rowSelectionInfo: null// 选中数据
    }
  },
  computed: {
    // 计算选中产品条数
    selectCount () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 重置数据
    resetData () {
      this.queryParam.productName = ''
      this.queryParam.productCode = ''
      this.queryParam.origCode = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.productType = []
      this.$nextTick(() => {
        this.$refs.table.refresh(true)
      })
    },
    //  清空选项
    resetSearchForm () {
      this.$refs.table.clearSelected()
    },
    // 批量添加
    handleSave () {
      if (!this.rowSelectionInfo || (this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        this.$message.warning('请在列表勾选后再进行操作！')
        return
      }
      const resultList = JSON.parse(JSON.stringify(this.rowSelectionInfo && this.rowSelectionInfo.selectedRows))
      this.$emit('ok', resultList)
      this.isShow = false
    },
    // 关闭弹框
    onClose () {
      this.isShow = false
      this.$emit('close')
    },
    //  产品分类  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] : ''
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.resetSearchForm()
        this.rowSelectionInfo = null
        this.$emit('close')
      } else {
        const _this = this
        _this.resetData()
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .chooseProducts-modal{
    .products-con{
      .btn-con{
        text-align: center;
        margin: 30px 0 20px;
        .button-cancel{
          font-size: 12px;
        }
      }
    }
  }
</style>
