<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>
      <a-form-item
        label="更换日期"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-date-picker
          style="width: 100%"
          :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
          v-decorator="['startDate']" />
      </a-form-item>
      <a-form-item
        label="数量"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          @blur="calcAmount"
          :min="1"
          :step="0.01"
          v-decorator="['num', {rules: [{required: true, message: '备件id不能为空'}]}]" />
      </a-form-item>
      <a-form-item
        label="价格"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          @blur="calcAmount"
          :min="1"
          :step="0.01"
          v-decorator="['price', {rules: [{required: true, message: '价格不能为空'}]}]" />
      </a-form-item>

      <a-form-item
        label="总价"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          v-decorator="['totalPrice', {rules: [{required: false, message: '总价不能为空'}]}]" />
      </a-form-item>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <spare-part-info-select-modal ref="spareSelectModal" @selected="handleSpareSelected"/>
    <spare-part-used-select-modal ref="sparePartUsedSelectModal" @select="handleOldSpareSelected" />
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addSparePartUsed, updateSparePartUsed } from '@/api/sqarepartmanage/sparepartused'
import { getSbInfoTree } from '@/api/sb/info'
import { fetchPartInfoOptions } from '@/api/part/info'
import { fetchSparePartInfoOptions } from '@/api/sqarepartmanage/sparepartinfo'
import SparePartInfoSelectModal from '@/views/sqarepartmanage/sparepartinfo/modules/SparePartInfoSelectModal'
import SparePartUsedSelectModal from '@/views/sqarepartmanage/sparepartused/modules/SparePartUsedSelectModal'

export default {
  name: 'BaseSparePartUsed',
  components: {
    SparePartInfoSelectModal, SparePartUsedSelectModal
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      statusMap: {},
      sbInfoTreeData: [],
      partInfoOptions: [],
      sparePartInfoOptions: [],
      model: {}
    }
  },
  props: {
  },
  created () {
    // 下拉框map
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_PART_USED_STATUS)
  },
  methods: {
    base (record) {
      this.setTree(record)
      this.visible = true
      this.model = record
      // 如果是空标识添加
      this.modalTitle = '添加'
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'num',
          'price',
          'totalPrice',
          'startDate'
        ])))
      })
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        // 日期处理
        values.startDate = this.BaseTool.Date.formatter(values.startDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.changeDate = this.BaseTool.Date.formatter(values.changeDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.realChangeDate = this.BaseTool.Date.formatter(values.realChangeDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        if (this.BaseTool.String.isBlank(values.id)) {
          addSparePartUsed(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSparePartUsed(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok')
    },
    setTree (record = {}) {
      getSbInfoTree().then(res => {
        this.sbInfoTreeData = res.data
      })
      fetchPartInfoOptions().then(res => {
        this.partInfoOptions = res.data
      })
      fetchSparePartInfoOptions().then(res => {
        this.sparePartInfoOptions = res.data
      })
    },
    handleSpareSelect () {
      this.$refs.spareSelectModal.base()
    },
    handleOldSpareSelect () {
      this.$refs.sparePartUsedSelectModal.base({}, { sbId: this.model.sbId, partId: this.model.partId })
    },
    handleSpareSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'spareId': key,
          'spareName': row.name
        }))
      })
    },
    handleOldSpareSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'oldSpareId': key,
          'oldSpareName': row.name
        }))
      })
    },
    calcAmount () {
      const { form: { setFieldsValue, getFieldValue } } = this
      const num = getFieldValue('num')
      const price = getFieldValue('price')
      const totalPrice = this.BaseTool.Number.mul(num, price)
      setFieldsValue({
        totalPrice
      })
    }
  }
}
</script>
