<template>
  <a-modal
    centered
    class="purchaseReceipt-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="purchaseReceipt-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="purchaseReceipt-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="purchaseReceipt-product-warehouse"
            @change="changeWarehouseCascade"
            placeholder="请选择仓位"
            :allowClear="false"
            v-model="form.warehouseLocationSn"
            style="width: 50%;">
            <a-select-option v-for="item in warehouseCascadeData" :value="item.warehouseLocationSn">
              {{ 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-form-model-item>
        <a-form-model-item label="采购数量" prop="productQty">
          <a-input-number
            id="purchaseReceipt-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="purchaseReceipt-product-modal-back" @click="isShow = false" style="margin-right: 15px;">取消</a-button>
          <a-button type="primary" id="purchaseReceipt-product-modal-save" @click="handleSave">{{ itemSn?'保存':'保存并新增' }}</a-button>
        </div>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import debounce from 'lodash/debounce'
// 组件
import { VSelect } from '@/components'
// 接口
import { supplierProductList } from '@/api/supplier'
import { warehouseCascadeList } from '@/api/warehouse'
import { savePurchaseDetail, getDetailData } from '@/api/purchase'
export default {
  name: 'PurchaseReceiptAddModal',
  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 {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      // form 表单设置
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 16 }
      },
      form: {
        supplierSn: '', // 供应商
        productSn: undefined, // 产品sn
        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: '' //  仓位备份数据
    }
  },
  methods: {
    // 搜索产品
    fetchUser (value) {
      console.log('fetching user', 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.$refs.productQty.focus()
      this.$refs.ruleForm.validate()
    },
    // 详情
    getDetail () {
      this.spinning = true
      getDetailData({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.form = Object.assign(this.form, data)
        }
        this.spinning = false
      })
    },
    //  保存
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          form.supplierSn = this.nowData.supplierSn
          form.sparePartsSn = this.nowData.sparePartsSn
          form.sparePartsNo = this.nowData.sparePartsNo
          form.warehouseSn = this.nowData.warehouseSn
          form.sparePartsDetailSn = this.itemSn ? this.itemSn : undefined
          _this.spinning = true
          savePurchaseDetail(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.$emit('ok', res.data)
                _this.spinning = false
                _this.isShow = false
              })
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 选择仓位
    changeWarehouseCascade (val) {
      this.$refs.productQty.focus()
      this.$refs.ruleForm.validate()
    },
    //  仓库仓位  级联  列表
    getWarehouseCascade () {
      const _this = this
      warehouseCascadeList({}).then(res => {
        if (res.status == 200) {
          const data = res.data
          var pos = data.findIndex(item => _this.nowData.warehouseSn === item.warehouseSn)
          if (pos != -1) {
            if (data[pos].warehouseLocationList && data[pos].warehouseLocationList.length > 0) {
              _this.warehouseCascadeData = data[pos].warehouseLocationList
              _this.form.warehouseLocationSn = data[pos].warehouseLocationList[0].warehouseLocationSn
            } else {
              _this.warehouseCascadeData = []
              _this.form.warehouseLocationSn = undefined
            }
          } else {
            _this.warehouseCascadeData = []
          }
        }
      })
    },
    // 重置
    resetData () {
      this.$refs.ruleForm.resetFields()
      this.form = {
        supplierSn: '', // 供应商
        productSn: undefined,
        productName: '',
        productCode: '',
        productOrigCode: '',
        warehouseSn: undefined,
        warehouseLocationSn: undefined,
        productCost: '',
        productQty: ''
      }
      this.productCost = ''
      this.itemSn = ''
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetData()
      } else {
        this.getWarehouseCascade()
      }
    },
    itemSn (newValue, oldValue) {
      if (this.isShow && newValue) {
        this.getDetail()
      }
    }
  }
}
</script>

<style lang="less">
  .purchaseReceipt-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>
