<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="expressName">
            <el-input v-model="form.expressName" placeholder="请输入快递名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="快递单号" prop="expressCode">
            <el-input v-model="form.expressCode" placeholder="请输入快递单号" />
          </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="realDeliveryTime">
            <el-date-picker
              v-model="form.realDeliveryTime"
              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="请输入备注" />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="deliver">确 定</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: 'Deliver',
    components: {},
    props: {
      // orderStatusOptions: {
      //   type: Array,
      //   default: () => [],
      // },
    },
    data() {
      return {
        form: {
          date: '',
          realDeliveryTime: '',
          expressName: '',
          expressCode: '',
          remark: '',
        },
        progress: {},
        rules: {
          expressCode: [{ required: true, message: '不能为空', trigger: ['blur', 'change'] }],
          expressName: [{ required: true, message: '不能为空', trigger: ['blur', 'change'] }],
          date: [{ required: true, message: '不能为空', trigger: ['blur', 'change'] }],
          realDeliveryTime: [{ required: true, message: '不能为空', trigger: ['blur', 'change'] }],
        },
        dialogFormVisible: false,
        planId: 0,
        title: '',
        fileSettings: {
          // 文件配置信息
          fileSize: 52428800,
          fileTypes: '.pdf,.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.txt',
          pictureSize: 52428800,
          pictureTypes: '.jpg,.jpeg,.gif,.png,.jfif,.txt',
          types: '.pdf,.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.mp4,.txt',
          videoSize: 104857600,
          videoType: '.mp4',
        },
      }
    },
    mounted() {},
    methods: {
      // 打开弹窗
      async open(row) {
        let flag = false
        await deliverWorkApi
          .list({ deliverProgressId: row.id })
          .then((res) => {
            if (res.data.list && res.data.list.length > 0) {
              if (res.data.list[0].progressStatus != '30') {
                flag = true
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
        if (flag) {
          this.$message.warning('组装任务单未完成，不可发货')
          return
        }
        this.title = '发货'
        this.progress = row
        this.form.date = ''
        this.form.realDeliveryTime = ''
        this.form.expressName = ''
        this.form.expressCode = ''
        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 deliver() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const [err, res] = await to(
              deliverWorkApi.deliverGoods({
                id: this.progress.id,
                estimatedArrivalTime: this.form.date,
                realDeliveryTime: this.form.realDeliveryTime,
                expressName: this.form.expressName,
                expressCode: this.form.expressCode,
                // 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>
