<template>
  <a-modal
    centered
    class="outStock-modal"
    :footer="null"
    :maskClosable="false"
    :title="title"
    v-model="isShow"
    @cancel="isShow=false"
    :width="800">
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="outStock-con">
        <div>
          <div ref="tableSearch" class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchForm">
              <a-row :gutter="15">
                <a-col :md="8" :sm="24">
                  <a-form-item label="产品编码">
                    <a-input id="productInfoList-code" v-model.trim="queryParam.dealerProductEntity.code" allowClear placeholder="请输入产品编码"/>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="产品名称">
                    <a-input id="productInfoList-name" v-model.trim="queryParam.dealerProductEntity.name" allowClear placeholder="请输入产品名称"/>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="产品分类">
                    <ProductType id="productInfoList-productType" placeholder="请选择产品分类" :isDealer="true" @change="changeProductType" v-model="productType"></ProductType>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="产品品牌">
                    <ProductBrand id="productInfoList-productBrandSn" placeholder="请选择产品品牌" v-model="queryParam.dealerProductEntity.productBrandSn"></ProductBrand>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24" style="margin-bottom: 10px;">
                  <a-button type="primary" @click="searchForm" :disabled="disabled" id="productInfoList-refresh">查询</a-button>
                  <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="productInfoList-reset">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <p style="font-weight: bold;">当前已选：{{ rowSelectionInfo&&rowSelectionInfo.selectedRowKeys?rowSelectionInfo.selectedRowKeys.length:0 }}个</p>
          <!-- 列表 -->
          <s-table
            class="sTable"
            ref="table"
            size="small"
            :rowKey="(record) => record.productSn"
            rowKeyName="productSn"
            :row-selection="{ columnWidth: 40 }"
            @rowSelection="rowSelectionFun"
            :data="loadData"
            :columns="columns"
            :scroll="{ y: 450 }"
            bordered>
          </s-table>
        </div>
        <!-- 按钮 -->
        <div class="btn-con">
          <a-button
            type="primary"
            id="outStock-save"
            size="large"
            class="button-primary"
            @click="handleSave"
            style="padding: 0 36px;">批量添加</a-button>
          <a-button
            id="outStock-cancel"
            size="large"
            class="button-cancel"
            @click="isShow=false"
            style="padding: 0 60px;margin-left: 15px;">取消</a-button>
        </div>
      </div>
      </div></a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable } from '@/components'
import { purchaseDetailCancelList, purchaseDetailCancelSave } from '@/api/purchaseDetail'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
export default {
  name: 'OutStockModal',
  components: { STable, ProductType, ProductBrand },
  mixins: [commonMixin],
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    chooseData: {
      type: Array,
      default: () => {
        return []
      }
    },
    paramsData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: '24%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '32%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '上次采购数量', dataIndex: 'qty', width: '18%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '上次缺货数量', dataIndex: 'cancelQty', width: '18%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: '8%', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      title: '',
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return purchaseDetailCancelList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.disabled = false
          }
          this.spinning = false
          const purchaseBillNo = data && data.list.length > 0 ? data.list[0].purchaseBillNo : '--'
          this.title = '上次采购缺货产品明细（采购单号：' + purchaseBillNo + '）'
          return data
        })
      },
      spinning: false,
      rowSelectionInfo: null,
      productType: [],
      dataList: [],
      queryParam: { //  查询条件
        dealerProductEntity: {
          code: '', //  产品编码
          name: '', //  产品名称
          productBrandSn: undefined, //  产品品牌
          productTypeSn1: '', //  产品一级分类
          productTypeSn2: '', //  产品二级分类
          productTypeSn3: '' //  产品三级分类
        }
      }
    }
  },
  methods: {
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.dealerProductEntity.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.dealerProductEntity.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.dealerProductEntity.productTypeSn3 = val[2] ? val[2] : ''
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 保存
    handleSave () {
      const _this = this
      if (!this.rowSelectionInfo || (this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        this.$message.warning('请在列表勾选后再进行操作！')
        return
      }
      const params = {
        confirm: false,
        purchaseBillSn: this.paramsData.purchaseBillSn,
        purchaseBillNo: this.paramsData.purchaseBillNo,
        purchaseBillDetailEntityList: this.rowSelectionInfo && this.rowSelectionInfo.selectedRows
      }
      purchaseDetailCancelSave(params).then(res => {
        if (res.status == 200 && res.data) {
          let content = ''
          if ((res.data.productSizeRepeat != res.data.productSize) && (res.data.productSizeRepeat != 0)) {
            content = `您已经选择 ${res.data.productSize} 个产品，其中 ${res.data.productSizeRepeat} 个产品已经存在于采购单中。本次只会加入不重复的产品，上次缺货数量将作为本次采购数量。确认加入本次采购吗？`
            this.confirmFun(content)
          } else if (res.data.productSizeRepeat == res.data.productSize) {
            content = `抱歉，您选择的 ${res.data.productSize} 个产品，采购单中已经全部存在，无需加入！`
            this.$info({
              title: '提示',
              content: content,
              okText: '好的',
              centered: true,
              onOk () {
                _this.$refs.table.clearSelected() // 清空表格选中项
              }
            })
          } else {
            content = `您已经选择 ${res.data.productSize} 个产品，上次缺货数量将作为本次采购数量。确认加入本次采购吗？`
            this.confirmFun(content)
          }
        }
      })
    },
    confirmFun (content) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: content,
        okText: '确认加入',
        cancelText: '重新选择',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          const params = {
            confirm: true,
            purchaseBillSn: _this.paramsData.purchaseBillSn,
            purchaseBillNo: _this.paramsData.purchaseBillNo,
            purchaseBillDetailEntityList: _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows
          }
          purchaseDetailCancelSave(params).then(res => {
            if (res.status == 200) {
              _this.$emit('ok')
              _this.isShow = false
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        },
        onCancel () {
          _this.$refs.table.clearSelected() // 清空表格选中项
        }
      })
    },
    searchForm () {
      this.$refs.table.refresh(true)
    },
    resetSearchForm () {
      const info = {
        productBrandSn: undefined,
        code: '', //  产品编码
        name: '', //  产品名称
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      }
      Object.assign(this.queryParam.dealerProductEntity, info)
      this.productType = []
      this.$refs.table.refresh(true)
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.$refs.table.clearSelected() // 清空表格选中项
      }
    }
  }
}
</script>

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