<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-tree-select
          style="width: 100%"
          :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
          :treeData="sbInfoTreeData"
          :treeNodeFilterProp="'title'"
          :disabled="true"
          :showSearch="true"
          v-decorator="['sbId', {rules: [{required: true, message: '设备不能为空'}]}]"
          placeholder="请选择"
        >
        </a-tree-select>
      </a-form-item>
      <a-form-item
        label="部件名称"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select
          :disabled="model.partId != null"
          v-decorator="['partId']"
          placeholder="请选择">
          <a-select-option
            v-for="({value, label}) of partInfoOptions"
            :key="value"
            :label="label"
            :value="value">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="备件id"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
        v-show="false"
      >
        <a-input
          v-decorator="['oldSpareId']" />
      </a-form-item>
      <a-form-item
        label="旧备件名称"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          style="width:70%;margin-right:5px"
          v-decorator="['oldSpareName']" />
        <a-button type="primary" @click="handleOldSpareSelect">选择备件</a-button>
      </a-form-item>
      <a-form-item
        label="备件id"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
        v-show="false"
      >
        <a-input
          v-decorator="['spareId', {rules: [{required: true, message: '备件id不能为空'}]}]" />
      </a-form-item>
      <a-form-item
        label="新备件名称"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          style="width:70%;margin-right:5px"
          v-decorator="['spareName', {rules: [{required: true, message: '备件名称不能为空'}]}]" />
        <a-button type="primary" @click="handleSpareSelect">选择备件</a-button>
      </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', {rules: [{required: true, message: '投用日期不能为空'}]}]" />
      </a-form-item>

      <a-form-item
        label="使用状态"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select v-decorator="['status', {rules: [{required: true, message: '使用状态不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="(label,value) in statusMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </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="['changeDate', {rules: [{required: true, message: '预计报废日期不能为空'}]}]" />
      </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="['realChangeDate']" />
      </a-form-item>

      <a-form-item
        label="原因"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          v-decorator="['reason', {rules: [{required: false, message: '原因不能为空'}]}]" />
      </a-form-item>

      <a-form-item
        label="备注"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          v-decorator="['remark']" />
      </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" @selected="handleOldSpareSelected" />
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addRepairPartUsed, updateRepairPartUsed } from '@/api/repair/part-used'
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',
          'storeId',
          'sbId',
          'partId',
          'spareId',
          'startDate',
          'status',
          'changeDate',
          'realChangeDate',
          'remark'
        ])))
      })
    },
    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)
        values.repairId = this.model.repairId
        if (this.BaseTool.String.isBlank(values.id)) {
          addRepairPartUsed(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateRepairPartUsed(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },
    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
      console.log(444, key, row)
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'oldSpareId': key,
          'oldSpareName': row.spareName
        }))
      })
    }
  }
}
</script>
