<template>
  <div v-if="permission !== 'n'" class="record-wrap">
    <ul v-if="rows.length" class="ul-wrap">
      <div
        style="float: right; font-size: 20px; margin-bottom: 10px"
        @click="sort"
      >
        <i :class="sortValue ? 'icon-jiangxu' : 'icon-shengxu'"></i>
      </div>
      <li
        v-for="item in rows"
        :key="`${item.id}${Math.random()}`"
        class="item"
        :class="{
          'pending-approval': ['awaiting_check', 'awaiting_feedback'].includes(
            item.status
          ),
        }"
      >
        <div
          class="status-icon"
          :class="{
            'error-color': ['reject', 'backToStart'].includes(item.status),
            'warning-color': item.status === 'retracted',
          }"
        >
          <i :class="statusMap[item.status] || 'icon-tongyizhuangtai'"></i>
        </div>
        <div class="item-right">
          <div class="right-top">
            <div class="bottom-left-text" :title="item.taskName">
              {{ item.taskName }}
            </div>
            <span
              v-if="
                ['awaiting_check', 'awaiting_feedback'].includes(item.status)
              "
              class="top-right-text"
            >
              已停留 {{ formatTimeLag(item) }}
            </span>
            <span v-else class="top-right-text">
              {{ item.completeTime || '-' }}
            </span>
          </div>
          <div class="right-top right-bottom">
            <div
              class="left-text-box"
              :class="{
                'warn-icon-box':
                  !formatQualfieds(item.qualfieds).length && !avatarName(item),
              }"
            >
              <div class="left-img-box">
                <!-- 未审批 组织、用户-->
                <template
                  v-if="
                    formatQualfieds(item.qualfieds).length > 0 &&
                    formatQualfieds(item.qualfieds)[0].type == 'group' &&
                    !item.auditor
                  "
                >
                  <div
                    class="icon avatar-icon"
                    :class="getHeadClass(formatQualfieds(item.qualfieds))"
                  />
                </template>
                <template
                  v-else-if="
                    formatQualfieds(item.qualfieds).length > 0 &&
                    formatQualfieds(item.qualfieds)[0].type == 'user' &&
                    !item.auditor &&
                    avatarMap[item.qualfieds[0].id]
                  "
                >
                  <img
                    class="image"
                    :src="imgSrc(formatQualfieds(item.qualfieds)[0].id)"
                  />
                </template>
                <!-- 当审批后是 group 时 -->

                <img
                  v-else-if="item.auditor && avatarMap[item.auditor]"
                  class="image"
                  :src="imgSrc(item.auditor)"
                />
                <span v-else-if="avatarName(item)" class="text">
                  {{ avatarName(item) }}
                </span>
                <ht-icon v-else name="warn"></ht-icon>
              </div>
              <div
                v-if="
                  item.status === 'transformCancel' &&
                  item.qualfiedNames &&
                  item.auditorName !== item.qualfiedNames
                "
                class="top-left-text"
                :title="item.qualfiedNames.replace(/,/g, '/')"
              >
                {{ item.qualfiedNames.replace(/,/g, '/') }}
              </div>
              <div
                v-if="
                  item.status === 'copyto' &&
                  item.qualfiedNames &&
                  item.auditorName !== item.qualfiedNames
                "
                class="top-left-text"
                :title="item.qualfiedNames.replace(/,/g, '/')"
              >
                {{ item.qualfiedNames.replace(/,/g, '/') }}
              </div>
              <div
                v-else-if="item.status === 'artificial_end' || item.auditor"
                class="top-left-text"
                :title="item.auditorName"
              >
                {{ item.auditorName }}
              </div>
              <div
                v-else-if="
                  currentShowUser(formatQualfieds(item.qualfieds)) ||
                  (item.qualfiedNames &&
                    item.qualfiedNames.replace(/,/g, '/')) ||
                  item.auditorName
                "
                class="top-left-text"
                :title="
                  currentShowUser(formatQualfieds(item.qualfieds)) ||
                  (item.qualfiedNames &&
                    item.qualfiedNames.replace(/,/g, '/')) ||
                  item.auditorName
                "
              >
                {{
                  currentShowUser(formatQualfieds(item.qualfieds)) ||
                  (item.qualfiedNames &&
                    item.qualfiedNames.replace(/,/g, '/')) ||
                  item.auditorName
                }}
              </div>
              <div v-else class="top-left-text warn-text">
                未获取到审批人，请与管理员联系
              </div>
            </div>
            <span
              v-if="item.agentLeaderId && item.status === 'agree'"
              class="bottom-right-text gx-bg"
              :title="item.statusVal"
            >
              {{ item.statusVal }}
            </span>
            <span
              v-else
              class="bottom-right-text"
              :class="statusColorMap[item.status]"
              :title="item.statusVal"
            >
              {{ item.statusVal }}
            </span>
          </div>
          <template v-if="item.opinion">
            <moreOpinion :key="Math.random()" :item="item"></moreOpinion>
          </template>
          <template v-if="item.filesArray && item.filesArray.length">
            <div
              v-for="file of item.filesArray"
              :key="file.uid"
              class="cont files-item"
            >
              <i
                v-if="file.status == 'success'"
                class="icon"
                :class="
                  getIconClass(
                    file.name || (file.response && file.response.fileName)
                  )
                "
              ></i>

              <div class="fileName" @click="preview(file)">
                {{ file.name || (file.response && file.response.fileName) }}
              </div>
              <i class="icon-xiazai1" @click="download(file)"></i>
            </div>
          </template>
          <div v-if="item.completeTime" class="approval-time">
            审批用时：{{ formatTimeLag(item) }}
          </div>
        </div>
      </li>
    </ul>
    <div v-else class="empty-image-wrap">
      <el-image :src="noDataImg"></el-image>
      <span>暂无记录</span>
    </div>
  </div>
