<template>
  <div>
    <p style="margin-top:17px;margin-bottom:15px;font-size:14px;">备注 <span v-if="num&&num!=''"> ({{num}})</span>
    </p>
    <div class="clearfix" style="display: flex;" v-if="doneOrNotDone==1&&type=='1'">
      <!-- 添加备注，上传图片 -->
      <div style="height:32px;width:22px;background-color:#fff;float:left;border-radius:3px 0 0 0;border:1px solid #E0E0E0;border-right-style:none;">
        <input ref="file" type="file" @change="readFile" class="upLoadImg inputfile">
        <Icon @click.native="upLoadImg" type="ios-attach" style="float:left" size="24" />
      </div>
      <div class="addbeizhu">
        <Input placeholder="添加备注" class="inp" v-model="comments" @on-change="changeAddStatus">
        <div slot="suffix" class="blue_link">
          <p style="line-height: 32px;" @click.stop="saveComment" v-if="addStatus==true">添加</p>
        </div>
        </Input>
      </div>
    </div>
    <div v-if="tipData.length>0">
      <div v-for="(item,index) in tipData" :key="index">
        <div class="tip-title">
          <p style="font-size:14px">
            <span class="blue_link">{{item.commentUserName}}</span>
            <span v-if="item.comments != '上传附件'">添加了备注</span>
            <span v-else="item.comments">添加了附件</span>
          </p>
          <p>
            <!-- 只能删除自己的评论，其他人的不可以删除 -->
            <span v-if="item.commentUserId == userId" class="blue_link" @click="deleteComment(item.commentId )">删除</span>
            <span style="color:#b0b0b0">{{ formDate(item.createDate)}}</span>
          </p>
        </div>
        <div style="color:#666;margin:8px 0 15px 0;font-size:13px;" v-if="item.comments != '上传附件'">“{{item.comments }}”</div>
        <div v-if="item.attachment && item.attachment.length>0" style="padding:0px 11px;">
          <!-- <div style="color:#919191;display:inline-block">附件：</div> -->
          <div class="attachment">
            <!-- 图片实现点击放大缩小功能，未完善 -->
            <template v-for="fujian in item.attachmentArr">
              <img :key="fujian.fileId" v-if="isPic(fujian.fileName)" @click="showImgPreview(fujian.filePath)" :class="{'active':isChoose}" style="width:70px;height:70px;" :src="fujian.filePath">
              <div :key="fujian.fileId" v-else @click="viewFile(fujian.filePath)" class="blue_link" style="font-size:12px;">{{fujian.fileName }}
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <van-popup get-container="body" class="van-dialog__preview" v-model="showPreview" position="right" :style="{ width: '100%',height:'100%','backgroundColor':'transparent'}"><div class="flexImgBox">
      <div class="imgBox">
        <img :src="previewUrl">
      </div>
      <div class="previewBtn">
        <van-icon @click="closePreview" size="30"  name="close" />
      </div>
    </div>
    </van-popup>
  </div>
