<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @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="['unit', {rules: [{required: true, message: '计量单位不能为空'}]}]" 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-tree-select
              style="width: 100%"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :treeData="sbTypeTreeData"
              :treeNodeFilterProp="'title'"
              :showSearch="true"
              v-decorator="['typeId', {rules: [{required: true, message: '设备类型不能为空'}]}]"
              placeholder="请选择"
            >
            </a-tree-select>
          </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-select v-decorator="['useType', {rules: [{required: true, message: '自定义类型不能为空'}]}]" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in useTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <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
              v-decorator="['name', {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-input
              v-decorator="['model', {rules: [{required: true, message: '设备型号不能为空'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <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
              disabled
              v-decorator="['nameModel']" />
          </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
              style="width: 70%"
              disabled
              v-decorator="['producerName', {rules: [{required: true, message: '生产商不能为空'}]}]" />
            <a-button style="width: 30%" type="primary" @click="handleProducerSelect">选择</a-button>
          </a-form-item>
          <a-form-item
            label="生产商"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            v-show="false"
          >
            <a-input
              v-decorator="['producerId', {rules: [{required: true, message: '生产商不能为空'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <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-select v-decorator="['level', {initialValue:1, rules: [{required: true, message: '设备等级不能为空'}]}]" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in levelMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </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-select
              show-search
              :value="unitName"
              :default-active-first-option="false"
              :show-arrow="true"
              :filter-option="true"
              :not-found-content="null"
              @search="handleSearch"
              @blur="handleBlur"
              @change="handleChange">
              <a-select-option
                v-for="(label,value) in unitMap"
                :key="value"
                :label="label"
                :value="label">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <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
              v-decorator="['value', {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-select v-decorator="['status', {initialValue:1, 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-col>
      </a-row>

      <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
              v-decorator="['remark', {rules: [{required: false, message: '备注不能为空'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <firm-producer-select-modal ref="producerSelectModal" @selected="handleProducerSelected"/>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addSbInfo, updateSbInfo } from '@/api/sb/model'
import { fetchSbTypeTree } from '@/api/sb/type'
import { fetchProducerOptions } from '@/api/firm/producer'
import FirmProducerSelectModal from '@/views/firm/producer/modules/FirmProducerSelectModal'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Vue from 'vue'

export default {
  name: 'BaseSbModel',
  components: {
    FirmProducerSelectModal
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      sbTypeTreeData: [],
      sbInfoTreeData: [],
      depreciationTypeMap: {},
      levelMap: {},
      statusMap: {},
      unitMap: {},
      unitName: null,
      useTypeMap: {},
      producers: [],
      sbInfoSelectType: null,
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      }
    }
  },
  props: {
  },
  created () {
    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.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_STANDARD_TYPE)
    this.useTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_USE_TYPE)
  },
  methods: {
    base (record) {
      this.setTree(record)
      this.setOptions()
      // 清除文件列表
      this.visible = true
      // 选择框查询条件
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        return
      }
      this.modalTitle = '编辑'
      if (this.BaseTool.Object.isBlank(record.id)) {
        this.modalTitle = '复制'
      }
      const { form: { setFieldsValue } } = this
      this.unitName = record.unit
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'model',
          'name',
          'value',
          'typeId',
          'useType',
          'level',
          'nameModel',
          'producerId',
          'producerName',
          'unit',
          'status',
          'remark'
        ])))
      })
    },
    save () {
      const { form: { validateFieldsAndScroll, setFieldsValue } } = this
      this.confirmLoading = true
      setFieldsValue({
        'unit': this.unitName
      })
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }

        if (this.BaseTool.String.isBlank(values.id)) {
          addSbInfo(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSbInfo(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 = {}) {
      fetchSbTypeTree().then(res => {
        this.sbTypeTreeData = res.data
      })
    },
    setOptions () {
      fetchProducerOptions().then(res => {
        this.producers = res.data
      })
    },
    handleProducerSelect () {
      const modal = this.$refs.producerSelectModal
      modal.base({}, { type: 1 })
    },
    handleProducerSelected (record, selectedRowKeys, selectedRow) {
      const { form: { setFieldsValue } } = this
      const [ key ] = selectedRowKeys
      const [ row ] = selectedRow
      setFieldsValue({
        'producerId': key,
        'producerName': row.name
      })
    },
    /**
     * @function 任务类型文本框的值变化时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleSearch (value) {
      // console.log("handleSearch: " + value)
      this.handleChange(value)
    },
    /**
     * @function 任务类型改变时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleChange (value) {
      // console.log("handleChange: " + value)
      this.unitName = (!isNaN(value) && value != '') ? this.BaseTool.Object.getField(this.unitMap, value) : value
      if (isNaN(this.unitName) || this.unitName == '') {
        this.unitName = value
      }
      // console.log("handleChangeEND: " + this.value)
    },
    /**
     * @function 任务类型失焦事件
     * @author ***
     * @time 2020-08-17
     **/
    handleBlur (value) {
      // console.log("handleBlur: " + value)
      this.unitName = value
    }
  }
}
</script>
