<template>
  <!-- 文件记录信息编辑弹窗 -->
  <div class="examination batch-edit-wrap">
    <el-dialog
      @close="closeDialog"
      :visible.sync="recordShowFlag"
      customClass="dialog_wrap"
      :close-on-click-modal="false"
    >
      <div slot="title" class="titleBox">
        <i
          :class="tableType === 0 ? 'el-icon-document' : 'el-icon-edit-outline'"
          style="font-size: 20px"
        ></i>
        <span style="margin-left: 10px; font-size: 18px">{{ type }}</span>
      </div>
      <el-form
        ref="editData"
        label-width="65px"
        :inline="true"
        :rules="ruleValidate"
        :model="editData"
      >
        <el-form-item prop="fileName" label="文件名称">
          <el-input
            v-model="editData.fileName"
            clearable
            size="small"
            style="width: 160px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="fileDate" label="文件日期">
          <el-date-picker
            v-model="editData.fileDate"
            size="small"
            type="date"
            style="width: 160px"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="memo" label="备注">
          <el-input
            v-model="editData.memo"
            clearable
            size="small"
            style="width: 392px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="audit" label="是否审核">
          <el-select
                v-model="audit"
                filterable
                collapse-tags
                size="small"
                style="width: 80px"
              >
                <el-option
                  v-for="(item, index) in isSmpType"
                  :key="index"
                  :label="item.isSmp"
                  :value="item.id"
                >
                </el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="文件上传">
          <el-input
            v-model="editData.filePath01"
            size="small"
            readonly
            disabled
            style="width: 192px; display: inline-block"
          ></el-input>
          <el-upload
            class="upload"
            action=""
            v-if="editData.filePath01 - 0 === 0"
            style="width: 40px; display: inline-block"
            :multiple="false"
            :show-file-list="false"
            accept=""
            :http-request="httpRequest"
          >
            <el-button
              type="goon"
              size="mini"
              icon="el-icon-upload2"
            ></el-button>
          </el-upload>
          <el-button
            v-else
            type="primary"
            size="mini"
            class="el-icon-circle-close"
            @click="dropFile"
          ></el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="saveData">确定</el-button>
        <el-button size="mini" type="default" @click="closeDialog"
          >取消</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCookie
} from '@/utils/util.js';
import {
  cookieUserId,
  cookieUserName
} from '@/config/config.js';
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  props: ['type', 'recordShowFlag', 'recordObj'],
  data () {
    return {
      // 编辑的数据对象
      editData: {
        fileName: '',
        fileDate: '',
        memo: '',
        filePath01: ''
      },
      editDataCache: {
        fileName: '',
        fileDate: '',
        memo: '',
        filePath01: ''
      },
      audit: '1',
      isSmpType: [
        { id: "0", isSmp: "否" },
        { id: "1", isSmp: "是" },
      ],
      tableType: 0,// 当前是编辑还是新增， 0为新增
      ruleValidate: {
        fileDate: [{ required: true, message: '该项不能为空', trigger: 'change' }]
      },
    }
  },
  created () {
  },
  mounted () {
    
  },
  methods: {
    getYNM (date) {
      let year = date.getFullYear().toString();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      return `${year}-${month}-${day}`;
    },
    // 关闭弹窗
    closeDialog () {
      this.$emit('close')
    },
    closeDialog1 () {
      this.$emit('refresh')
    },
    // 保存数据文件名称
    async saveData () {
      this.$refs["editData"].validate((valid) => {
        if(valid){
          // if (this.editData.filePath01 - 0 === 0) {
          //   return this.$message.warning('请上传文件')
          // }
          this.editData.tenantNo = '1'
          this.axios.post('pass/baseManagement/v1/limsisofileds/insertupdate?audit='+this.audit, this.editData, { individualType: 'json' }).then((res)=>{
            if (res.status === 'succeed') {
              this.$message.success('操作成功')
              this.closeDialog1()
            } else {
              this.$message.error(res.data)
            }
          })
        }
      })
    },
    // 文件上传
    async httpRequest (e) {
      let _this = this;
      if (!e.file) {
        // 没有文件
        return false
      }
      let file = new FormData()
      file.append('file', e.file)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.axios.post('pass/baseManagement/v1/file/upload', file, config).then(res =>{
        if (res.code === '0' || res.code === '200') {
          this.$message.success('上传成功')
          this.editData.fileName = res.data[0].oldFileName
          this.editData.filePath01 = res.data[0].fileName
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        return this.$message.error(e.message)
      })
      // 先获取文件id
      // const data = await this.axios.get('/icore.icp.web/file')
      // if (data.status - 0 !== 200 || data.data.url - 0 === 0) {
      //   return this.$message.error('操作异常，请重试')
      // }
      // let fileId = data.data.fid
      // let uploadPath = data.data.url.split('.')[0]
      // let uploadFile = new FormData()
      // uploadFile.append('file', file)
      // let config = {
      //   headers: {
      //     'Content-Type': 'multipart/form-data'
      //   }
      // }
      // // 上传文件
      // const fileData = await this.axios.post(`/icore.icp.web/${uploadPath}/${fileId}`, uploadFile, config)
      // if (fileData.status - 0 === 201 && fileData.data.size - 0 > 0) {
      //   this.$message.success('上传成功')
      //   // this.editData.filePath01 = fileData.data.name
      //   this.editData.filePath01 = `/${uploadPath}/${fileId}`
      // } else {
      //   return this.$message.error('操作异常，请重试')
      // }
    },
    // 删除已有文件
    async dropFile () {
      let result = await this.MessageBox.confirm('确认删除该文件重新上传吗？').catch(() => 'cancel')
      if (result == 'cancel') return
      var data
      try {
        if(this.editData.id){
          const data = await this.axios.post('pass/baseManagement/v1/limsisofileds/delectFile', {stId : this.editData.id}, { individualType: 'json' })
          if (data.status === 'succeed') {
            this.editData.filePath01 = ''
            this.$message.success('文件删除成功')
          } else {
            this.$message.error(data.message)
          }
        }else{
          this.editData.filePath01 = ''
          this.$message.success('文件删除成功')
        }
      } catch (e) {
        console.log(e)
      }
    }
  },
  watch: {
    recordObj (newVal, oldVal) {
      this.editData = { ...this.editDataCache, ...newVal }
      if(this.editData.fileDate == null || this.editData.fileDate == ""){
        this.editData.fileDate = this.getYNM(new Date())
      }
    }
  }
}
</script>
<style>
.batch-edit-wrap .el-icon-close {
  display: none;
}

.batch-edit-wrap .el-dialog__header {
  padding-top: 0px;
}

.batch-edit-wrap .el-select .el-input__inner {
  padding-right: 25px !important;
}

.dialog_wrap {
  width: 520px !important;
}

.dialog_wrap .el-dialog__footer {
  text-align: center;
}
</style>