<template>
  <div class="signature">
    <el-tag
      v-for="(item, index) in signatureList"
      :key="item.userId"
      :index="index"
      @close="handleRemove(item)"
    >
      <el-tooltip
        class="item"
        effect="dark"
        :content="getImgMsg(item)"
        placement="top"
      >
        <img
          :ref="`signature_` + item.signature"
          class="signature-image"
          :src="item.imgSrc || getShowSignature(item)"
        />
      </el-tooltip>
    </el-tag>
  </div>
</template>
<script>
  import { getCurrentSeal } from '@/api/uc.js'
  import { fileUrl } from '@/api/portal'
  import { mapMutations, mapState } from 'vuex'
  import moment from 'moment'

  export default {
    name: 'HtSignature',
    props: {
      permission: {
        type: String,
        default: 'w',
        validator: function (value) {
          return ['b', 'w', 'r', 'n'].indexOf(value) !== -1
        },
      },
      value: {
        type: String,
        default: '',
      },
      fieldPath: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        signatureList: [],
        showSignatureMap: {},
      }
    },
    computed: {
      ...mapState('user', ['userInfo', 'username']),
      ...mapState('signature', ['signatureConfig', 'signatureStatus']),
      userId() {
        return this.userInfo?.user?.userId
      },
      getImgMsg() {
        return (item) => {
          return `${item.name}于${item.createTime}进行了签章`
        }
      },
    },
    watch: {
      signatureConfig: {
        handler(val) {
          if (val.field == this.fieldPath) {
            if (this.signatureStatus === 'start') {
              this.setSignatureStatus('ing') //发出消息，开始签章处理
              if (val.isCover) {
                this.signatureList = []
              } else {
                let index = this.getCurrentIndex(null)
                if (index >= 0) {
                  this.signatureList.splice(index, 1)
                }
              }
              this.getSignature(val.password, val.secretFree)
            }
          } else if (this.signatureStatus === 'start' && !this.fieldPath) {
            this.$message.warning(
              '未获取到签章字段路径，请初始化表单模板后重新保存表单！'
            )
          }
        },
        deep: true,
        immediate: true,
      },
    },
    mounted() {
      if (this.value) {
        this.signatureList = JSON.parse(this.value)
      }
    },
    methods: {
      ...mapMutations('signature', [
        'setSignatureConfig',
        'setSignatureStatus',
      ]),
      handleRemove(item) {
        let index = 0
        let rIdx = 0
        this.signatureList.forEach((sn) => {
          if (sn.userId == item.userId) {
            rIdx = index
          }
          index++
        })
        this.signatureList.splice(rIdx, 1)
      },
      getSignature(password, secretFree) {
        getCurrentSeal(password, secretFree).then((res) => {
          if (res.state) {
            this.reloadSignatures(res.value)
            setTimeout(() => {
              this.setSignatureStatus('success')
            }, 300)
          } else {
            this.setSignatureStatus('fail')
          }
        })
      },
      getShowSignature(item) {
        if (!item.signature)
          return this.$message.warning('未获取到签章，请检查签章配置！')
        if (!this.showSignatureMap[item.signature]) {
          this.$set(item, 'imgSrc', fileUrl(item.signature))
          this.showSignatureMap[item.signature] = item.imgSrc
        } else {
          setTimeout(() => {
            try {
              if (this.$refs['signature_' + item.signature]) {
                this.$refs['signature_' + item.signature][0].src =
                  this.showSignatureMap[item.signature]
              } else {
                this.getShowSignature(item.signature)
              }
            } catch (error) {
              return this.showSignatureMap[item.signature]
            }
          }, 100)
        }
      },
      reloadSignatures(fileId) {
        if (fileId) {
          this.showSignatureMap[fileId] = null
        }
        let index = this.getCurrentIndex(fileId)
        if (index < 0) {
          this.signatureList.push({
            index: this.signatureList.length + 1,
            userId: this.userId,
            name: this.username,
            signature: fileId,
            createTime: moment(new Date()).format('YYYY-MM-DD:HH:mm:ss'),
          })
          const submitSignatureList = this.signatureList.map((item) => {
            item.imgSrc && delete item.imgSrc
            return {
              ...item,
            }
          })
          this.$emit('input', JSON.stringify(submitSignatureList))
        }
      },
      getCurrentIndex(fileId) {
        let _this = this
        let rindex = -1
        if (this.signatureList.length > 0) {
          let index = 0
          this.signatureList.forEach((f) => {
            if (f.userId == _this.userId) {
              if (fileId) {
                f.signature = fileId
                _this.showSignatureBtn = false
              }
              rindex = index
              return rindex
            }
            index++
          })
        }
        return rindex
      },
    },
  }
</script>
<style lang="scss" scoped>
  .signature {
    ::v-deep {
      div[aria-invalid='true'] .el-input__inner,
      div[aria-invalid='true'] .el-input__inner:focus {
        border-color: #f56c6c;
      }
      .el-tag {
        margin-right: 7px;
        height: 28px;
        line-height: 26px;
        color: #666;
        background-color: transparent;
        border-color: #ebeef5;
        cursor: pointer;
        .signature-image {
          // width: 80px;
          // height: 28px;
          height: 100%;
        }
      }
    }
  }
</style>
