<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px">
    <el-form ref="form" label-position="top" :model="form" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="附件" prop="fileUrl">
            <el-upload
              ref="uploadRef"
              action="#"
              :before-upload="
                (file) => {
                  return beforeAvatarUpload(file)
                }
              "
              :http-request="uploadRequest"
              :limit="1">
              <el-button size="mini" type="primary">点击上传</el-button>
            </el-upload>
            <el-button v-show="form.fileUrl != ''" @click="showFile(form.fileUrl)">查看</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="选择完成日期" prop="date">
            <el-date-picker
              v-model="form.date"
              placeholder="请选择日期"
              style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" :rows="5" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="complete">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import deliverWorkApi from '@/api/work/deliverWork'
  import to from 'await-to-js'
  import axios from 'axios'
  import asyncUploadFile from '@/utils/uploadajax'

  export default {
    name: 'CompleteProgress',
    components: {},
    props: {
      // orderStatusOptions: {
      //   type: Array,
      //   default: () => [],
      // },
    },
    data() {
      return {
        form: {
          date: '',
          fileUrl: '',
          fileName: '',
          remark: '',
        },
        progress: {},
        rules: {
          fileUrl: [{ required: true, message: '不能为空', trigger: ['blur', 'change'] }],
          date: [{ required: true, message: '不能为空', trigger: ['blur', 'change'] }],
        },
        dialogFormVisible: false,
        planId: 0,
        title: '',
        fileSettings: {
          // 文件配置信息
          fileSize: 52428800,
          fileTypes: '.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.txt',
          pictureSize: 52428800,
          pictureTypes: '.jpg,.jpeg,.gif,.png,.jfif,.txt',
          types: '.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.mp4,.txt',
          videoSize: 104857600,
          videoType: '.mp4',
        },
      }
    },
    mounted() {},
    methods: {
      // 打开弹窗
      open(row) {
        this.title = '完成'
        this.progress = row
        this.form.date = ''
        this.form.fileUrl = ''
        this.form.fileName = ''
        this.form.remark = ''
        if (this.$refs['form']) {
          this.$refs['form'].resetFields()
        }
        if (this.$refs.uploadRef) {
          this.$refs.uploadRef.clearFiles() //去掉文件列表
        }
        this.dialogFormVisible = true
      },
      // 上传附件
      beforeAvatarUpload(file) {
        let flag1 = file.size < this.fileSettings.fileSize
        if (!flag1) {
          this.$message.warning('文件过大，请重新选择！')
          return false
        }
        let flag2 = this.fileSettings.fileTypes.split(',').includes('.' + file.name.split('.').pop())
        if (!flag2) {
          this.$message.warning('文件类型不符合，请重新选择！')
          return false
        }
        return true
      },
      // 上传
      uploadRequest(option) {
        let _this = this
        let url = process.env.VUE_APP_UPLOAD_WEED
        axios
          .post(url)
          .then(function (res) {
            if (res.data && res.data.fid && res.data.fid !== '') {
              option.action = `${process.env.VUE_APP_PROTOCOL}${res.data.publicUrl}/${res.data.fid}`
              asyncUploadFile(option).then(() => {
                _this.form.fileName = option.file.name
                _this.form.fileUrl = `${process.env.VUE_APP_PROTOCOL}${res.data.publicUrl}/${res.data.fid}` // 资料存储url
              })
            } else {
              _this.$message({
                type: 'warning',
                message: '未上传成功！请刷新界面重新上传！',
              })
            }
          })
          .catch(function () {
            _this.$message({
              type: 'warning',
              message: '未上传成功！请重新上传！',
            })
          })
      },
      // 查看附件
      showFile(url) {
        let fileName = this.form.fileName
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.responseType = 'blob' // 通过文件下载url拿到对应的blob对象
        xhr.onload = () => {
          if (xhr.status === 200) {
            let link = document.createElement('a')
            let body = document.querySelector('body')
            link.href = window.URL.createObjectURL(xhr.response)
            link.download = fileName
            link.click()
            this.$message.success('下载成功')
            body.removeChild(link)
            window.URL.revokeObjectURL(link.href)
          }
        }

        xhr.send()
      },
      // 完成
      async complete() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            // 10发货任务单/20组装任务单/30部署安装单
            if (this.progress.progressType == '20') {
              const [err, res] = await to(
                deliverWorkApi.completeAssembleGoodsProgress({
                  id: this.progress.id,
                  reaEndDate: this.form.date,
                  fileUrl: this.form.fileUrl,
                  fileName: this.form.fileName,
                  remark: this.form.remark,
                })
              )
              if (err) return
              if (res.code == 200) {
                this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
                this.$emit('fetch-data')
              }
            } else if (this.progress.progressType == '30') {
              const [err, res] = await to(
                deliverWorkApi.completeInstall({
                  id: this.progress.id,
                  installDate: this.form.date,
                  installCheckFileUrl: this.form.fileUrl,
                  fileName: this.form.fileName,
                  remark: this.form.remark,
                })
              )
              if (err) return
              if (res.code == 200) {
                this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
                this.$emit('fetch-data')
              }
            }
            this.dialogFormVisible = false
          }
        })
      },
    },
  }
</script>
