<template>
  <a-drawer
    :zIndex="zIndex"
    :title="title"
    placement="right"
    :visible="isShow"
    :width="width"
    :get-container="false"
    :wrap-style="{ position: 'absolute' }"
    @close="onCancel"
    wrapClassName="outStock-modal"
  >
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="outStock-con">
        <div>
          <div ref="searchBox" class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchForm">
              <a-row type="flex" :gutter="12" justify="start">
                <a-col flex="auto">
                  <a-form-item label="产品编码">
                    <a-input id="productInfoList-code" v-model.trim="queryParam.code" allowClear placeholder="请输入产品编码"/>
                  </a-form-item>
                </a-col>
                <a-col flex="auto">
                  <a-form-item label="产品名称">
                    <a-input id="productInfoList-name" v-model.trim="queryParam.name" allowClear placeholder="请输入产品名称"/>
                  </a-form-item>
                </a-col>
                <a-col flex="250px">
                  <a-form-item label="产品分类">
                    <ProductType id="productInfoList-productType" placeholder="请选择产品分类" :isDealer="true" @change="changeProductType" v-model="productType"></ProductType>
                  </a-form-item>
                </a-col>
                <a-col flex="250px">
                  <a-form-item label="产品品牌">
                    <ProductBrand id="productInfoList-productBrandSn" placeholder="请选择产品品牌" v-model="queryParam.productBrandSn"></ProductBrand>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col flex="auto">
                  <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>
          <div class="actions-buttons">
            <a-button
              type="primary"
              ghost
              id="outStock-save"
              @click="handleSave"
              style="padding: 0 20px;">批量添加</a-button>
            <span style="font-weight: bold;margin-left:15px;" v-if="rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length">已选：{{ rowSelectionInfo&&rowSelectionInfo.selectedRowKeys.length }}个</span>
          </div>
          <!-- 列表 -->
          <s-table
            class="sTable"
            ref="table"
            size="small"
            :rowKey="(record) => record.productSn"
            rowKeyName="productSn"
            :row-selection="{ columnWidth: 40 }"
            :scroll="{ y:tableHeight, x: 1000 }"
            @rowSelection="rowSelectionFun"
            :data="loadData"
            :defaultLoadData="false"
            :columns="columns"
            :pageSize="30"
            bordered>
          </s-table>
        </div>
      </div>
      </div>
    </a-spin>
  </a-drawer>
</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 {}
      }
    },
    width: {
      type: [String, Number],
      default: '70%'
    },
    zIndex: {
      type: Number,
      default: 1050
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      tableHeight: 0,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: '240px', align: 'center', customRender: function (text) { return text || '--' }, fixed: 'left' },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '320px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '上次采购数量', dataIndex: 'qty', width: '180px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '上次缺货数量', dataIndex: 'cancelQty', width: '180px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: '80px', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      title: '',
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return purchaseDetailCancelList(Object.assign(parameter, { dealerProductEntity: this.queryParam })).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      spinning: false,
      rowSelectionInfo: null,
      productType: [],
      queryParam: { //  查询条件
        code: '', //  产品编码
        name: '', //  产品名称
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      }
    }
  },
  methods: {
    setTableH () {
      this.$nextTick(() => {
        const searchBoxH = this.$refs.searchBox.offsetHeight
        this.tableHeight = window.innerHeight - searchBoxH - 340
      })
    },
    //  产品分类  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] : ''
    },
    // 表格选中项
    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 rows = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
      const list = []
      rows.map(item => {
        list.push({
          cancelQty: item.cancelQty,
          qty: item.qty,
          productSn: item.productSn,
          price: item.price
        })
      })

      const params = {
        confirm: false,
        purchaseBillSn: this.paramsData.purchaseBillSn,
        purchaseBillNo: this.paramsData.purchaseBillNo,
        purchaseBillDetailEntityList: list
      }
      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, params)
          } else if (res.data.productSizeRepeat == res.data.productSize) {
            content = `抱歉，您选择的 ${res.data.productSize} 个产品，采购单中已经全部存在，无需加入！`
            this.$info({
              title: '提示',
              content: content,
              okText: '好的',
              centered: true,
              zIndex: 1100,
              onOk () {
                _this.$refs.table.clearSelected() // 清空表格选中项
              }
            })
          } else {
            content = `您已经选择 ${res.data.productSize} 个产品，上次缺货数量将作为本次采购数量。确认加入本次采购吗？`
            this.confirmFun(content, params)
          }
        }
      })
    },
    confirmFun (content, params) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: content,
        okText: '确认加入',
        cancelText: '重新选择',
        centered: true,
        closable: true,
        zIndex: 1100,
        onOk () {
          _this.spinning = true
          params.confirm = true
          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() // 清空表格选中项
        }
      })
    },
    onCancel () {
      this.$emit('close')
      this.$refs.table.clearSelected() // 清空表格选中项
    },
    searchForm () {
      this.$refs.table.refresh(true)
    },
    resetSearchForm () {
      this.queryParam = {
        productBrandSn: undefined,
        code: '', //  产品编码
        name: '', //  产品名称
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '' //  产品三级分类
      }
      this.productType = []
      this.$refs.table.refresh(true)
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    },
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.onCancel()
      } else {
        setTimeout(() => {
          this.setTableH()
        }, 200)
        this.resetSearchForm()
        this.title = '上次采购缺货产品明细（采购单号：' + this.paramsData.purchaseBillNo + '）'
      }
    }
  }
}
</script>

<style lang="less">
  .outStock-modal{
    .ant-drawer-header{
      padding: 13px 20px;
    }
    .ant-drawer-body{
      padding: 15px 20px;
      height: calc(100% - 50px);
    }
    .outStock-con{
      .actions-buttons{
        padding: 10px 0;
      }
    }
  }
</style>