</template>
<script>
import {

  getApproveComment, //根据审批项ID获取备注详情
  saveComment, //添加备注
  deleteComment, //删除备注

} from "../service/getData.js"
export default {
  props: {
    type: {
      default: ''
    }
  },
  created() {
    if (process.env.NODE_ENV == 'production') {
      this.url = process.env.Url + '/landcrm/rest/uploadFileInfo/uploadMutiFile'
    }
    // 获取备注
    this.getApproveComment(this.$route.query.auditItemId);
    this.doneOrNotDone = this.$route.query.doneOrNotDone
  },
  methods: {
    isPic(flag) {
      var reg = /\.(png|jpg|gif|jpeg|webp)$/;
      return reg.test(flag);
    },
    readFile(e) {
      if (!e.target.files[0]) return;
      let _this = this;
      let file = e.target.files[0];
      let formData = new FormData();
      formData.append("file", file);
      fetch(this.url, {
          method: "POST",
          body: formData
        })
        .then(res => res.json())
        .then(data => {
          this.upLoadData = data.fileInfo
          this.uploadSuccess()
        })
    },
    uploadSuccess(file, fileList) { //附件上传成功
      this.$Message.success("添加附件成功");
      let uploadFiles = {
        fileId: "",
        fileName: "",
        filePath: ""
      }
      // console.log('uploadFiles',uploadFiles)
      // console.log('21321',typeof(this.upLoadData))
      // this.uploadFiles = uploadFiles
      uploadFiles.fileId = this.upLoadData.fid
      uploadFiles.fileName = this.upLoadData.fName
      uploadFiles.filePath = this.upLoadData.resPath
      this.uploadFiles = JSON.stringify(uploadFiles);
      this.uploadImg();
    },
    // 上传图片备注
    uploadImg() {
      let self = this;
      var saveData = {
        auditItemId: this.$route.query.auditItemId,
        commentUserId: localStorage.getItem('memberId'), // 审批任务的代办人ID
        commentUserAccount: localStorage.getItem('userAccount'), //备注人账号
        commentUserName: localStorage.getItem('userName'), // 操作人
        attachment: self.uploadFiles,
        comments: '上传附件'
      }
      saveComment(saveData).then(res => {
        if (res.status == 200) {
          self.uploadFiles = '';
          self.tipData = []
          self.getApproveComment(this.$route.query.auditItemId)
        }
      })

    },
    uploadError(error, file, fileList) { //文件上传失败时的钩子
      this.$Modal.warning({
        title: '错误',
        content: '文件上传失败',
      });
    },
    //添加备注
    saveComment() {

      var self = this;
      var saveData = {
        auditItemId: this.$route.query.auditItemId, // 审批项ID
        comments: self.comments, //备注人内容

        commentUserId: localStorage.getItem('memberId'), // 审批任务的代办人ID

        commentUserAccount: localStorage.getItem('userAccount'), //备注人账号

        commentUserName: localStorage.getItem('userName') // 操作人
      }
      if (self.uploadFiles && self.uploadFiles != '') {
        saveData.attachment = self.uploadFiles
      }
      if (self.comments && self.comments != "") {
        saveComment(saveData).then(res => {
          if (res.status == 200) {
            self.tipData = []
            self.getApproveComment(this.$route.query.auditItemId)
          }
        })
      } else {
        self.$Message.error("备注内容不能为空")
      }

    },
    // 根据审批项ID获取备注详情
    getApproveComment(id) {
      var self = this;
      var searchForm = {
        auditItemId: id, //审批项ID
      }
      getApproveComment(searchForm).then(res => {
        if (res.status == 200) {
          let data = res.data || [];
          data.forEach(item => {
            if (item.attachment) {
              let attachment = JSON.parse(item.attachment);
              if (Array.isArray(attachment)) {
                item.attachmentArr = attachment;
              } else {
                item.attachmentArr = [attachment];
              }
            }
          })
          self.tipData = data;
          self.comments = "";
          self.num = self.tipData.length;
        } else {
          self.$Message.error(res.message)
        }
      })
    },
    changeAddStatus() {
      if (this.comments && this.comments != '') {
        this.addStatus = true;
      } else {
        this.addStatus = false;
      }
    },
    // 设置时间轴时间
    formDate(date) {
      if (date && date != "") {
        var str = "";
        var arr = date.split(" ");
        str += arr[0].match(/\d{2}-\d{2}$/) + " " + arr[1].match(/^\d{2}:\d{2}/);
        return str
      }
    },
    // 图片放大缩小
    imgScc: function(filePath) {
      this.isChoose = !this.isChoose
    },
    // 根据附件为文件跳转查看
    viewFile(url) {
      window.open(url)
    },
    //删除备注
    deleteComment(id) {
      var self = this;
      var deletForm = {
        commentId: id //备注ID
      };
      deleteComment(deletForm).then(res => {
        if (res.status == 200) {
          self.tipData = [];
          self.getApproveComment(this.$route.query.auditItemId)
        }
      });
    },
    showImgPreview(url){
      this.previewUrl = url;
      this.showPreview = true;
    },
    closePreview(){
      this.showPreview = false;
    }
  },
  data() {
    return {
      url: '/landcrm/rest/uploadFileInfo/uploadMutiFile',
      userId: localStorage.userId,
      doneOrNotDone: '',
      flag: true,
      tipData: [],
      upLoadData: [],
      comments: '',
      num: '',
      processKey: this.$route.query.processKey,
      addStatus: false, //备注里的添加显示状态
      isChoose: false, //图片放大缩小类的添加
      showPreview:false,
      previewUrl:'',
    }
  }
}

</script>
<style scoped>
.inputfile {
  position: absolute;
  /*left:-99999px;*/
  opacity: 0;
  width: 25px;
  height: 32px;
  z-index: 2;
}

/* 操作按钮 */
.blue_link {
  color: #2D8CF0;
  display: inline-block;
  margin-right: 3px;
  font-size: 14px;
  cursor: pointer;
  text-decoration: none;

  .left_icon {
    float: left;
    font-size: 20px;
    margin: -2px 5px 0 0;
  }
}

.blue_link:hover {
  color: #1860ad;

}

.addbeizhu {
  height: 32px;
  flex: 1;
  /* background-color: red; */
}

.inp {

  float: left !important;
  width: 93%;
}

.inp /deep/ .ivu-input {
  border-radius: 0px 3px 0px 0px !important;
  border-left-style: none !important;
}

.line-date {
  color: #6A6A6A;
  font-size: 12px;
  padding: 0 0 5px;
  text-align: right;
}

.flexImgBox{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.imgBox{
  flex:1;
  display: flex;
  align-items: center;
}
.previewBtn{
  height: 60px;
  text-align: center;
  color:#fff;
  line-height: 60px;
}
</style>
