<template>
  <div class="pageContent taskSubmission">
    <van-nav-bar
      title="提交任务"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
      @click-right="() => {}"
      :fixed="true"
    >
      <template #right>
        <div class="submit" @click="submit">提交</div>
      </template>
    </van-nav-bar>
    <div class="content">
      <textarea
        name=""
        id="textarea"
        maxlength="1000"
        v-model="textarea"
        placeholder="请按照要求完成任务"
        style="resize: none; height: 300px"
        ref="textarea"
        @input="inputInfo($event)"
      ></textarea>
      <div class="files">
        <div class="file-item" v-for="(item, index) in subFiles" :key="index">
          <div class="file-icon" v-if="item.type === 'video'">
            <van-icon name="video-o"></van-icon>
          </div>
          <div class="file-icon luyin" v-else-if="item.type === 'vote'">
            <van-icon name="luyin" class-prefix="iconfont"></van-icon>
          </div>
          <van-image class="file-image" fit="cover" :src="item.base64" v-else-if="item.type === 'image'"></van-image>
          <div class="file-name">{{ item.file.name }}</div>
          <div class="file-delete" @click="onDelete(index)">
            <van-icon name="cross"></van-icon>
          </div>
        </div>
      </div>
      <div class="other">
        <div class="tools">
          <div class="tool" @click="onSelect('vote')">
            <van-icon class="tool-icon" name="luyin" class-prefix="iconfont"></van-icon>
            <div class="tool-text">录音</div>
          </div>
          <div class="tool" @click="onSelect('image')">
            <van-icon class="tool-icon" name="photo-o"></van-icon>
            <div class="tool-text">图片</div>
          </div>
          <div class="tool" @click="onSelect('video')">
            <van-icon class="tool-icon" name="video-o"></van-icon>
            <div class="tool-text">视频</div>
          </div>
        </div>
        <div class="number">{{ textarea.length }}/1000</div>
      </div>
    </div>

    <div class="taskDemand">任务要求</div>

    <input
      ref="votefile"
      type="file"
      class="file"
      id="votefile"
      accept="audio/mp3,audio/mp4"
      @click="
        e => {
          e.target.value = '';
        }
      "
      @change="onChange('vote')"
    />
    <input
      ref="imagefile"
      type="file"
      class="file"
      id="imagefile"
      accept="image/png,image/jpeg,image/jpg"
      @click="
        e => {
          e.target.value = '';
        }
      "
      @change="onChange('image')"
    />
    <input
      ref="videofile"
      type="file"
      class="file"
      id="videofile"
      accept="video/mp4"
      @click="
        e => {
          e.target.value = '';
        }
      "
      @change="onChange('video')"
    />
  </div>
</template>

<script>
import development from '@/api/development';

export default {
  components: {},
  data() {
    return {
      id: 1,
      rankId: 1,
      textarea: '',
      subFiles: [],
      only: true, // 文件是否唯一
      maxFile: 3, // 最大文件数量 仅only=false时有效
      maxFileSize: 200 // 最大文件大小MB
    };
  },
  mounted() {
    let id = this.$route.params.id;
    let rankId = this.$route.params.rankId;
    if (id && rankId) {
      this.id = id;
      this.rankId = rankId;
    } else {
      this.$toast('参数错误');
      setTimeout(() => {
        this.$router.back();
      }, 2000);
      return;
    }
    this.initData();
  },
  watch: {
    textarea() {
      let textArea = this.$refs['textarea'];
      if (textArea.scrollHeight > 300) {
        textArea.style.height = textArea.scrollHeight + 'px';
      } else {
        textArea.style.height = 300 + 'px';
      }
    }
  },
  methods: {
    async initData() {},
    async submit() {
      if (!this.subFiles.length) {
        this.$toast('请选择文件');
        return;
      }
      this.$toast.loading({
        forbidClick: true,
        duration: 0,
      });
      if (this.subFiles.length) {
        let re = await this.subFile();
        if (!re) {
          this.$toast('文件上传失败,请重新提交');
          return;
        }
      }
      console.log(
        this.subFiles.map(item => {
          return item.url;
        })
      );
      // 提交任务
      let re = await development.SubmitTask({
        id: this.id,
        uploadData: {
          content: this.textarea,
          file: this.subFiles
            .map(item => {
              return item.url;
            })
            .join(';')
        }
      });
      if (re) {
        if (re.succeed) {
          this.$toast('提交成功');
          setTimeout(() => {
            this.$router.back();
          }, 2000);
        } else {
          this.$toast(re.message);
        }
      } else {
        this.$toast('提交失败');
      }
    },
    async subFile() {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async resolve => {
        // for遍历subFiles数组
        for (let i = 0; i < this.subFiles.length; i++) {
          let item = { ...this.subFiles[i] };
          if (!item.url) {
            let formData = new FormData();
            formData.set('fileName', item.file.name);
            formData.set('file', item.file);
            let re = await development.UploadFile({ formData });
            if (!re || !re.succeed) {
              resolve(false);
              return;
            } else {
              item.url = re.data.url;
              this.subFiles[i] = item;
            }
          }
        }
        resolve(true);
      });
    },
    onSelect(type) {
      console.log(type);
      this.$refs[type + 'file'].click();
    },
    onDelete(index) {
      this.subFiles.splice(index, 1);
    },
    onChange(type) {
      const file = this.$refs[type + 'file'].files[0];
      console.log(file);

      // 最大文件大小
      if (file.size > this.maxFileSize * 1024 * 1024) {
        this.$toast(`文件大小不能超过${this.maxFileSize}MB`);
        return;
      }

      if (type === 'image') {
        this.blobToDataURL(file, base64 => {
          this.pushFileData({
            type,
            base64,
            file
          });
        });
      } else {
        this.pushFileData({
          type,
          file
        });
      }
      // const formData = new FormData();
      // formData.append('file', file);
      // formData.append('type', type);
      // console.log(formData);
    },
    pushFileData(fileData) {
      if (this.only) {
        this.subFiles = [fileData];
      } else {
        if (this.subFiles.length < this.maxFile) {
          this.subFiles.push(fileData);
        } else {
          this.$toast(`最多上传${this.maxFile}个文件`);
        }
      }
    },
    // 图片转base64
    blobToDataURL(blob, callBack) {
      let reader = new FileReader();
      reader.onload = function (evt) {
        let base64 = evt.target.result;
        callBack(base64);
      };
      reader.readAsDataURL(blob);
    },
    inputInfo(event) {
      event.target.style.height = '300px'; // 默为空时的高度设置
    }
  }
};
</script>

