<template>
  <a-drawer
    title="选择产品"
    class="chooseProducts-modal"
    placement="right"
    closable
    :visible="isShow"
    @close="isShow=false"
    width="70%"
  >
    <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"
            :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-code" 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-orignCode" v-model.trim="queryParam.productOrigCode" allowClear placeholder="请输入原厂编码"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-model-item label="产品名称">
                  <a-input id="chooseProducts-name" 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" :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: this.chooseDataList && this.chooseDataList.indexOf(record.productSn) > -1 } })}"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :pagination="{pageSizeOptions: ['20','50','100','200','500']}"
          :data="loadData"
          :defaultLoadData="false"
          style="max-height:650px;"
          :scroll="{ y: 600 }"
          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 { shopPromoProductList } from '@/api/shopPromo'

export default {
  name: 'ChooseProductsModal',
  components: { STable, ProductBrand, productTypeAll },
  mixins: [commonMixin],
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    chooseData: {
      type: Array,
      default: () => {
        return []
      }
    },
    propmSn: {
      type: String,
      default: ''
    }
  },
  data () {
    const _this = this
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      loading: false, //  表格加载中
      isShow: this.openModal, //  是否打开弹框
      // form表单label 布局
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      //  查询条件
      queryParam: {
        productName: '', // 产品名称
        productCode: '', //  产品编码
        productOrigCode: '', //  原厂编码
        productBrandSn: undefined, //  产品品牌
        productType: [], // 产品分类
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      },
      chooseDataList: [], // 已选择被禁用的数据
      columns: [
        { title: '序号', dataIndex: 'no', width: 60, align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', align: 'center' },
        { title: '产品名称', dataIndex: 'productName', align: 'center', width: '18%', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'productOrigCode', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '商城售价', dataIndex: 'shopProductPrice', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '终端价', dataIndex: 'terminalPrice', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '品牌', dataIndex: 'productBrandName', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, width: '10%', align: 'center' },
        { title: '包装数', scopedSlots: { customRender: 'productQty' }, align: 'center' },
        { title: '单位', dataIndex: 'unit', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        params.promoSn = this.propmSn
        // 获取列表数据 有分页
        return shopPromoProductList(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
          }
          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.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productOrigCode = ''
      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)
    },
    //  产品分类  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] : ''
    },
    // 禁用
    handleDisabled (list) {
      this.chooseDataList = list
    }
  },
  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()
        if (_this.chooseData && _this.chooseData.length > 0) {
          let selectedRowKeys = _this.chooseData.map(item => {
            return item.goodsSn
            })
          this.$nextTick(() => { // 页面渲染完成后的回调
            _this.$refs.table.setTableSelected(selectedRowKeys, _this.chooseData) // 设置表格选中项
          })
        }
      }
    }
  }
}
</script>

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