<template>
  <el-dialog :title="dialogTitle" :visible.sync="visible" width="800px" class="import-modal-wrap" append-to-body>
    <el-form
      :model="searchArray"
      ref="searchArrayRef"
      size="small"
      :inline="true"
      :rules="rules"
      style="margin-top:20px;"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="营销任务名称" prop="marketName">
            <el-input
              v-model="searchArray.marketName"
              placeholder="请输入营销任务名称"
              clearable
              style="width:630px"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否需要反馈" prop="isFeedback">
            <el-select 
              v-model="searchArray.isFeedback" 
              placeholder="请选择" 
              style="width:630px" 
              clearable
            >
              <el-option
                key="0"
                value="0"
                label="否"
              ></el-option>
              <el-option
                key="1"
                value="1"
                label="是"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="任务结束时间" prop="endTime">
            <el-date-picker
              v-model="searchArray.endTime"
              placeholder="请选择"
              clearable
              style="width:630px"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传名单" prop="list" label-width="107px">
            <el-upload
              class="import-upload"
              ref="upload"
              :limit="1"
              action="none"
              accept=".xlsx, .xls"
              :on-change="onUploadChange"
              :on-remove="handleRemove"
              :auto-upload="false"
              :fileList="fileList"
              drag
            >
              <svg-icon icon-class="upload-cloud" class="upload-cloud" />
              <div class="el-upload__text">
                <span style="font-size: 12px; color: #666666; line-height: 14px">仅允许导入xls、xlsx格式文件, 文件大小不能超过60MB</span>
                <div style="height: 60px">
                  <el-button size="small" type="primary" class="upload-btn">上传文件</el-button>
                  <el-button type="text" icon="el-icon-download" style="font-size: 12px; margin-left: 10px" @click.stop="download">下载模板</el-button>
                </div>
                <span
                  v-if="fileDataArr.length > 0"
                  class="file-name"
                  :class="{ 'is-show-del': isDelete }"
                  @mouseenter="isDelete = !isDelete"
                  @mouseleave="isDelete = !isDelete"
                  >{{ getFileName() }} <i class="el-icon-close" @click.stop="delFile"></i
                ></span>
              </div>
              <div class="el-upload__tip text-center" slot="tip"></div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button 
        type="primary" 
        :loading="btnLoading"
        @click="submitUpload" 
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { uploadFile, editFile, downloadFile, querystatus } from '@/api/task/markettask.js'
import { downloadFiles } from '@/utils'
import { isEmpty, cloneDeep } from 'lodash'
import dayjs from 'dayjs'

