<template>
  <a-modal
    :title="modalTitle"
    :width="850"
    :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 v-show="false" >
        <a-input v-decorator="['modelId']" type="hidden"/>
      </a-form-item>

      <a-form-item v-show="false" >
        <a-input v-decorator="['spareId']" type="hidden"/>
      </a-form-item>

      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="选择备件"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              style="width: 70%"
              disabled
              v-decorator="['spareName', {rules: [{required: true, message: '备件不能为空'}]}]" />
            <a-button style="width: 30%" type="primary" @click="handleSpareSelect">选择</a-button>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="更换周期"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            style="margin-bottom:0;"
          >
            <!-- 解决校验问题 -->
            <a-form-item :style="{ display: 'inline-block', width: '60%' }">
              <a-input-number
                :min="1"
                style="width: 100%"
                v-decorator="['period', {initialValue: 500,rules: [{required: true, message: '更换周期不能为空'}]}]"/>
            </a-form-item>
            <a-form-item
              :style="{ display: 'inline-block', width: '40%' }"
            >
              <a-select
                v-decorator="['periodType', {initialValue: 6,rules: [{required: true, message: '周期类型不能为空'}]}]"
                placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in periodTypeMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="数量"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="1"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-decorator="['num', {initialValue:1, rules: [{required: true, message: '数量不能为空'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <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="['checkDate']" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <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="['nextCheckDate']" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="更换里程/台时"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['changeNum']" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="下次更换里程/台时"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['nextChangeNum']" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <spare-part-info-select-modal :type="'checkbox'" ref="spareSelectModal" @selected="handleSpareSelected"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'

import { addSbInfo } from '@/api/sb/model'
import { addSbModelBom, updateSbModelBom, deleteSbModelBoms } from '@/api/sb/modelbom'
import SparePartInfoSelectModal from '@/views/sqarepartmanage/sparepartinfo/modules/SparePartInfoSelectModal'
import Vue from 'vue'
import BaseTool from "@/utils/tool";

export default {
  name: 'BaseSbModel',
  data () {
    return {
      confirmLoading: false,
      modelId: null,
      spareId: null,
      modalTitle: null,
      sbId: null,

      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map,
      enableMap: {},
      statusMap: {},
      sbTypeTreeData: [],
      typeMap: {},
      periodTypeMap: {}
    }
  },
  components: {
    SparePartInfoSelectModal
  },
  created () {
    // 下拉框map
    this.depreciationTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_DEPRECIATIONTYPE)
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_LEVEL)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_MODEL_RECOMMEND)
    this.unitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_UNIT)
    this.enableMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YES_NO)
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_STANDARD_TYPE)
    this.useTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_UES_TYPE)
    this.periodTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_PERIOD_TYPE)
  },
  methods: {
    base (record) {
      this.visible = true
      if (this.BaseTool.Object.isBlank(record.modelId)) {
        this.sbId = record.id
        this.modalTitle = '添加'
        const { form: { setFieldsValue } } = this
        // 日期处理
        this.$nextTick(() => {
          setFieldsValue(Object.assign({
            'modelId': record.modelId,
            'sbId': record.id
          }))
        })
        return
      }
      this.modalTitle = '编辑'
      const { form: { setFieldsValue } } = this
      record.spareName = record.name
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'modelId',
          'spareId',
          'checkDate',
          'nextCheckDate',
          'changeNum',
          'nextChangeNum',
          'spareName',
          'period',
          'periodType',
          'num'
        ])))
      })
    },

    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },

    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.sbId = this.sbId
        values.checkDate = BaseTool.Date.formatter(values.checkDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.nextCheckDate = BaseTool.Date.formatter(values.nextCheckDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)

        if (this.BaseTool.String.isBlank(values.modelId)) {
          console.log(values)
          addSbModelBom(values)
            .then((response) => {
              this.$message.info('添加成功')
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSbModelBom(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },

    handleSpareSelect () {
      this.$refs.spareSelectModal.base({}, { yt: 1 })
    },
    handleSpareSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'spareId': key,
          'spareName': row.name
        }))
      })
    },
    handleDel () {
      const data = [...this.data]
      let ids = []
      ids = this.selectedRows.map(item => item.bomId)

      // 调取删除接口，批量删除
      this.confirmLoading = true
      deleteSbModelBoms(ids)
        .then(() => {
          this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
          this.handleCancel(values)
          this.$message.info('删除成功')
        }).catch(() => {
          this.confirmLoading = false
        })
    }

  }
}
</script>
