
<template>
  <div class="aos-flow-history">
    <div type="detail">
      <div class="radio">
        <el-radio-group v-model="reverse" @change="handleSortChange">
          <el-radio-button :label="false">正序</el-radio-button>
          <el-radio-button :label="true">倒序</el-radio-button>
        </el-radio-group>
        <el-radio-group v-model="isShowClaimData" @change="handleShowClaim" class="aos-flow-history__showClaim">
          <el-radio-button :label="true">显示认领</el-radio-button>
          <el-radio-button :label="false">不显示认领</el-radio-button>
        </el-radio-group>
        <el-button type="primary" class="aos-flow-history__comment" @click="handleShowDrawer">评论&nbsp;&nbsp;({{ total }}条)</el-button>
      </div>
      <div class="appro" v-for="ele in translateHistoryDetailList" :key="ele.id">
        <div class="title">
          <span>{{ $time.formatTime(ele.date, "yyyy-mm-dd", '/') }}</span>
          <span>{{ $time.formatTime(ele.date, "hh:mm:ss", '/') }}</span>
        </div>
        <div class="icon">
          <div class="icon-round">
            <i class="el-icon-s-check"></i>
          </div>
          <div v-if="(reverse && ele.type !== 'PROCESS_STARTED') || (!reverse && ele.type !== 'PROCESS_COMPLETED')"
            class="icon-line"></div>
        </div>
        <div class="result">
          <div class="result-title">
            <span class="title">{{ ele.taskName }}</span>
            <el-tag v-if="ele.typeName" :type="tagType(ele)" size="mini">{{
              ele.typeName
            }}</el-tag>
          </div>
          <div class="result-text" v-if="startEndType.indexOf(ele.type) < 0">
            <span class="name">{{ ele.userName }}</span>
            <span v-if="ele.orgName" class="branch">{{ ele.orgName }}</span>
            <span v-if="ele.taskConsumeTime" class="time">任务历时:{{ ele.taskConsumeTime }}</span>
            <span v-if="ele.commentNonSuspendConsumeTime" class="time">审核历时:{{ ele.commentNonSuspendConsumeTime }}</span>
          </div>
          <div class="result-message"
            v-if="startEndType.indexOf(ele.type) < 0 && (ele.remindMessage || ele.innerRemindMessage || ele.reasonMessage)">
            <span class="result-message__container"
              v-if="ele.reasonMessage && ['suspend', 'turnToward', 'transfer'].indexOf(ele.type) < 0">有条件通过意见：<span
                class="aos-flow-history__message">{{ ele.reasonMessage }}</span></span>
            <span class="result-message__container">审批意见：<span class="aos-flow-history__message">{{ ele.remindMessage
            }}</span></span>
            <span class="result-message__container" v-if="ele.innerRemindMessage" style="color: #909399">内部意见：<span
                class="aos-flow-history__message">{{ ele.innerRemindMessage }}</span></span>
            <span class="result-message__container" v-if="ele.type === 'suspend'">挂起原因：<span
                class="aos-flow-history__message">{{ ele.reasonMessage }}</span></span>
            <span class="result-message__container" v-if="ele.type === 'turnToward'">转办原因：<span
                class="aos-flow-history__message">{{ ele.reasonMessage }}</span></span>
            <span class="result-message__container" v-if="ele.type === 'transfer'">转移原因：<span
                class="aos-flow-history__message">{{ ele.reasonMessage }}</span></span>
          </div>
          <div class="aos-flow-history__file" v-if="ele.taskFiles && ele.taskFiles.length > 0"
            :id="'aos-flow-history_' + ele.id">
            <div v-for="(item, index) in ele.taskFiles" :key="index" class="aos-flow-history__file-item">
              <div class="aos-flow-history__file-item-body">
                <div v-if="otherFileTypeList.indexOf(item.fileExt) > -1" class="aos-flow-history__file-item-detail">
                  <i v-if="iconList.includes(item.fileExt)" class="iconfont" :class="'icon-' + item.fileExt"
                    style="cursor:pointer;font-size:50px;" :title="item.fileName" :name="item.fileName" />
                  <i v-if="item.fileExt === 'docx'" class="iconfont icon-doc" style="cursor:pointer;font-size:50px;"
                    :title="item.fileName" :name="item.fileName" />
                  <i v-if="item.fileExt === 'xlsx'" class="iconfont icon-doc" style="cursor:pointer;font-size:50px;"
                    :title="item.fileName" :name="item.fileName" />
                </div>
                <div v-else-if="item.fileExt === 'pdf'" class="aos-flow-history__file-item-detail"
                  @click="handleViewPdf(item)">
                  <i class="iconfont icon-pdf" style="cursor:pointer;font-size:50px;" :title="item.fileName"
                    :name="item.fileName" />
                </div>
                <div v-else-if="videoFileTypeList.indexOf(item.fileExt) > -1" class="aos-flow-history__file-item-detail"
                  @click="handleViewVideo(item)">
                  <i class="iconfont icon-mp4" style="cursor:pointer;font-size:50px;" :title="item.fileName"
                    :name="item.fileName" />
                </div>
                <div v-else-if="audioFileTypeList.indexOf(item.fileExt) > -1" class="aos-flow-history__file-item-detail"
                  @click="handleViewVideo(item)">
                  <i class="iconfont icon-mp3" style="cursor:pointer;font-size:50px;" :title="item.fileName"
                    :name="item.fileName" />
                </div>
                <div v-else class="aos-flow-history__file-item-detail"
                  @click="handleViewerImg('aos-flow-history_' + ele.id)">
                  <img style="cursor:pointer;" :src="item.realFileUrl" :alt="item.fileName" :name="item.fileName"
                    :title="item.fileName" />
                </div>
                <div class="aos-flow-history__file-item-operation">
                  <span class="aos-flow-history__file-item-operation-download" @click="handleDownload(item)">下载</span>
                </div>
              </div>
              <div class="aos-flow-history__file-item-name">{{ item.fileName + '.' + item.fileExt }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="播放器" :visible.sync="showVideDialog" append-to-body destroy-on-close width="30%"
      @close="handleVideoClose">
      <div class="aos-files__video">
        <aos-video ref="aos-flow-history-video" :options="videoOptions"></aos-video>
      </div>
    </el-dialog>
    <el-drawer title="评论" :visible.sync="showDrawer" direction="rtl" :destroy-on-close="true" size="50%">
      <div class="aos-flow-history__drawer-add">
        <el-input v-model="appendComment" placeholder="请输入评论"></el-input>
        <el-button type="primary" style="margin-left:5px" @click="handleAppendComment">添加评论</el-button>
      </div>
      <aos-table 
        ref="commentTable" 
        :data="commentList" 
        :tableTemplate="commentcTableTemplate" 
        show-pagination
        :show-setting="true" 
        :fixedHead="false" 
        :maxHight="300" :currentPage="currentPage" :pageSize="pageSize"
        :total="total" @table-current-change="handleCurrentChange" @table-size-change="handleSizeChange">
      </aos-table>
    </el-drawer>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
import Viewer from 'viewerjs-optimize';
import { commentcTableTemplate } from './model/index';
export default {
  name: "AosFlowHistory",
  props: {
    processInstanceId: {
      type: String
    }
  },
  watch: {
    processInstanceId(val, oldVal) {
      if (val && val !== oldVal) {
        this.getProcessInstanceId()
        
       // this.getIsShowComment()
      }
    }
  },
  data() {
    return {
      reverse: true,
      historyDetailList: "", // 历史审批意见,
      copyProcessInstanceId: "",
      startEndMessage: "",
      translateHistoryDetailList: [],
      startEndType: ['PROCESS_STARTED', 'PROCESS_COMPLETED'],
      userIdList: [],
      otherFileTypeList: ['docx', 'doc', 'xls', 'zip', 'xlsx', 'rar', 'txt'],
      iconList: ['bmp', 'doc', 'gif', 'mp3', 'pdf', 'ppt', 'txt', 'rar', 'xls', 'zip', 'wps', 'avi', 'mp4'],
      videoFileTypeList: ['mp4', 'webm', 'mov', 'flv'],
      audioFileTypeList: ['mp3', 'wav', 'ogg'],
      imgFileTypeList: ['png', 'jpg', 'jpeg', 'gif', 'tif', 'bmp', 'svg', 'webp'],
      showVideDialog: false,
      videoOptions: {},
      viewer: null,
      showDrawer: false,
      commentcTableTemplate: commentcTableTemplate,
      commentList: [],
      pageSize: 10,
      currentPage: 1,
      total: 0,
      appendComment: '',
      isShowClaimData:true,
    };
  },
  created() {
    this.getProcessInstanceId();
    const claim = this.$utils.userSetting.getUserSettingByName('aos-flow-history')
    if(!claim){
      this.isShowClaimData = true
      this.$utils.userSetting.setUserSettingByName('aos-flow-history','claim')
    }else if(claim ==='claim'){
      this.isShowClaimData = true
    //  this.$utils.userSetting.setUserSettingByName('aos-flow-history','claim')
    }else if(claim === 'refuse'){
      this.isShowClaimData = false
     // this.$utils.userSetting.setUserSettingByName('aos-flow-history','refuse')
    }
    //this.getIsShowComment()
  },
  methods: {
    handleShowClaim(){
      if(this.isShowClaimData){
        this.$utils.userSetting.setUserSettingByName('aos-flow-history','claim')
      }else{
        this.$utils.userSetting.setUserSettingByName('aos-flow-history','refuse')
      }
      this.getApprovalMessage()
    },
    //POST /api/v2/process-comment/append 追加评论
    handleAppendComment() {
      if(!this.appendComment){
        this.$message.error('请输入评论内容!')
        return
      }
      this.$http({
        url: '/bpm/api/v2/process-comment/append',
        method: 'post',
        data: {
          comment: this.appendComment,
          processInstId: this.copyProcessInstanceId
        }
      }).then(() => {
        this.$message({
          message: '追加评论成功',
          type: 'success'
        })
        this.appendComment = ''
        this.getAllProcessComment()
      })
    },
    //GET /api/v2/process-comment/get/{processInstId}获取评论
    getAllProcessComment() {
      this.$http({
        url: '/bpm/api/v2/process-comment/get-list/' + this.copyProcessInstanceId,
        method: 'get',
        params: {
          page: this.currentPage - 1,
          size: this.pageSize
        }
      }).then((resp) => {
        this.commentList = resp.data.content
        this.total = resp.data.totalElements
      })
    },
    handleSizeChange(size) {
      this.tableList = []
      this.pageSize = size
      this.currentPage = 1
      this.getAllProcessComment()
    },
    handleCurrentChange(page) {
      this.tableList = []
      this.currentPage = page
      this.getAllProcessComment()
    },
    handleShowDrawer() {
      this.showDrawer = true
      //this.getAllProcessComment()
    },
    handleDownload(fileItem) {
      const fileName = fileItem.fileName + '.' + fileItem.fileExt
      this.$http({
        url: fileItem.realFileUrl,
        responseType: 'blob',
      }).then((res) => {
        this.download(res.data, fileName)
      })
    },
    download(blob, name) {
      const a = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = name
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a)
    },
    handleVideoClose() {
      this.$refs['aos-flow-history-video'].destory()
    },
    handleViewPdf(item) {
      this.$openPdfViewer(item.realFileUrl)
    },
    handleViewVideo(item) {
      this.showVideDialog = true
      this.videoOptions = {
        width: 400,
        sources: [
          {
            src: item.realFileUrl,
            type: `video/${item.fileExt}`
          }
        ]
      }
    },
    handleViewerImg(id) {
      this.showImgViewer = true;
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
      this.viewer = new Viewer(document.getElementById(id), {
        className: 'aos-img-viewer-container ' + id
      });
    },
    handleViewImg() {
      const data = this.currentFiles
      if (!data.detailChildren || (data.detailChildren && data.detailChildren.length <= 0)) return
      this.removeContainer(data.id)
      let container = this.currentContainer
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
      const children = data.detailChildren
      if (!this.currentContainerId || (this.currentContainerId && this.currentContainerId !== data.id)) {
        container = this.createImgList(children, data.id)
      }
      this.currentContainerId = data.id
      this.currentContainer = container
      this.viewer = new Viewer(document.getElementById('aos-files-' + data.id), {
        className: 'aos-img-viewer-container ' + ('aos-files-' + data.id)
      });
      container.children[0].click()
    },
    getRefLabel(refCode, paramsData, resData) {
      if (!refCode) {
        this.$message({
          type: 'error',
          message: '参照对应的 refCode 不能为空.'
        });
        return;
      }
      return this.$optimizeHttp({
        url: '/core/api/ref/translate/' + refCode,
        method: 'get',
        params: {
          code: paramsData
        }
      }).then(res => {
        const refList = cloneDeep(res.data)
        const refObject = {}
        refList.forEach(item => {
          refObject[item.code] = item.value
        })
        resData.forEach(item => {
          if (item.userId) {
            item.userName = refObject[item.userId]
          }
        })
        this.translateHistoryDetailList = resData
      }).catch(() => {
        this.translateHistoryDetailList = resData
      });
    },
    arrayToObject(array) {
      if (!array && !Array.isArray(array)) return {}
      let object = {}
      array.forEach(item => {
        object[item.code] = item.value
      })
      return object
    },
    tagType(item) {
      if (item.type === 'complete') {
        return 'success'
      } else if (item.type === 'reject') {
        return 'warning'
      } else if (item.type === 'refuse') {
        return 'danger'
      }
    },
    handleSortChange() {
      this.translateHistoryDetailList.reverse();
    },
    getProcessInstanceId() {
      if (this.$route.query && this.$route.query.processInstanceId) {
        // this.processInstanceId = this.$route.query.processInstanceId
        this.copyProcessInstanceId = this.$route.query.processInstanceId;
      }
      if (this.processInstanceId) {
        this.copyProcessInstanceId = this.processInstanceId
      }
      if (this.copyProcessInstanceId) {
        this.getApprovalMessage();
        this.getAllProcessComment()
      }
    },
    // getIsShowComment(){
    //   if (this.$route.query && this.$route.query.type) {
    //    this.isShowComment = false
    //   }else{
    //     this.isShowComment = true
    //   }
    // },
    // 获取审批意见
    getApprovalMessage() {
      let filterTypes = ''
      if(this.isShowClaimData){
        filterTypes = 'refuse'
      }else{
        filterTypes ='claim'
      }
      this.$http({
        method: "get",
        url: "/bpm/api/v2/process-comments-auto-auth/" + this.copyProcessInstanceId,
        params:{filterTypes : filterTypes}
      }).then((res) => {
        const resData = res.data
        this.userIdList = []
        resData.forEach(item => {
          if (item.userId) {
            this.userIdList.push(item.userId)
          }
          if (item.taskFiles && item.taskFiles.length > 0) {
            item.taskFiles.forEach(item => {
              item.realFileUrl = '/bpm/api/task/file-download/' + item.taskId + '/' + item.commentId
              item.fileExt = item.fileSuffix.split('.')[1]
            })
          }
        })
        this.translateHistoryDetailList = resData
        if(!this.reverse){
          this.translateHistoryDetailList.reverse();
        }
        // this.getRefLabel('user', this.userIdList.join(','), resData)
      });
    },
  },
};
</script>
