<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>

      <row-list :col="1">
        <row-item>
          <a-form-item
            label="合同"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <upload-file :max-size="100" ref="upload" @catchFile="catchFile"></upload-file>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { uploadPurchaseContract } from '@/api/purchase/purchase-contract'
import UploadFile from '@/components/Upload/UploadFile'

export default {
  name: 'BasePurchaseContractUpload',
  components: { UploadFile },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      actualUrl: ''

    }
  },
  props: {},
  created () {
  },
  methods: {
    base (record) {
      this.visible = true
      const { form: { setFieldsValue } } = this
      this.modalTitle = '上传真实合同文件'
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id'
        ])))
        const fileList = []
        if (record.actualUrl) {
          fileList.push({
            uid: 0,
            name: '合同',
            status: 'done',
            url: record.actualUrl,
            originUrl: record.actualUrl
          })
        }
        this.$refs.upload.base(fileList)
      })
    },
    catchFile (fileList) {
      if (fileList.length > 0) {
        this.actualUrl = fileList[0].url
      }
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.actualUrl = this.actualUrl
        if (!this.actualUrl) {
          this.$message.error('请上传合同文件')
          return
        }
        uploadPurchaseContract(values)
          .then(() => {
            this.handleCancel(values)
          }).catch(() => {
            this.confirmLoading = false
          })
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      // this.form.resetFields()
      this.$emit('ok', values)
    }

  }
}
</script>
