<template>
  <a-modal
    centered
    class="addProduct-modal"
    :footer="null"
    :maskClosable="false"
    title="新增"
    v-model="isShow"
    @cancel="isShow=false"
    :width="900">
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="products-con">
        <div style="display:flex;align-items: center;padding:10px 0;">
          <div style="font-size:14px;"><span style="color:red;">*</span>供应商名称：</div>
          <div style="flex-grow: 1;">
            <supplier
              id="addProduct-supplier"
              style="width:50%"
              ref="supplier"
              v-model="supplierSn"
              @change="getChoosed"
              placeholder="请输入供应商名称搜索"></supplier>
          </div>
        </div>
        <div style="padding:10px 0;border-bottom: 1px solid #eee;">
          <span style="font-size:14px;">选择产品</span>
          <span style="font-weight: bold;" v-if="rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length">
            （已选：{{ rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length||0 }}个）
          </span>
        </div>
        <div style="padding:15px 0 0;">
          <!-- 搜索条件 -->
          <div class="table-page-search-wrapper">
            <a-form-model
              id="addProduct-form"
              ref="ruleForm"
              class="form-model-con"
              layout="inline"
              :model="queryParam"
              :rules="rules"
              @keyup.enter.native="handleSearch"
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol">
              <a-row :gutter="15">
                <a-col :md="6" :sm="24">
                  <a-form-model-item label="产品编码" prop="code">
                    <a-input id="addProduct-code" v-model.trim="queryParam.code" allowClear placeholder="请输入产品编码"/>
                  </a-form-model-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-model-item label="产品品牌">
                    <ProductBrand id="addProduct-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
                  </a-form-model-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-model-item label="产品分类">
                    <ProductType id="addProduct-productType" placeholder="请选择产品分类" @change="changeProductType" v-model="queryParam.productType"></ProductType>
                  </a-form-model-item>
                </a-col>
                <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                  <a-button type="primary" @click="handleSearch" :disabled="disabled" id="addProduct-refresh">查询</a-button>
                  <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="addProduct-reset">重置</a-button>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
          <!-- 列表 -->
          <s-table
            class="sTable"
            ref="table"
            size="small"
            :rowKey="(record) => record.productSn"
            rowKeyName="productSn"
            :row-selection="{ columnWidth: 40, getCheckboxProps:record =>({props: { disabled: this.chooseData && this.chooseData.indexOf(record.productSn) > -1 }}) }"
            @rowSelection="rowSelectionFun"
            :columns="columns"
            :data="loadData"
            :scroll="{ y: 400 }"
            :defaultLoadData="false"
            bordered>
          </s-table>
        </div>
        <!-- 按钮 -->
        <div class="btn-con">
          <a-button
            id="addProduct-cancel-btn"
            class="button-cancel"
            @click="isShow=false"
            style="padding: 0 30px;margin-right: 15px;">取消</a-button>
          <a-button
            type="primary"
            id="addProduct-save-btn"
            @click="handleSave"
            style="padding: 0 30px;">保存</a-button>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
// 组件
import { STable } from '@/components'
import ProductBrand from '@/views/common/productBrand.js'
import ProductType from '@/views/common/productType.js'
import supplier from '@/views/common/supplier.js'
// 接口
import { productPricingList } from '@/api/product'
import { addProduct, supplierProductSnList } from '@/api/supplier'
export default {
  name: 'AddProductModal',
  components: { STable, supplier, ProductType, ProductBrand },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    type: { //  类型，经销权设置dealership,  供应商添加产品supplier
      type: String,
      default: 'supplier'
    },
    dealerSn: { // 经销商sn
      type: String || Number,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      disabled: false, //  查询、重置按钮是否可操作
      loading: false, //  表格加载中
      // 表单label布局设置
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      supplierSn: undefined, // 供应商sn
      //  查询条件
      queryParam: {
        code: '', //  产品编码
        productBrandSn: undefined, //  产品品牌
        productType: [], // 产品分类默认值
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      },
      // 表单验证规则
      rules: {
        productBrandSn: [ { required: true, message: '请选择产品品牌', trigger: 'change' } ],
        productType: [ { required: true, message: '请选择产品分类', trigger: 'change' } ]
      },
      chooseData: [], // 已选产品
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'code', align: 'center' },
        { title: '产品名称', dataIndex: 'name', 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)
        return productPricingList(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// 表格选中数据
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 查询所有已选sn
    getChoosed () {
      this.spinning = true
      supplierProductSnList({ sn: this.supplierSn }).then(res => {
        if (res.status == 200) {
          this.$refs.table.clearTable()
          this.chooseData = res.data //  包含先前所选产品
          this.handleSearch()
        }
        this.spinning = false
      })
    },
    // 查询
    handleSearch () {
      const _this = this
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (_this.supplierSn) {
            _this.$refs.table.refresh(true)
          } else {
            _this.$message.warning('请先选择供应商！')
          }
        } else {
          return false
        }
      })
    },
    // 重置数据
    resetData () {
      this.queryParam.code = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.productType = []
    },
    //  重置
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    // 保存
    handleSave () {
      const _this = this
      if (!this.supplierSn) {
        this.$message.warning('请先选择供应商！')
        return
      }
      if (!this.rowSelectionInfo || (this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        this.$message.warning('请选择产品！')
        return
      }
      const arr = []
      this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.map(item => {
        if (_this.chooseData.indexOf(item) == -1) {
          arr.push(item)
        }
      })
      if (arr.length) {
        this.addProduct(arr)
      } else {
        this.$message.warning('请选择产品！')
      }
    },
    // 添加产品  数据处理
    addProduct (arr) {
      this.spinning = true
      addProduct({
        supplierSn: this.supplierSn,
        productSnList: arr
      }).then(res => {
        if (res.status == 200) {
          this.$emit('ok')
          this.isShow = false
        }
        this.spinning = false
      })
    },
    //  选择产品分类  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.$emit('close')
        // 重置数据
        this.$refs.table.clearTable()
        this.chooseData = []
        this.supplierSn = undefined
        this.resetData()
      }
    }
  }
}
</script>

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