<!--
 * @desc B端服务 - 企业通用
 * @author linyuanjie
 * @date 2023/9/23
-->

<template>
  <div class="do-task">
    <div class="mb12">
      <el-button @click="backFn">后退</el-button>
    </div>
    <div>
      <span class="f18 fwb clr_333">提交任务</span> - <span>企业通用</span>
    </div>
    <div class="form-wrapper">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="140px">
        <el-form-item label="关联企业包：" prop="packageId">
          <el-select
            class="w100"
            v-model="formData.packageId"
            placeholder="请选择">
            <el-option
              v-for="item in relatedEntPackList"
              :key="item.id"
              :label="item.scorePackageName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目主题：" prop="meetingtTitle">
          <el-input v-model="formData.meetingtTitle" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="项目时间：" prop="meetingTime">
          <el-date-picker
            v-model="formData.meetingTime"
            class="w100"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="文件上传：" prop="files">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="headers"
            :before-upload="beforeFileUpload"
            :on-remove="(file, fileList) => { handleFileRemove(file, fileList, 'files') }"
            :before-remove="beforeFileRemove"
            :on-success="(response, file, fileList) => { handleFileSuccess(response, file, fileList, 'files') }"
            :on-error="(err, file, fileList) => { handleFileError(err, file, fileList, 'files') }"
            :file-list="importFileObj['files']"
            :show-file-list="false">
            <el-button icon="el-icon-upload">上传文件</el-button>
          </el-upload>
          <div class="file-list pl4">
            <div v-for="(item, index) in importFileObj['files']" :key="item.url" class="file-item pr4 pointer">
              <div>
                <i class="el-icon-tickets mr7" /><span class="file-item-name">{{ item.name }}</span>
              </div>
              <div class="file-item-right">
                <span v-if="imgTypeList.includes(item.url.split('.')[1])" class="file-item-view f12 mr8" @click="viewImgFn(item)">查看</span>
                <i class="el-icon-close" @click="removeFileFn(item.url, index, 'files')" />
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="外采费用：" prop="outsourcingAmount">
          <el-input-number v-model="formData.outsourcingAmount" controls-position="right" :min="0" class="w100 input-num-box" />
        </el-form-item>
        <el-form-item
          label="凭证："
          prop="outsourcingAmountProof"
          :required="!!formData.outsourcingAmount"
          :rules="{ message: '请上传凭证', trigger: 'blur', type: 'array' }">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="headers"
            :before-upload="beforeFileUpload"
            :on-remove="(file, fileList) => { handleFileRemove(file, fileList, 'outsourcingAmountProof') }"
            :before-remove="beforeFileRemove"
            :on-success="(response, file, fileList) => { handleFileSuccess(response, file, fileList, 'outsourcingAmountProof') }"
            :on-error="(err, file, fileList) => { handleFileError(err, file, fileList, 'outsourcingAmountProof') }"
            :file-list="importFileObj['outsourcingAmountProof']"
            :show-file-list="false">
            <el-button icon="el-icon-upload">上传文件</el-button>
          </el-upload>
          <div class="file-list pl4">
            <div v-for="(item, index) in importFileObj['outsourcingAmountProof']" :key="item.url" class="file-item pr4 pointer">
              <div>
                <i class="el-icon-tickets mr7" /><span class="file-item-name">{{ item.name }}</span>
              </div>
              <div class="file-item-right">
                <span v-if="imgTypeList.includes(item.url.split('.')[1])" class="file-item-view f12 mr8" @click="viewImgFn(item)">查看</span>
                <i class="el-icon-close" @click="removeFileFn(item.url, index, 'outsourcingAmountProof')" />
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="任务积分：" prop="score">
          <el-input-number v-model="formData.score" controls-position="right" :min="0" class="w100 input-num-box" />
        </el-form-item>
        <el-form-item label="会议总结:" prop="meetingSummary">
          <el-input type="textarea" v-model="formData.meetingSummary" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="saveFn">保 存</el-button>
        <el-button type="primary" size="small" @click="submitFn">提 交</el-button>
      </div>
    </div>
    <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="viewerList" />
  </div>
</template>

<script>
import {getEntTaskTemp, getRelatedEntPackList, saveTaskCommon, saveTaskCommonTemp} from "@/api/enterpriseTask"
import store from "@/store";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";

