<template>
  <a-modal
    centered
    class="bulkWarehousingOrder-product-modal"
    :footer="null"
    :maskClosable="false"
    :title="(itemSn ? '编辑' : '新增') + '产品'"
    v-model="isShow"
    @cancel="isShow=false"
    :width="800">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="bulkWarehousingOrder-product-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
        @keyup.enter.native="handleSave">
        <a-form-model-item label="供应商" prop="supplierSn">{{ (nowData&&nowData.supplierName) || '--' }}</a-form-model-item>
        <a-form-model-item label="产品编码" :prop="!itemSn?'productSn':''">
          <a-select
            show-search
            id="bulkWarehousingOrder-product-productSn"
            ref="productSn"
            v-if="!itemSn"
            v-model="form.productSn"
            placeholder="请选择"
            :filter-option="false"
            :not-found-content="fetching ? undefined : null"
            :autoFocus="true"
            @search="fetchUser"
            @change="handleChange"
          >
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="item in productData" :key="item.product.productSn + item.product.code" :value="item.product.productSn">{{ item.product.code }}</a-select-option>
          </a-select>
          <span v-else>{{ form.productCode }}</span>
        </a-form-model-item>
        <a-form-model-item label="产品名称" prop="productName">{{ form.productName || '--' }}</a-form-model-item>
        <a-form-model-item label="原厂编码" prop="productOrigCode">{{ form.productOrigCode || '--' }}</a-form-model-item>
        <a-form-model-item label="仓库仓位" prop="warehouseLocationSn">
          {{ (nowData&&nowData.warehouseName) || '--' }} >
          <a-select
            id="bulkWarehousingOrder-product-warehouse"
            @change="changeWarehouseCascade"
            placeholder="请选择仓位"
            :allowClear="false"
            style="width: 50%;"
            v-model="form.warehouseLocationSn">
            <a-select-option v-for="item in warehouseCascadeData" :value="item.sn">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="成本价">
          <span style="margin-right:20px;">{{ form.productCost ? toThousands(form.productCost) : '--' }}</span>
          <a-checkbox v-if="productCost||isGift" :disabled="!!itemSn" v-model="isGift">是否为赠品</a-checkbox>
        </a-form-model-item>
        <a-form-model-item label="数量" prop="productQty">
          <a-input-number
            id="bulkWarehousingOrder-product-productQty"
            ref="productQty"
            v-model="form.productQty"
            :precision="0"
            :min="1"
            :max="99999999"
            placeholder="请输入"
            style="width: 50%;margin-right:20px;" /><span>个</span>
        </a-form-model-item>
        <div class="btn-cont">
          <a-button id="bulkWarehousingOrder-product-modal-back" @click="isShow = false" style="margin-right: 15px;">取消</a-button>
          <a-button type="primary" id="bulkWarehousingOrder-product-modal-save" @click="handleSave">{{ itemSn?'保存':'保存并新增' }}</a-button>
        </div>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect } from '@/components'
