<template>
  <el-dialog title="上传销售合同" :visible.sync="dialogFormVisible" :width="'600px'">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange list-form"
    >
      <el-form-item label="销售合同" prop="contractFile">
        <span slot="label" class="required-label">销售合同</span>
        <cy-upload
          ref="saleContractRef"
          :upload-params="{}"
          :file-data="ruleForm.contractFile"
          :upload-from-orange-status="true"
          :limit="1"
          :file-type="'pdf'"
          :file-size="20"
          placeholder="请上传销售合同文件"
        />
      </el-form-item>
      <el-form-item label="合同签署日期" prop="signDate">
        <el-date-picker
          v-model="ruleForm.signDate"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择签署日期"
          style="width: 100%;"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancle">取 消</el-button>
      <el-button type="primary" @click="handleUploadFile">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { uploadSaleContractFile } from '@/api/myTrade/salesContract'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    contractId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      ruleForm: {
        contractFile: [],
        signDate: '',
        fileId: '', // 文件id
        contractId: '' // 列表id
      },
      rules: {
        signDate: [
          { required: true, message: '请选择合同签署日期', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        this.dialogFormVisible = val
      }
    }
  },
  methods: {
    handleCancle() {
      this.$refs.ruleFormRef.resetFields()
      this.dialogFormVisible = false
      this.ruleForm = {
        contractFile: [],
        signDate: '',
        fileId: '',
        contractId: ''
      }
      this.$emit('close')
    },
    handleUploadFile() {
      this.$refs.ruleFormRef.validate(async(valid) => {
        if (valid) {
          const fileList = this.$refs.saleContractRef.getFileLists
          if (fileList.length === 0) {
            this.$message.warning('请上传合同文件')
            return
          }
          const params = {
            signDate: this.ruleForm.signDate,
            fileId: fileList[0].id,
            contractId: this.contractId
          }
          const res = await uploadSaleContractFile(params)

          if (res.success) {
            this.$message.success('上传成功')
            this.dialogFormVisible = false
            this.$router.go(0)
          }
        }
      })
    }
  }
}
</script>