export default {
  name: "doTaskCommon",
  components: { ElImageViewer },
  data () {
    return {
      taskTypeId: 61,
      headers: {
        Authorization: 'Bearer ' + store.getters.access_token
      },
      uploadUrl: '/admin/sys-file/upload',
      formData: {
        files: [],
        outsourcingAmountProof: []
      },
      formRules: {
        packageId: [{ required: true, message: '请选择关联积分包', trigger: 'blur' }],
        score: [{ required: true, message: '请输入任务积分', trigger: 'blur' }],
        meetingtTitle: [{ required: true, message: '请输入项目主题', trigger: 'blur' }],
        meetingTime: [{ required: true, message: '请选择项目时间', trigger: 'blur' }],
        files: [{ required: true, message: '请上传会议邀请函', trigger: 'blur' }],
      },
      relatedEntPackList: [], // 关联企业包
      importFileObj: {
        files: [],
        outsourcingAmountProof: []
      }, // 所有上传文件
      fileTypeLimit: [
        // 图片
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp',
        'image/jpg',
        // word
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        // excel
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        // pdf
        'application/pdf',
        'application/x-pdf',
        // ppt
        'application/vnd.ms-powerpoint', // .ppt
        'application/vnd.openxmlformats-officedocument.presentationml.presentation' // .pptx
      ], // 支持上传的文件类型
      imgTypeList: ['jpeg', 'jpg', 'png', 'git', 'bmp'], // 能查看的文件类型
      showViewer: false,
      viewerList: []
    }
  },
  methods: {
    async saveFn () {
      const params = {
        ...this.formData,
        files: this.importFileObj['files'].map(ele => ({
          fileName: ele.name,
          url: ele.url
        })),
        outsourcingAmountProof: this.importFileObj['outsourcingAmountProof'].map(ele => ({
          fileName: ele.name,
          url: ele.url
        }))
      }
      const res = await saveTaskCommonTemp(params)
      if (res.data.code === 0) {
        this.$message.success('保存成功')
        this.backFn()
      }
    },
    submitFn () {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          const params = {
            ...this.formData,
            files: this.importFileObj['files'].map(ele => ({
              fileName: ele.name,
              url: ele.url
            })),
            outsourcingAmountProof: this.importFileObj['outsourcingAmountProof'].map(ele => ({
              fileName: ele.name,
              url: ele.url
            }))
          }
          const res = await saveTaskCommon(params)
          if (res.data.code === 0) {
            this.$message.success('提交成功')
            this.backFn()
          }
        } else {
          return false
        }
      })
    },
    // 获取B端服务保存缓存数据
    async getEntTaskTempFn () {
      const res = await getEntTaskTemp(this.taskTypeId)
      if (res.data.code === 0 && res.data.data) {
        const data = res.data.data
        this.formData = Object.assign({}, data)
        this.formData.files = Array.isArray(data.files) ? data.files.map(ele => ele.url) : []
        this.importFileObj.files = Array.isArray(data.files) ? data.files.map(ele => ({ name: ele.fileName, url: ele.url })) : []

        this.formData.outsourcingAmountProof = Array.isArray(data.outsourcingAmountProof) ? data.outsourcingAmountProof.map(ele => ele.url) : []
        this.importFileObj.outsourcingAmountProof = Array.isArray(data.outsourcingAmountProof) ? data.outsourcingAmountProof.map(ele => ({ name: ele.fileName, url: ele.url })) : []
      }
    },
    async getRelatedEntPackListFn () {
      const res = await getRelatedEntPackList()
      console.log(res);
      if (res.data.code === 0) {
        this.relatedEntPackList = res.data.data || []
      }
    },
    backFn () {
      this.$emit('back')
    },
    beforeFileUpload (file) {
      if (!this.fileTypeLimit.includes(file.type)) {
        this.$message.warning('不支持的文件格式');
        return false
      }
    },
    beforeFileRemove (file, _fileList) {
      if (file.status === 'success') {
        return this.$confirm(`确定移除 ${ file.name }？`);
      }
    },
    removeFileFn (url, index, itemName) {
      this.importFileObj[itemName].splice()
      this.$confirm(`确定移除${url}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.importFileObj[itemName].splice(index, 1)
        this.formData[itemName].splice(index, 1)
      }).catch(() => {})
    },
    handleFileRemove (file, _fileList, fileIdx) {
      const delIdx = this.importFileObj[fileIdx].findIndex(ele => ele.url === file.url)
      this.importFileObj[fileIdx].splice(delIdx, 1)
      this.$set(this.importFileObj, fileIdx, [...this.importFileObj[fileIdx]])
    },
    handleFileSuccess (res, file, fileList, fileIdx) {
      if (res.code === 0) {
        this.$set(this.importFileObj, fileIdx, [...this.importFileObj[fileIdx], { name: file.name, url: res.data.url }])
        this.formData[fileIdx] = [...this.formData[fileIdx], res.data.url]
        this.$message.success('上传成功！')
      }
    },
    handleFileError () {
      this.$message.error('上传失败！')
    },
    viewImgFn (fileItem) {
      this.viewerList = [fileItem.url]
      this.showViewer = true
    },
    closeViewer () {
      this.showViewer = false
    }
  },
  mounted () {
    this.getRelatedEntPackListFn()
    this.getEntTaskTempFn()
  }
}
</script>

<style lang="scss" scoped>
.do-task {
  position: relative;
  .form-wrapper {
    margin-top: 36px;
    .file-list {
      margin-top: 12px;
      .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .file-item-name {
          color: #606266;
        }
        &:hover {
          background-color: #f5f7fa;
          .file-item-name {
            color: #2d8cf0;
          }
        }
        .file-item-right {
          .file-item-view {
            &:hover {
              color: #2d8cf0;
            }
          }
          .el-icon-close {
            &:hover {
              color: #606266;
            }
          }
        }
      }
    }
    .input-num-box {
      ::v-deep .el-input__inner {
        text-align: left;
      }
    }
  }
}
</style>