import debounce from 'lodash/debounce'
import { supplierProductList } from '@/api/supplier'
import { warehouseCascadeList } from '@/api/warehouse'
import { sparePartsSaveDetail, sparePartsDetailD } from '@/api/spareParts'
export default {
  name: 'BulkWarehousingOrderBasicInfoModal',
  mixins: [commonMixin],
  components: { VSelect },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemSn: {
      type: [Number, String],
      default: ''
    },
    nowData: {
      type: Object,
      default: () => {
        return null
      }
    }
  },
  data () {
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 16 }
      },
      form: {
        supplierSn: '', // 供应商
        productSn: undefined,
        productName: '',
        productCode: '',
        productOrigCode: '',
        warehouseSn: '',
        warehouseLocationSn: undefined,
        productCost: '',
        productQty: ''
      },
      productCost: '',
      rules: {
        productSn: [
          { required: true, message: '请选择产品编码', trigger: 'change' }
        ],
        warehouseLocationSn: [
          { required: true, message: '请选择仓位', trigger: 'change' }
        ],
        productCost: [
          { required: true, message: '该产品没有设置成本价', trigger: 'blur' }
        ],
        productQty: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ]
      },
      fetching: false,
      productData: [],
      warehouseCascadeData: [], //  仓库仓位  下拉数据
      warehouseSnBackups: '', //  仓库备份数据
      warehouseLocationSnBackups: '', //  仓位备份数据
      isGift: false
    }
  },
  methods: {
    // 搜索产品
    fetchUser (value) {
      this.fetching = true
      const params = {
        product: {
          code: value
        },
        supplierSn: this.nowData.supplierSn,
        pageNo: 1,
        pageSize: 20
      }
      supplierProductList(params).then(res => {
        if (res.status == 200) {
          this.productData = res.data && res.data.list ? res.data.list : []
          this.fetching = false
        } else {
          this.productData = []
          this.fetching = false
        }
      })
    },
    // 产品编码  change
    handleChange (value) {
      const ind = this.productData.findIndex(item => item.productSn == value)
      this.form.productName = this.productData[ind].product.name
      this.form.productCode = this.productData[ind].product.code
      this.form.productOrigCode = this.productData[ind].product.origCode
      this.form.productCost = this.productData[ind].cost
      this.productCost = this.form.productCost
      this.form.productQty = ''
      this.isGift = false
      this.$refs.productQty.focus()
      this.$refs.ruleForm.validate()
    },
    // 详情
    getDetail () {
      this.spinning = true
      sparePartsDetailD({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.form = Object.assign(this.form, data)
          this.warehouseSnBackups = this.form.warehouseSn || undefined
          this.warehouseLocationSnBackups = this.form.warehouseLocationSn || undefined
          this.isGift = this.form.giftFlag == 1
        }
        this.spinning = false
      })
    },
    //  保存
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          form.sparePartsSn = this.nowData.sparePartsSn
          form.sparePartsNo = this.nowData.sparePartsNo
          form.supplierSn = this.nowData.supplierSn
          form.giftFlag = this.isGift ? 1 : 0
          if (!_this.itemSn) {
            delete form.id
            delete form.sparePartsDetailSn
            if (!this.productCost) {
              _this.$message.warning('该产品没有设置成本价！')
              return false
            }
          }
          _this.spinning = true
          sparePartsSaveDetail(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.$emit('ok', res.data)
                _this.spinning = false
                if (!_this.itemSn) {
                  _this.resetData()
                  _this.$refs.productQty.blur()
                  _this.$refs.productSn.focus()
                } else {
                  _this.isShow = false
                }
              })
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    changeWarehouseCascade (val) {
      this.$refs.productQty.focus()
      this.$refs.ruleForm.validate()
    },
    //  仓库仓位  级联  列表
    getWarehouseCascade () {
      const _this = this
      warehouseCascadeList({}).then(res => {
        if (res.status == 200) {
          // 默认仓库
          const defSn = this.isShowWarehouse ? this.nowData.warehouseSn : this.defWarehouse && this.defWarehouse.warehouseSn
          _this.form.warehouseSn = defSn
          _this.warehouseSnBackups = defSn
          const data = res.data.find(item => item.warehouseSn == defSn)
          // 默认仓库下的仓位列表
          if (data && data.warehouseLocationList) {
            data.warehouseLocationList.map(subItem => {
              subItem.sn = subItem.warehouseLocationSn
              // 取默认仓位
              if (subItem.defaultFlag == 1) {
                _this.form.warehouseLocationSn = subItem.warehouseLocationSn
                _this.warehouseLocationSnBackups = subItem.warehouseLocationSn
              }
            })
            // 仓库仓位树数据
            this.warehouseCascadeData = data.warehouseLocationList
          } else {
            this.warehouseCascadeData = []
          }
        } else {
          this.warehouseCascadeData = []
        }
      })
    },
    resetData () {
      this.$refs.ruleForm.resetFields()
      this.form = {
        supplierSn: '', // 供应商
        productSn: undefined,
        productName: '',
        productCode: '',
        productOrigCode: '',
        warehouseSn: this.warehouseSnBackups,
        warehouseLocationSn: this.warehouseLocationSnBackups,
        productCost: '',
        productQty: ''
      }
      this.productCost = ''
      this.isGift = false
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetData()
        this.warehouseSnBackups = ''
        this.warehouseLocationSnBackups = ''
      } else {
        this.getWarehouseCascade()
      }
    },
    itemSn (newValue, oldValue) {
      if (this.isShow && newValue) {
        this.getDetail()
      }
    },
    isGift (newValue, oldValue) {
      if (newValue) {
        this.form.productCost = 0
      } else {
        this.form.productCost = this.productCost
      }
    }
  }
}
</script>

<style lang="less">
  .bulkWarehousingOrder-product-modal{
    .ant-modal-body {
      padding: 40px 40px 24px;
      .ant-form-item{
        margin-bottom: 10px;
      }
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
  }
</style>