</template>
<script>
  import moment from 'moment'
  import _ from 'lodash'
  import moreOpinion from './moreOpinion.vue'
  import permission from '@/mixins/permission.js'

  const { saveAs } = require('file-saver')
  export default {
    name: 'HtHistoricalApproval',
    componentName: 'HtHistoricalApproval',
    components: {
      moreOpinion,
    },
    mixins: [permission],
    props: {
      instId: String,
      order: Boolean,
      taskId: String,
    },
    data() {
      return {
        nodeIdMap: {},
        src: '',
        data: { taskId: '', referOpinion: false },
        fileId: '',
        previewNodeFormDialogVisible: false,
        opinionSelectNodeId: '',
        opinionInstId: '',
        opinionTaskId: '',
        opinionFormData: '',
        opinionTaskName: '',
        opinionProcDefId: '',
        rows: [], // 表格数据
        statusMap: {
          awaiting_check: 'icon-tiaojiantongbu', //待阅
          awaiting_feedback: 'icon-tiaojiantongbu', //待阅
          agree: 'icon-tongyizhuangtai',
          retracted: 'icon-bohuizhuangtai',
          reject: 'icon-bohuizhuangtai',
          backToStart: 'icon-bohuizhuangtai',
        },
        statusColorMap: {
          awaiting_check: 'blue-bg',
          awaiting_feedback: 'blue-bg',
          retracted: 'yellow-bg',
          reject: 'red-bg',
          backToStart: 'red-bg',
          transforming: 'sky-bg',
          inqu: 'purple-bg',
          deliverto: 'zb-bg',
          addsign: 'hqjq-bg',
          revoker_to_start: 'yellow-bg',
          agent: 'agent-bg',
          revoker: 'yellow-bg',
        },
        avatarMap: {},
        noDataImg: require('@/assets/no-data.png'),
        sortValue: this.order,
      }
    },
    computed: {
      imgSrc() {
        return (userId) => {
          return this.$requestConfig.getImgSrc(this.avatarMap[userId])
        }
      },
      avatarName() {
        return (item) => {
          const userName = item.auditorName || item.qualfiedNames
          return userName && userName.replace(/,/g, '/').substr(0, 1)
        }
      },
    },
    created() {
      this.initParams()
      this.loadData()
    },
    methods: {
      formatQualfieds(data) {
        let qualfieds = data || []
        if (typeof qualfieds === 'string') {
          qualfieds = JSON.parse(qualfieds)
        }
        return qualfieds
      },
      currentShowUser(data) {
        return data.map((item) => item.name).join('/')
      },
      getAvatars(ids) {
        return this.$requestConfig.getAvatarsByUserId(ids.join(','))
      },
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (this.sortValue && columnIndex === 1) {
          if (
            this.nodeIdMap[row.taskKey].length > 1 &&
            this.nodeIdMap[row.taskKey][
              this.nodeIdMap[row.taskKey].length - 1
            ] == row
          ) {
            return {
              rowspan: this.nodeIdMap[row.taskKey].length,
              colspan: 1,
            }
          } else if (this.nodeIdMap[row.taskKey].length > 1) {
            return {
              rowspan: 0,
              colspan: 0,
            }
          } else {
            return {
              rowspan: 1,
              colspan: 1,
            }
          }
        }
      },
      getHeadClass(value) {
        const GROUP_TYPE_MAP = {
          position: 'ht-icon-gangwei',
          job: 'ht-icon-zhiwu',
          org: 'ht-icon-zuzhi',
          role: 'ht-icon-jiaose',
        }
        return GROUP_TYPE_MAP[value[0].groupType]
      },
      getIconClass(fileName) {
        if (!fileName) return ''
        let fileNameArr = fileName.split('.')
        let fileType = fileNameArr.length && fileNameArr[1]
        const FILE_TYPE_MAP = {
          docx: 'ht-icon-doc',
          doc: 'ht-icon-doc',
          xls: 'ht-icon-xls',
          xlsx: 'ht-icon-xls',
          ppt: 'ht-icon-ppt',
          pdf: 'ht-icon-pdf',
          rar: 'ht-icon-rar',
          zip: 'ht-icon-zip',
          txt: 'ht-icon-txt',
          mp4: 'ht-icon-mp4',
        }
        if (Object.keys(FILE_TYPE_MAP).includes(fileType)) {
          return FILE_TYPE_MAP[fileType]
        }
        let imgArr = ['jpeg', 'png', 'gif', 'psd', 'dds', 'webp', 'svg', 'jpg']
        if (imgArr.includes(fileType)) {
          return 'ht-icon-img'
        }
        let FileType = [
          'jpeg',
          'png',
          'gif',
          'psd',
          'dds',
          'webp',
          'svg',
          'jpg',
          'mp4',
          'txt',
          'zip',
          'rar',
          'pdf',
          'ppt',
          'xls',
          'xlsx',
          'docx',
          'doc',
        ]
        if (!FileType.includes(fileType)) {
          return 'ht-icon-qita'
        }
      },
      showQualfiedsNames(status, qualfieds, qualfiedNames) {
        const length = this.qualfiedsName(qualfiedNames, true)
        return (
          (length < 2 && status != 'awaiting_check') ||
          (status == 'awaiting_check' &&
            qualfieds &&
            qualfieds.length == 1 &&
            !qualfieds[0].users)
        )
      },
      initParams() {
        if (this.instId) {
          this.data.instId = this.instId
          this.data.taskId = this.taskId
          this.data.referOpinion = this.referOpinion
          this.data.nodeType = this.nodeType
          this.data.defId = this.defId
          this.data.nodeId = this.nodeId
          //类型为我的请求时添加参数isRequest进行过滤
          if (this.myReadType === 'request') {
            this.data.isRequest = true
          }
        }
      },
      qualfiedsName(names, isLength) {
        if (names && isLength) {
          return names.split(',').length
        }
        if (names && !isLength) {
          return names.split(',')
        }
      },
      isQualfiedListHasUser(data) {
        if (Array.isArray(data)) {
          for (let i = 0; i < data.length; i++) {
            if (data[i].users) {
              return true
            }
          }
          return false
        }
      },
      //持续时间
      formatTimeLag(row) {
        let endTimes = new moment()
        if (!row.completeTime) {
          endTimes = new moment(new Date())
        } else {
          endTimes = new moment(new Date(row.completeTime))
        }

        let createTime = new moment(new Date(row.createTime))
        let duration = moment.duration(endTimes.diff(createTime))
        let { _data } = duration
        if (_data.days > 0) return _data.days + '天'
        if (_data.hours > 0) return _data.hours + '小时'
        if (_data.minutes > 0) return _data.minutes + '分钟'
        if (_data.minutes == 0 && _data.seconds >= 0) return '小于1分钟'
      },
      search(item) {
        window.open(
          this.$requestConfig.filePreview(item.response && item.response.fileId)
        )
      },
      preview(file) {
        if (file.status !== 'success') {
          this.$message.warning(this.t('ht.file.forbiddenPreview'))
          return
        }

        window.open(
          this.$requestConfig.filePreview(file.response && file.response.fileId)
        )
      },
      download(file) {
        this.$requestConfig
          .download(file.response.fileId)
          .then(({ data, headers }) => {
            if (data && headers) {
              // 附件下载
              const fileName = decodeURIComponent(
                headers['content-disposition']
                  .split(';')[1]
                  .split('filename=')[1]
              )
              const blob = new Blob([data])
              saveAs(blob, fileName)
            }
          })
          .catch((err) => {
            this.$toast.fail(`附件下载失败：${err}`)
          })
      },

      loadData() {
        if (!this.instId && !this.taskId) {
          return
        }
        const params = {
          instId: this.instId,
          taskId: this.taskId,
          referOpinion: true,
          defId: null,
          nodeId: null,
        }
        this.$requestConfig
          .getOpinionsById(params)
          .then((response) => {
            response.map((e) => {
              if (!this.nodeIdMap[e.taskKey]) {
                this.nodeIdMap[e.taskKey] = []
              }
              this.nodeIdMap[e.taskKey].push(e)
              //有可能出现e.files是"\"\""的情况
              e.filesArray = []
              if (e.files) {
                e.files = JSON.parse(e.files)
                e.filesArray = eval(e.files)
              }
            })
            let newArr = []
            this.rows = response

            if (response && response.length) {
              const ids = response
                .map((item) => {
                  const qualfiedList = this.formatQualfieds(item.qualfieds)
                  if (item.auditor) {
                    return item.auditor
                  }
                  return qualfiedList.map((it) => it.id).join(',')
                })
                .filter(Boolean)
              this.getAvatars(_.union(ids)).then((res) => {
                this.avatarMap = res
                if (res && Object.keys(res).length) {
                  newArr = response.map((item) => {
                    const firstQualfieds = this.formatQualfieds(
                      item.qualfieds
                    )[0]
                    const manualEndUserId =
                      !item.qualfieds && item.auditor ? item.auditor : ''
                    return {
                      ...item,
                      imgSrc:
                        firstQualfieds && res[firstQualfieds.id]
                          ? this.$requestConfig.getImgSrc(
                              res[firstQualfieds.id]
                            )
                          : manualEndUserId && res[manualEndUserId]
                          ? this.$requestConfig.getImgSrc(res[manualEndUserId])
                          : '',
                    }
                  })
                  this.rows = this.sortValue ? newArr : newArr.reverse()
                  this.filterOpinions()
                }
              })
            } else {
              this.filterOpinions()
            }
          })
          .finally(() => {})
      },
      filterOpinions() {
        if (!this.rows || this.rows == undefined) {
          return
        }
        this.rows = this.rows.filter((r) => r.status != 'modify_opinion')
      },
      sort() {
        this.sortValue = !this.sortValue
        this.loadData()
      },
    },
  }
