<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="productSn">
          <a-select
            show-search
            id="bulkWarehousingOrder-product-productSn"
            ref="productSn"
            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>
        </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="warehouse">
          <a-cascader
            @change="changeWarehouseCascade"
            v-model="form.warehouse"
            expand-trigger="hover"
            :allowClear="false"
            :options="warehouseCascadeData"
            :fieldNames="{ label: 'name', value: 'sn', children: 'warehouseLocationList' }"
            id="bulkWarehousingOrder-product-warehouse"
            placeholder="请选择仓库仓位"
            style="width: 100%;" />
        </a-form-model-item>
        <a-form-model-item label="成本价" prop="productCost">
          <a-input-number
            id="bulkWarehousingOrder-product-productCost"
            v-model="form.productCost"
            :precision="2"
            :min="0"
            :max="999999"
            placeholder="请输入"
            style="width: 100%;" />
        </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="999999"
            placeholder="请输入"
            style="width: 80%;" /><span>个</span>
        </a-form-model-item>
        <div class="btn-cont">
          <a-button type="primary" id="bulkWarehousingOrder-product-modal-save" @click="handleSave">{{ itemSn?'保存':'保存并新增' }}</a-button>
          <a-button id="bulkWarehousingOrder-product-modal-back" @click="isShow = false" style="margin-left: 15px;">取消</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: '',
        warehouse: [],
        warehouseSn: '',
        warehouseLocationSn: '',
        productCost: '',
        productQty: ''
      },
      rules: {
        productSn: [
          { required: true, message: '请选择产品编码', trigger: 'change' }
        ],
        warehouse: [
          { required: true, message: '请选择仓库仓位', trigger: 'change' }
        ],
        productCost: [
          { required: true, message: '请输入成本价', trigger: 'blur' }
        ],
        productQty: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ]
      },
      fetching: false,
      productData: [],
      warehouseCascadeData: [], //  仓库仓位  下拉数据
      warehouseSnBackups: '', //  仓库备份数据
      warehouseLocationSnBackups: '', //  仓位备份数据
      defaultWarehouseCascade: [] //  默认仓库仓位
    }
  },
  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.productData[ind].cost != 0) ? this.productData[ind].cost : ''
      this.$refs.productQty.focus()
    },
    // 详情
    getDetail () {
      sparePartsDetailD({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.form = Object.assign(this.form, data)
          this.fetchUser(this.form.productCode)
          this.form.warehouse = [this.form.warehouseSn, this.form.warehouseLocationSn]
          this.warehouseSnBackups = this.form.warehouseSn || undefined
          this.warehouseLocationSnBackups = this.form.warehouseLocationSn || undefined
        }
      })
    },
    //  保存
    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
          if (!_this.itemSn) {
            delete form.id
            delete form.sparePartsDetailSn
          }
          _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
                _this.resetData()
                _this.$refs.productQty.blur()
                _this.$refs.productSn.focus()
              })
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    changeWarehouseCascade (val) {
      if (val.length < 2) {
        this.$message.warning('当前仓库无仓位，请选择其他仓库')
        this.form.warehouseSn = this.warehouseSnBackups
        this.form.warehouseLocationSn = this.warehouseLocationSnBackups
        if (this.warehouseSnBackups || this.warehouseLocationSnBackups) {
          this.form.warehouse = [this.warehouseSnBackups, this.warehouseLocationSnBackups]
        } else {
          this.form.warehouse = []
        }
      } else {
        this.form.warehouseSn = val[0] ? val[0] : ''
        this.form.warehouseLocationSn = val[1] ? val[1] : ''
        this.warehouseSnBackups = this.form.warehouseSn
        this.warehouseLocationSnBackups = this.form.warehouseLocationSn
      }
      this.$refs.productQty.focus()
    },
    //  仓库仓位  级联  列表
    getWarehouseCascade () {
      const _this = this
      warehouseCascadeList({}).then(res => {
        if (res.status == 200) {
          res.data.filter(item => {
            // 过滤默认仓库
            if (item.defaultFlag == 1) { //  defaultFlag为1是默认仓库
              _this.defaultWarehouseCascade[0] = item.warehouseSn
              // 过滤默认仓位
              item.warehouseLocationList.filter(subItem => {
                if (subItem.defaultFlag == 1) {
                  _this.defaultWarehouseCascade[1] = subItem.warehouseLocationSn
                  _this.form.warehouse = _this.defaultWarehouseCascade
                  _this.form.warehouseSn = _this.defaultWarehouseCascade[0] || undefined
                  _this.form.warehouseLocationSn = _this.defaultWarehouseCascade[1] || undefined
                  _this.warehouseSnBackups = _this.defaultWarehouseCascade[0] || undefined
                  _this.warehouseLocationSnBackups = _this.defaultWarehouseCascade[1] || undefined
                }
              })
            }
          })
          res.data.map(item => {
            item.sn = item.warehouseSn
            if (item.warehouseLocationList) {
              item.warehouseLocationList.map(subItem => {
                subItem.sn = subItem.warehouseLocationSn
              })
            }
          })
          this.warehouseCascadeData = res.data
        } else {
          this.warehouseCascadeData = []
        }
      })
    },
    resetData () {
      this.$refs.ruleForm.resetFields()
      this.form = {
        supplierSn: '', // 供应商
        productSn: undefined,
        productName: '',
        productCode: '',
        productOrigCode: '',
        warehouse: [],
        warehouseSn: '',
        warehouseLocationSn: '',
        productCost: '',
        productQty: ''
      }
      // this.$refs.productSn.focus()
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetData()
        this.warehouseSnBackups = ''
        this.warehouseLocationSnBackups = ''
      } else {
        this.$nextTick(() => {
          this.resetData()
        })
        this.getWarehouseCascade()
      }
    },
    itemSn (newValue, oldValue) {
      if (this.isShow && newValue) {
        this.getDetail()
      }
    }
  }
}
</script>

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