export default {
  components: {
  },
  props: {
    dialogTitle: {
      required: true,
      type: String,
      default: '营销任务创建'
    },
    perInfo: {
      required: true,
      type: Object,
      default: {}
    }
  },
  computed: {
    userid() {
      return localStorage.getItem('userid')
    }
  },
  watch: {
    visible(val) {
      val && this.getInitData()
    },
    perInfo: {
      handler(val) {
        console.log('val', val)
        this.searchArray = {
          marketName: val.marketName,
          isFeedback: val.isFeedback,
          endTime: val.endTime
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      searchArray: {
        marketName: "",
        isFeedback: "",
        endTime: ""
      },
      rules: {
        marketName: [
          {
            required: true,
            message: '请输入营销任务名称',
            trigger: 'blur'
          }
        ],
        isFeedback: [
          {
            required: true,
            message: '请选择是否需要反馈',
            trigger: 'blur'
          }
        ],
        endTime: [
          {
            required: true,
            message: '请选择营销任务结束时间',
            trigger: 'blur'
          }
        ]
      },
      isDelete: false,
      visible: false,
      btnLoading: false,
      fileList: [],
      fileDataArr: [],
      file: '',
      timer: ''
    }
  },
  methods: {
    delFile() {
      this.clearFiles()
      this.fileDataArr = []
    },
    onUploadChange(file, fileList) {
      const isLt60M = file.size / 1024 / 1024 < 60
      if (!isLt60M) {
        this.$message.error('上传单个文件大小不能超过 60MB!')
        this.clearFiles()
        return false
      } else {
        if (fileList.length > 0) {
          this.fileDataArr = cloneDeep(fileList)
          this.onSuccess(file.raw)
        }
        fileList.splice(0, 1)
        // this.fileList = []
      }
    },
    clearFiles() {
      this.fileList = []
      this.fileDataArr = []
      this.file = ''
      this.$refs.upload?.clearFiles()
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    onSuccess(file) {
      this.file = file
    },
    getInitData() {
      this.clearFiles()
    },
    onClose() {
      this.visible = false
      this.clearFiles()
    },
    download() {
      downloadFile().then((res) => {
        downloadFiles(res, `营销任务模板_${new Date().getTime()}.xlsx`)
      })
    },
    submitUpload() {
      this.$refs.searchArrayRef.validate(valid => {
        if (valid) {
          const isEdit = this.dialogTitle.includes('编辑')
          if (this.fileDataArr.length === 0 && !isEdit) {
            this.$message.warning('请上传名单~')
            return
          }
          this.btnLoading = true
          const params = isEdit ?
          {
            ...this.searchArray,
            id: this.perInfo.id
          }
          : this.searchArray
          
          const formData = new FormData()
          this.file && formData.append('file', this.file)
          formData.append('dto', JSON.stringify({
            ...params,
            endTime: dayjs(params.endTime).format('YYYY-MM-DD') + ' 23:59:59'
          }))
          const API = isEdit ? editFile : uploadFile
          API(formData)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success('后台正在处理中，请稍后查看')
                this.$emit('onRefreshTable')
                // if (this.fileDataArr.length > 0 && res.data) {
                //   this.getstatus(res.data)
                // } else {
                //   this.$emit('onRefreshTable')
                // }
                this.onClose()
              }
            })
            .catch((err) => console.error(err))
            .finally(() => {
              this.btnLoading = false
            })
        }
      })
    },
    getstatus(id) {
      this.timer = setInterval(() => {
        querystatus(id).then(res => {
          if (res.data !== '0') {
            this.$message.success('上传成功，可查看任务')
            this.$emit('onRefreshTable')
            this.timer && clearInterval(this.timer)
          }
        })
      }, 4000)
    },
    onOpen() {
      this.visible = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    getFileName() {
      if (isEmpty(this.fileDataArr)) {
        return ''
      }
      return this.fileDataArr[0].name
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form--inline .el-form-item {
  display: flex;
}
.import-upload {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  ::v-deep .el-upload {
    width: 630px;
    .el-upload-dragger {
      background-color: #f7f8fa;
      border: 1px dashed #cccccc;
      width: 100%;
      height: 200px;
      border-radius: 2px;
    }
    .el-icon-upload {
      margin: 40px 0 13px;
    }
    .upload-btn {
      margin: 24px 0 16px 0;
    }
    .el-upload__text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
  }
}
.common-header-title {
  margin-bottom: 24px;
}
.select-cnt {
  width: 700px;
  margin: 20px auto 50px auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  > span {
    display: inline-block;
    width: 56px;
  }
  .el-select {
    flex: 1;
  }
}
.el-upload__tip {
  margin-top: 20px;
}
.list-header {
  clear: both;
  > p {
    font-size: 0;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    > span {
      font-size: 14px;
      color: #212121;
      display: inline-block;
      letter-spacing: normal;
      word-spacing: normal;
      width: 10%;
      margin-right: 12px;
    }
  }
  ul {
    max-height: 50vh;
    margin: 0;
    list-style: none;
    padding: 0;
    .form-vl {
      display: flex;
      align-items: center;
      ::v-deep .el-form-item {
        margin-right: 12px;
        margin-bottom: 0;
        width: 10%;
        .el-form-item__content {
          display: flex;
          span {
            display: inline-block;
            max-width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        &.is-error .el-form-item__content {
          width: 62%;
        }
      }
    }
    .el-icon-remove-outline,
    .el-icon-circle-plus-outline {
      font-size: 24px;
      cursor: pointer;
    }
    .disabeld-icon {
      color: #dcdfe6;
      cursor: not-allowed;
      pointer-events: none;
    }
  }
}
.file-name {
  color: #666666;
  font-size: 12px;
  font-weight: 400;
  margin-top: 2px;
  cursor: default;
  .el-icon-close {
    margin-left: 50px;
    visibility: hidden;
    cursor: pointer;
  }
  &.is-show-del {
    .el-icon-close {
      visibility: visible;
    }
  }
}
.upload-cloud {
  width: 50px;
  height: 50px;
  margin: 4px 0 10px 0;
}
</style>

<style lang="scss">
.import-modal-wrap {
  .el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
  }
}
</style>