<template>
  <a-modal
    :title="modalTitle"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel">
<!--    <a-row :gutter="48" slot="extra">
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right" >
          <a-button style="margin-left: 8px" type="primary" @click="save()">保存</a-button>
          <a-button style="margin-left: 8px" @click="handleCancel()">返回列表</a-button>
        </span>
      </a-col>
    </a-row>-->
    <a-form :form="form">

      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['sbId']" type="hidden"/>
        <a-input v-decorator="['typeId']" type="hidden"/>
      </a-form-item>
      <a-form-item v-show="false" >
        <a-input v-decorator="['unit']" type="hidden"/>
      </a-form-item>
      <a-form-item v-show="false" >
        <a-input v-decorator="['unitBz']" type="hidden"/>
      </a-form-item>
      <a-form-item v-show="false">
        <a-input v-decorator="['producerId']" />
      </a-form-item>
      <a-form-item v-show="false">
        <a-input v-decorator="['supplierId']" />
      </a-form-item>
      <title-divider title="类型设置" width="150px"></title-divider>
      <row-list :col="2">
        <row-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="spareTypeData"
              :treeNodeFilterProp="'title'"
              :showSearch="true"
              v-decorator="['parentTypeId', {rules: [{required: true, message: '类别不能为空'}]}]"
              placeholder="请选择"
            >
            </a-tree-select>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="备件名称"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['name', {rules: [{required: true, message: '设备名称不能为空'}]}]" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="规格型号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['ggxh']" />
          </a-form-item>
        </row-item>
      </row-list>
      <row-list :col="2">
        <row-item>
          <a-form-item
            label="生产商"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              style="width: 70%"
              disabled
              v-decorator="['producerName']" />
            <a-button style="width: 30%" type="primary" @click="handleProducerSelect">选择</a-button>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="备件价值"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="0.01"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-decorator="['initialValue', {rules: [{required: true, message: '备件价值不能为空'}]}]" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="采购供应商"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              style="width: 70%"
              disabled
              v-decorator="['supplierName']" />
            <a-button style="width: 30%" type="primary" @click="handleSupplierSelect">选择</a-button>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="备件编号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['no', {rules: [{required: false, message: '备件编码不能为空'}]}]" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="原厂编号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              style="width: 100%"
              v-decorator="['initNo']" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="自编号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['zbh', {rules: [{required: false, message: '自编号不能为空'}]}]" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="助记码"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['zjm']" />
          </a-form-item>
        </row-item>

        <row-item>
          <a-form-item
            label="备件等级"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select v-decorator="['level', {initialValue: 1}]" 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>
        </row-item>
        <row-item>
          <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>
        </row-item>
        <row-item>
          <a-form-item
            label="包装单位"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              show-search
              :value="unitNameBz"
              :default-active-first-option="false"
              :show-arrow="true"
              :filter-option="true"
              :not-found-content="null"
              @search="handleSearchBz"
              @blur="handleBlurBz"
              @change="handleChangeBz">
              <a-select-option
                v-for="(label,value) in unitMap"
                :key="value"
                :label="label"
                :value="label">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="折算系数"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              placeholder="单位折算为包装单位，如24个单位包装为一箱"
              v-decorator="['unitRate']" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="采购周期"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input suffix="天"
              v-decorator="['purchasePeriod']" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="使用周期"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input suffix="月"
              v-decorator="['usePeriod']" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="最高库存"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="1"
              v-decorator="['maxStock']" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="最低库存"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="1"
              v-decorator="['minStock']" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="初始库存"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="1"
              v-decorator="['initStock']" />
          </a-form-item>
        </row-item>

        <row-item>
          <a-form-item
            label="英文名称"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['englishName', {rules: [{required: false, message: '英文名称不能为空'}]}]" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="产地"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select v-decorator="['cd']" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in cdMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="备件图片"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-upload
              :action="uploadUrl"
              :multiple="true"
              list-type="picture"
              :file-list="this.defaultApplicationFileList"
              @change="handleApplicationFileChange"
              accept="image/*"
              :headers="headers"
            >
              <a-button> <a-icon type="upload" /> 上传图片 </a-button>
            </a-upload>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['remark', {rules: [{required: false, message: '备注不能为空'}]}]" />
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <firm-producer-select-modal ref="producerSelectModal" @selected="handleProducerSelected"/>
    <supplier-select-modal ref="supplierSelectModal" @selected="handleSupplierSelected"/>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addSparePartInfo, querySparePartInfo, updateSparePartInfo } from '@/api/sqarepartmanage/sparepartinfo'
