<template>
  <a-modal
    centered
    class="bulkWarehousingOrder-product-modal"
    :footer="null"
    :maskClosable="false"
    :title="(itemSn ? '编辑' : '新增') + '产品'"
    v-model="isShow"
    @cancle="isShow=false"
    :width="800">
    <a-form-model
      id="bulkWarehousingOrder-product-form"
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="formItemLayout.labelCol"
      :wrapper-col="formItemLayout.wrapperCol" >
      <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"
          v-model="form.productSn"
          placeholder="请选择"
          :filter-option="false"
          :not-found-content="fetching ? undefined : null"
          @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"
          v-model="form.productQty"
          :precision="0"
          :min="1"
          :max="999999"
          placeholder="请输入"
          style="width: 80%;" /><span>个</span>
      </a-form-model-item>
    </a-form-model>
    <div class="btn-cont">
      <a-button type="primary" id="bulkWarehousingOrder-product-modal-save" @click="handleSave">保存</a-button>
      <a-button id="bulkWarehousingOrder-product-modal-back" @click="isShow = false" style="margin-left: 15px;">取消</a-button>
    </div>
  </a-modal>
</template>

<script>
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',
  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, //  是否打开弹框
      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: '' //  仓位备份数据
    }
  },
  methods: {
    // 搜索产品
    fetchUser (value) {
      console.log('fetching user', value)
      this.fetching = true
      const params = {
        product: {
          code: value,
          onlineFalg: '1' //  已上线
        },
        supplierSn: this.nowData.supplierSn,
        pageNo: 1,
        pageSize: 20
      }
      supplierProductList(params).then(res => {
        if (res.status == 200) {
          this.productData = 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.productData[ind].cost == 0 ? 0.1 : ''
    },
    // 详情
    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
          sparePartsSaveDetail(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.isShow = false
                _this.$emit('ok', res.data)
              }, 1000)
            }
          })
        } 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
      }
    },
    // 仓库仓位
    getWarehouseCascade () {
      warehouseCascadeList({}).then(res => {
        if (res.status == 200) {
          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 = []
        }
      })
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.$refs.ruleForm.resetFields()
        this.warehouseSnBackups = ''
        this.warehouseLocationSnBackups = ''
      } else {
        if (this.warehouseCascadeData.length == 0) {
          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>