<style scoped lang="scss">
@import './include.scss';
@font-face {
  font-family: 'iconfont'; /* Project id 2652084 */
  src: url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAANEAAsAAAAABxwAAAL2AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACCcAqCGIIcATYCJAMICwYABCAFhGcHLxtXBsgeg207eZwyVtIpsOplBI9rn/OSHBH6c6exoBhk9X7ZspEVtsojGbE/2r2vkFPpV2buw7mUmIgZXrt5I7euHSahADJ9/u+d/hbhBfDWHLQ2PrA8oA/UWMsi7OQFxi2yuwKxyGcE2u2KpniYnFkIuo/qqAQsKTPbgyQ3HvG5daAuBBQFp1uFZujSIt5CE+mZ4jneBO+P//ZDnaQpMwtO7iQ1wuGvDmtErv4r8gfVeA14eEITMjZXZorzzY4jSlFik5L2KoeyeVJbBL866toTrPuPRxDNzOxOMIkF5yR0RKf6ywQKWnANaPQqoKV0ThsYuFvd1IL2C9pDm31bWjovNnrXi4eKH63R0VgbXoHqoejhxdNTSlt4j3e7OPT4GLnx9PTi4UGq7u+vDN1fh7IbiOyutOz28bwOdN7UHIuhNXX5rjpyKnLb30Mn1iRWx03XuwotL0or3Evd/FMD0yq07SzstDNK2tIdshx3F5JCRWZBWlHOrZta6lbhLhElsYGJZYFRQYmlVDYkTS0NCg+JL2cDkocDSl1ynMMda4kz39bGuERUTPevz7Ohs4OVE7pyk1x9b2WtWQ7EAtRzt5LkB3zHw6c7XTV6ka+tHQV8fefUFoyoF8hPALSeoSN43cpLQGLRgqRSJRQyyTVqdyBrt8LUTE+/576agdvKhFYDN+dqMZEgazXPKJx1NOmwj2atDtBuQ9LqDgNklERpw7IBhNBrA0m398h6HTEK5wlNhr2gWa9ftLsYOtt1WI6GBILrKG5E9W2I3yCVMLaaBnTzMbdJVEfKosWYsHwcRn4c33w6BUswGWIG28z1p5RBDJGKUTJ3GhaJpEhGpALcQDk8SmXhPj5M1Us4DVIxJCCwOhTWCKnXBuFrICXBeGSa/bx8GFcTkToEyChOECw+po/44fAFMFIUElDLlezCasblj6IYCIOglBiSLAzCRESkEFn1IAGsAcXB6xGTCedjkRiogjO/SvxoO6CdqU1h9cmaHjW18SUAAAA=');
}

.iconfont {
  font-family: 'iconfont' !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.iconfont-luyin:before {
  content: '\e60b';
}

.taskSubmission {
  .submit {
    color: white;
    font-size: 25px;
    border-radius: 40px;
    padding: 5px 50px;
    background: black;
  }

  .content {
    background: white;
    border-radius: 12px;
    padding: 10px;

    #textarea {
      width: 100%;
      font-size: 30px;
    }

    .files {
      display: flex;
      flex-wrap: wrap;
      width: 100%;

      .file-item {
        overflow: hidden;
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 200px;
        height: 200px;
        color: black;
        border-radius: 10px;
        margin-right: 20px;
        margin-bottom: 20px;
        background: #e8e8e8;

        .file-icon {
          i {
            font-size: 60px;
          }
        }
        .file-image {
          position: absolute;
          left: 0;
          top: 0;
          width: 200px;
          height: 200px;
          z-index: 98;
        }
        .file-name {
          width: 100%;
          text-align: center;
          font-size: 22px;
        }
        .file-delete {
          position: absolute;
          top: 5px;
          right: 5px;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 50px;
          height: 50px;
          font-size: 30px;
          color: red;
          border-radius: 50%;
          background: white;
          z-index: 99;
        }
      }
    }
    .other {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      padding: 10px 0;

      .tools {
        display: flex;
        align-items: center;
        .tool {
          font-size: 25px;
          text-align: center;
          margin-right: 30px;
          .tool-icon {
            font-size: 60px;
          }
        }
      }

      .number {
        font-size: 25px;
        color: gray;
      }
    }
  }
  .taskDemand {
    padding: 20px 0;
    font-size: 30px;
    color: gray;
  }

  .file {
    display: none;
  }
}
</style>