import { querySpareType, fetchSpareTypeTree } from '@/api/sqarepartmanage/sparetype'
import { fetchSbGuigeOptions } from '@/api/sb/guige'
import FirmProducerSelectModal from '@/views/firm/producer/modules/FirmProducerSelectModal'
import SupplierSelectModal from '@/views/purchase/supplier/modules/SupplierSelectModal'
import UploadSpareFile from '@/components/Upload/UploadSpareFile'
import Vue from 'vue'
import { uploadUrl } from '@/api/upms/file'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'BaseSparePartInfo',
  components: {
    FirmProducerSelectModal,
    SupplierSelectModal,
    UploadSpareFile
  },
  data () {
    return {
      unitName: null,
      unitNameBz: null,
      gg: null,
      uploadUrl: uploadUrl,
      defaultApplicationFileList: [],
      applicationFileList: [], // 备件图片
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      levelMap: {},
      unitMap: {},
      cdMap: {},
      ytMap: {},
      spareTypeData: [],
      spareTypeDataMiddle: [],
      spareTypeDataChild: [],
      producers: [],
      ggList: [],
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      },
      // 表头
      columns: [
        {
          title: '集团统一编号',
          dataIndex: 'uniteNo'
        },
        {
          title: '一级类别',
          dataIndex: 'parentName'
        },
        {
          title: '一级编码',
          dataIndex: 'parentNo'
        },
        {
          title: '二级类别',
          dataIndex: 'middleName'
        },
        {
          title: '二级编码',
          dataIndex: 'middleNo'
        },
        {
          title: '三级类别',
          dataIndex: 'childName'
        },
        {
          title: '三级编码',
          dataIndex: 'childNo'
        },
        {
          title: '名称',
          dataIndex: 'name'
        },
        {
          title: '名称编码',
          dataIndex: 'nameNo'
        },
        {
          title: '规格',
          dataIndex: 'ggxh'
        },
        {
          title: '规格编码',
          dataIndex: 'ggNo'
        }
      ],
      data: [],
      sbId: null
    }
  },
  props: {
  },
  created () {
    // 下拉框map
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_PART_INFO_LEVEL)
    this.unitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_UNIT)
    this.cdMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PRODUCER_AREA)
    this.ytMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_USE_TYPE)
  },
  methods: {
    base (record, sbId) {
      this.setTree(record)
      this.visible = true
      this.sbId = sbId
      console.log('sbId: ', sbId)
      // 如果是空标识添加
      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.applicationFileList = record.applicationFileList
      this.defaultApplicationFileList = this.BaseTool.UPLOAD.transImg(this.applicationFileList)
      this.unitName = record.unit
      this.unitNameBz = record.unitBz
      this.gg = record.ggxh
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'no',
          'sbId',
          'initNo',
          'uniteNo',
          'nameNo',
          'ggNo',
          'name',
          'parentTypeId',
          'middleTypeId',
          'childTypeId',
          'typeId',
          'level',
          'initialValue',
          'producerId',
          'producerName',
          'supplierId',
          'supplierName',
          'unit',
          'unitBz',
          'unitRate',
          'englishName',
          'childNo',
          'parentNo',
          'parentName',
          'childName',
          'typeName',
          'middleNo',
          'middleName',
          'cd',
          'ggxh',
          // 'yt',
          'zjm',
          'zbh',
          'maxStock',
          'minStock',
          'initStock',
          'remark'
        ])))
      })
    },
    save () {
      const { form: { validateFieldsAndScroll, setFieldsValue } } = this
      this.confirmLoading = true
      console.log('sbId: ' + this.sbId)
      setFieldsValue({
        'unit': this.unitName,
        'unitBz': this.unitNameBz,
        'sbId': this.sbId
      })
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.applicationFileList = this.applicationFileList
        // 日期处理
        if (this.BaseTool.String.isBlank(values.id)) {
          addSparePartInfo(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSparePartInfo(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleProducerSelect () {
      this.$refs.producerSelectModal.base({}, { type: 3 })
    },
    handleProducerSelected (record, selectedRowKeys, selectedRow) {
      const { form: { setFieldsValue } } = this
      const [ key ] = selectedRowKeys
      const [ row ] = selectedRow
      setFieldsValue({
        'producerId': key,
        'producerName': row.name
      })
    },
    handleSupplierSelect () {
      this.$refs.supplierSelectModal.base()
    },
    handleSupplierSelected (record, selectedRowKeys, selectedRow) {
      const { form: { setFieldsValue } } = this
      const [ key ] = selectedRowKeys
      const [ row ] = selectedRow
      setFieldsValue({
        'supplierId': key,
        'supplierName': row.name
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.unitName = null
      this.unitNameBz = null
      this.gg = null
      this.data = []
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      } else {
        this.$emit('ok')
      }
    },
    /**
     * 设置备件类别树
     */
    setTree (record = {}) {
      fetchSpareTypeTree({ }).then(res => {
        this.spareTypeData = res.data
      })
      /*querySpareType({ filter: 2, parentId: record.parentTypeId }).then(res => {
        this.spareTypeDataMiddle = res.data
      })
      querySpareType({ filter: 2, parentId: record.middleTypeId }).then(res => {
        this.spareTypeDataChild = res.data
      })*/
      fetchSbGuigeOptions().then(res => {
        this.ggList = res.data
      })
    },

    checkSpareNo () {
      const { form: { getFieldValue } } = this
      const typeId = getFieldValue('typeId')
      const name = getFieldValue('name')
      // const ggxh = getFieldValue('ggxh')
      if (typeId == null) {
        this.$message.error('请先设置大小类型')
        return
      }
      querySparePartInfo({
        typeId: typeId,
        name: name,
        dataScope: {
          sortBy: 'desc',
          sortName: 'name'
        }
      }).then(res => {
        this.data = res.data
      })
    },
    /**
     * @function 任务类型文本框的值变化时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleSearch (value) {
      this.handleChange(value)
    },
    /**
     * @function 任务类型改变时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleChange (value) {
      this.unitName = (!isNaN(value) && value !== '') ? this.BaseTool.Object.getField(this.unitMap, value) : value
      if (isNaN(this.unitName) || this.unitName === '') {
        this.unitName = value
      }
    },
    /**
     * @function 任务类型失焦事件
     * @author ***
     * @time 2020-08-17
     **/
    handleBlur (value) {
      this.unitName = value
    },
    /**
     * @function 任务类型文本框的值变化时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleSearchBz (value) {
      this.handleChange(value)
    },
    /**
     * @function 任务类型改变时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleChangeBz (value) {
      this.unitNameBz = (!isNaN(value) && value !== '') ? this.BaseTool.Object.getField(this.unitMap, value) : value
      if (isNaN(this.unitNameBz) || this.unitNameBz === '') {
        this.unitNameBz = value
      }
    },
    /**
     * @function 任务类型失焦事件
     * @author ***
     * @time 2020-08-17
     **/
    handleBlurBz (value) {
      this.unitNameBz = value
    },
    /**
     * @function 任务类型文本框的值变化时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleSearchG (value) {
      this.handleChangeG(value)
    },
    /**
     * @function 任务类型改变时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleChangeG (value) {
      this.gg = (!isNaN(this.ggList[value]) && this.ggList[value] !== '') ? this.ggList[value].label : value
      if (isNaN(this.gg) || this.gg === '') {
        this.gg = value
      }
    },
    /**
     * @function 任务类型失焦事件
     * @author ***
     * @time 2020-08-17
     **/
    handleBlurG (value) {
      this.gg = value
    },
    parentChange (val, option) {
      querySpareType({ parentId: val, filter: 2 }).then(res => {
        this.spareTypeDataMiddle = res.data
      })
      const { form: { setFieldsValue } } = this
      setFieldsValue({ parentNo: option.data.key, typeId: val, middleTypeId: null, middleNo: null, childTypeId: null, childNo: null })
    },
    middleChange (val, option) {
      querySpareType({ parentId: val, filter: 2 }).then(res => {
        this.spareTypeDataChild = res.data
      })
      const { form: { setFieldsValue } } = this
      setFieldsValue({ middleNo: option.data.key, typeId: val, childTypeId: null, childNo: null })
    },
    childChange (val, option) {
      const { form: { setFieldsValue } } = this
      setFieldsValue({ childNo: option.data.key, typeId: val, childTypeId: val })
    },
    handleApplicationFileChange (info) {
      this.defaultApplicationFileList = info.fileList
      this.applicationFileList = this.setFileList(info, 14)
    },
    setFileList (info, type) {
      const file = info.file
      const fileList = info.fileList
      if (file.status === 'done') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'removed') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'error') {
        this.$message.error('上传失败')
        return []
      }
    }
  }
}
</script>