</script>
<style lang="scss" scoped>
  .record-wrap {
    height: 100%;
    .empty-image-wrap {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      ::v-deep {
        .el-image {
          width: 240px;
        }
      }
    }
  }
  .ul-wrap,
  .current-item-box {
    height: calc(100% - 48px);
    overflow: auto;
    padding: 24px 16px;
    .item {
      width: 100%;
      display: flex;
      justify-content: space-between;
      position: relative;
      &:not(:last-child) {
        &::after {
          content: '';
          position: absolute;
          width: 1px;
          background: #a8e8f2;
          left: 9px;
          top: 20px;
          height: calc(100% - 22px);
        }
      }
      .status-icon {
        width: 18px;
        height: 18px;
        line-height: 18px;
        text-align: center;
        i {
          font-size: 18px;
          color: #07c160;
        }
      }
      .left-img-box {
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        border-radius: 50%;
        background: #409eff;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 8px;
        .icon {
          font-size: 16px;
          width: 16px;
          height: 16px;
          line-height: 16px;
          border-radius: 4px;

          background-size: 100% 100%;
          padding-top: 0;

          &.ht-icon-gangwei {
            background: url(../../../src/assets/file/gangwei.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-zuzhi {
            background: url(../../../src/assets/file/zuzhi.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-jiaose {
            background: url(../../../src/assets/file/jiaose.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-zhiwu {
            background: url(../../../src/assets/file/zhiwu.svg);
            background-size: 100% 100%;
          }
        }
        .text {
          color: #fff;
          font-size: 14px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .item-right {
        flex: 1;
        width: calc(100% - 32px - 16px);
        margin-left: 16px;
        margin-bottom: 24px;
        .right-top,
        .right-bottom {
          display: flex;
          justify-content: space-between !important;
        }
        .right-top {
          line-height: 20px;
          flex-wrap: nowrap;
          .bottom-left-text {
            font-size: 14px;
            color: #262626;
            font-weight: 550;
            flex: 1;
            margin-right: 32px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .left-text-box {
            display: flex;
            align-items: center;
            width: calc(100% - 100px);

            .qualfiedNames-total {
              font-size: 12px;
              color: #8c8c8c;
              padding: 0 4px;
            }
            .more-icon {
              color: #409eff;
              font-size: 16px;
              margin-top: 1px;
            }
          }
          .warn-icon-box {
            width: unset;
            .left-img-box {
              background: transparent;
              width: 20px;
              height: 20px;
              svg {
                color: #e55555;
                width: 20px !important;
                height: 20px !important;
              }
            }
          }
          .top-right-text {
            color: #8c8c8c;
            font-size: 12px;
            white-space: nowrap;
          }
        }
        .option {
          margin: 0;
          padding: 8px;
          background: #f9f9f9;
          font-size: 12px;
          color: #262626;
          border-radius: 8px;
          line-height: 1.5;
          white-space: pre-line;
        }
        .icon {
          font-size: 16px;
          margin-right: 8px;
          width: 16px;
          height: 16px;
          border-radius: 4px;
          background: url(../../../src/assets/file/unknow.svg);
          background-size: 100% 100%;
          padding-top: 0;

          &.ht-icon-doc {
            background: url(../../../src/assets/file/doc.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-img {
            background: url(../../../src/assets/file/img.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-pdf {
            background: url(../../../src/assets/file/pdf.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-ppt {
            background: url(../../../src/assets/file/ppt.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-rar {
            background: url(../../../src/assets/file/rar.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-txt {
            background: url(../../../src/assets/file/txt.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-xls {
            background: url(../../../src/assets/file/xls.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-zip {
            background: url(../../../src/assets/file/zip.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-mp4 {
            background: url(../../../src/assets/file/mp4.svg);
            background-size: 100% 100%;
          }
          &.ht-icon-qita {
            background: url(../../../src/assets/file/qita.svg);
            background-size: 100% 100%;
          }
        }
        .avatar-icon {
          margin-right: 0;
        }
        .fileName {
          width: calc(100% - 47px);

          color: #262626;
          font-size: 12px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .cont {
          padding: 8px;
          margin: 8px 0;
          background: #f9f9f9;
          color: #262626;
          border-radius: 8px;
          display: flex;
          align-items: center;
        }
        .icon-xiazai1 {
          font-size: 16px;
          position: absolute;
          right: 8px;
          color: #8c8c8c;
        }
        .right-bottom {
          margin: 8px 0;
          height: 22px;
          line-height: 22px;
          display: flex;
          justify-content: flex-start;
          align-items: flex-start;
          .top-left-text {
            font-size: 14px;
            font-weight: 500;
            color: #262626;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .warn-text {
            color: #e55555;
          }
          .bottom-right-text {
            display: inline-block;
            padding: 0 8px;
            font-size: 12px;
            color: #07c160;
            border-radius: 4px;
            background: rgba(7, 193, 96, 0.1);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .blue-bg {
            color: #0080fe;
            background: rgba(0, 128, 254, 0.1);
          }
          .red-bg {
            color: #e55555;
            background: rgba(229, 85, 85, 0.12);
          }
          .sky-bg {
            color: #3ac3df;
            background: rgba(58, 195, 223, 0.1);
          }
          .purple-bg {
            color: #4053ff;
            background: rgba(64, 83, 255, 0.1);
          }
          .zb-bg {
            color: #73c0d4;
            background: rgba(115, 192, 212, 0.1);
          }
          .hqjq-bg {
            color: #8550e1;
            background: rgba(133, 80, 225, 0.1);
          }
          .wt-bg {
            color: #51519a;
            background: rgba(81, 81, 154, 0.1);
          }
          .gx-bg {
            color: #e57a52;
            background: rgba(229, 122, 82, 0.1);
          }
          .yellow-bg {
            color: #ffae44;
            background: rgba(255, 174, 68, 0.1);
          }
        }
        .files-item {
          cursor: pointer;
        }
      }
      .image {
        width: 24px;
        height: 24px;
        border-radius: 50%;
      }
      .green-color {
        color: #07c160;
      }
      .error-color {
        i {
          color: #e55555;
        }
      }
      .warning-color {
        i {
          color: #ffae44;
        }
      }
      .approval-time {
        color: #8c8c8c;
        line-height: 18px;
        font-size: 12px;
        padding-top: 4px;
      }
    }
    .pending-approval {
      &:not(:last-child) {
        &::after {
          background: #dcdee0;
        }
      }
      .status-icon {
        i {
          color: #0080fe;
        }
      }
    }
  }
  .opinion-container {
    padding: 8px;
    background: #f9f9f9;
  }
  .content {
    max-height: 54px;
    overflow: hidden;
    transition: max-height 0.5s;
  }
  .text-content {
    font-size: 14px;
    line-height: 18px;
    white-space: pre-line;
  }
  .btn {
    color: #409eff;
    cursor: pointer;
    font-size: 14px;
  }
  .current-item-box {
    padding: 0;
  }
  .current-item-box .item .item-right {
    margin: 0;
  }
</style>
