<template>
  <a-modal
    :title="modalTitle"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <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-form-item>

      <row-list :col="2">
        <row-item>
          <a-form-item
            label="测量设备编号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              style="width: 80%"
              v-decorator="['cardNo']"/>
            <a-button type="primary" style="width: 20%" @click="handleSbSelect">选择</a-button>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="检定设备名称"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              v-decorator="['sbName', {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
              disabled
              v-decorator="['sbModel']"/>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="检定周期"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              suffix="月"
              v-decorator="['checkPeriod']"/>
          </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: true, message: '检定单号不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-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="['lastDate', {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="['name']"/>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="检定单位"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['requirement', {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
              disabled
              v-decorator="['fdjxh']" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['remark']" />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="管理状态"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select v-decorator="['sbStatus', {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>
        </row-item>
      </row-list>
      <row-list :col="2">
        <row-item>
          <a-form-item
            label="图片"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-upload
              :action="uploadUrl"
              :multiple="false"
              list-type="picture"
              accept="image/*"
              :file-list="this.defaultCheckImgList"
              @change="handleCheckImgChange"
              :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-upload
              :action="uploadUrl"
              :multiple="true"
              :file-list="this.defaultCheckFileList"
              @change="handleCheckFileChange"
              :headers="headers"
            >
              <a-button> <a-icon type="upload" /> 选择上传文件 </a-button>
            </a-upload>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <measure-sb-info-select-modal ref="sbInfoSelectModal" @selected="handleSbSelectd"/>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { STable, Ellipsis } from '@/components'
import { addCheckStandard, updateCheckStandard } from '@/api/sb/measurelog'
import BaseTool from '../../../../utils/tool'
import { queryUser } from '@/api/upms/user'
import { uploadUrl } from '@/api/upms/file'
import MeasureSbInfoSelectModal from '@/views/sb/measure/modules/MeasureSbInfoSelectModal'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'BaseCheckStandard',
  components: {
    STable,
    Ellipsis,
    MeasureSbInfoSelectModal
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      statusMap: {},
      checkImgList: [], // 图片
      checkFileList: [], // 文档
      defaultCheckImgList: [],
      defaultCheckFileList: [],
      uploadUrl: uploadUrl,
      userList: {},
      editingKey: '',
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      },
      data: [],
      cacheData: []
    }
  },
  props: {
  },
  created () {
    // 下拉框map
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_MEASURE_STATUS)
  },
  methods: {
    base (record, sbInfo) {
      this.visible = true
      queryUser({}).then(res => {
        this.userList = res.data
      })
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        this.cacheData = []
        if (sbInfo != null) {
          const { form: { setFieldsValue } } = this
          // 日期处理
          this.$nextTick(() => {
            setFieldsValue({ sbId: sbInfo.id, fdjxh: sbInfo.fdjxh, cardNo: sbInfo.cardNo, sbStatus: sbInfo.status, sbModel: sbInfo.model, sbName: sbInfo.name, checkPeriod: sbInfo.checkPeriod })
          })
        }
        return
      }
      this.modalTitle = '编辑'
      if (this.BaseTool.Object.isBlank(record.id)) {
        this.modalTitle = '复制'
      }
      this.checkImgList = record.checkImgList
      this.checkFileList = record.checkFileList
      this.defaultCheckImgList = this.BaseTool.UPLOAD.transImg(this.checkImgList)
      this.defaultCheckFileList = this.BaseTool.UPLOAD.transImg(this.checkFileList)
      const { form: { setFieldsValue } } = this
      if (record.lastDate != null) {
        record.lastDate = this.BaseTool.Moment(record.lastDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'lastDate'
          ])))
        })
      }
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'sbId',
          'name',
          'no',
          'type',
          'period',
          'sbStatus',
          'sbName',
          'sbModel',
          'sbNo',
          'checkDate',
          'nextCheckDate',
          'cardNo',
          'checkPeriod',
          'checkUserId',
          'periodType',
          'actionType',
          'enable',
          'requirement',
          'fdjxh',
          'remark'
        ])))
      })
      this.data = BaseTool.Object.copy(record.paramList)
      this.cacheData = BaseTool.Object.copy(record.paramList)
      this.editingKey = ''
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.paramList = this.data
        // 上传文件
        values.checkImgList = this.checkImgList
        values.checkFileList = this.checkFileList
        // 日期数据的处理
        values.lastDate = BaseTool.Date.formatter(values.lastDate, BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        if (this.BaseTool.String.isBlank(values.id)) {
          addCheckStandard(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateCheckStandard(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)
      }
    },
    handleChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    cancel (key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      this.editingKey = ''
      if (!this.checkParams(target)) {
        const data = [...this.data]
        const cacheData = [...this.cacheData]
        this.data = data.filter(item => item.id !== key)
        this.cacheData = cacheData.filter(item => item.id !== key)
        return
      }
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.id)[0])
        console.log(target, 'target')
        delete target.editable
        this.data = newData
      }
    },
    handleCheckImgChange (info) {
      this.defaultCheckImgList = info.fileList
      this.checkImgList = this.setFileList(info, 31)
    },
    handleCheckFileChange (info) {
      this.defaultCheckFileList = info.fileList
      this.checkFileList = this.setFileList(info, 32)
    },
    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 null
      }
    },
    handleSbSelect () {
      this.$refs.sbInfoSelectModal.base()
    },
    handleSbSelectd (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'sbId': key,
          'sbName': row.name,
          'sbModel': row.model,
          'checkPeriod': row.checkPeriod,
          'cardNo': row.cardNo
        }))
      })
    }
  }
}
</script>
