<template>
  <div>
    <div
      class="signature"
      :class="{
        'vbl-height': !(signatureList && signatureList.length > 0),
        'ht-subTable': belong == 'subTable',
      }"
    >
      <el-tag
        v-for="(item, index) in signatureList"
        :key="item.userId"
        :index="index"
        @close="handleRemove(item)"
      >
        <div
          v-if="
            inputWriteable &&
            showQz &&
            item.userId == userId &&
            belong !== 'main'
          "
          ref="imgDelete"
          class="delete-img"
        >
          <i class="el-icon-close" @click="handleReset(item)"></i>
        </div>
        <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>
      <el-button
        v-if="inputWriteable && showQz && belong === 'subDiv'"
        :disabled="DisabledButton"
        size="small"
        type="text"
        icon="icon-shenpiyijian"
        style="padding: 7px"
        @click="startButton"
      >
        签章
      </el-button>
      <!-- :disabled="isDisabledSignature(row, '${field.fieldPath}')"
      @click="" -->
    </div>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="25%"
      append-to-body
      :before-close="handleClose"
      :close-on-click-modal="false"
      custom-class="ht-signature-dialog"
    >
      <div>
        <div class="ht-signature-dialog-lable">请输入签章密码:</div>
        <ht-input
          v-model="signaturePassword"
          width="100%"
          validate="required"
          show-password
        ></ht-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import inputName from '@/mixins/inputName.js'
  import form from '@/mixins/form.js'
  import _ from 'lodash'
  // import { getCurrentSeal } from '@/api/uc.js'
  // import { fileUrl } from '@/api/portal'
  // import { mapMutations, mapState } from 'vuex'
  import moment from 'moment'
  import methods from './methods.js'
  export default {
    name: 'HtSignature',
    components: {},
    mixins: [inputName, form, methods],

    props: {
      value: {
        type: String,
        default: '',
      },
      fieldPath: {
        //配置的签章字段
        type: String,
        default: '',
      },
      belong: {
        //所属位置 main subDiv subTable
        type: String,
        default: 'main',
      },
      boSubEntity: {
        //所属表格名称
        type: String,
        default: '',
      },
      isValidate: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        signatureList: [],
        showSignatureMap: {},
        dialogVisible: false,
        signaturePassword: '', //签章密码
      }
    },
    computed: {
      // ...mapState('user', ['userInfo', 'username']),
      // ...mapState('signature', [
      //   'signatureConfig',
      //   'signatureStatus',
      //   'signatureType',
      // ]),

      userId() {
        let userInfo = ''
        if (this.hasFieldPath('user', 'userInfo')) {
          userInfo = this.$store.state.user.userInfo
        }

        if (userInfo && userInfo.user && userInfo.user.userId) {
          return userInfo.user.userId
        } else {
          return ''
        }
      },
      getImgMsg() {
        return (item) => {
          return `${item.name}于${item.createTime}进行了签章`
        }
      },
    },
    watch: {
      signatureConfig: {
        handler(val) {
          if (val.field === this.fieldPath) {
            if (this.signatureStatus === 'start') {
              this.$store.commit('signature/setSignatureStatus', 'ing')
              // 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,
      },

      value: {
        handler(val) {
          // if (this.signatureType === 'sub' && this.belong == 'subTable') {
          if (val) {
            if (typeof val === 'string') {
              this.signatureList = JSON.parse(this.value)
            } else this.signatureList = this.value
          } else {
            this.signatureList = []
          }
          // }
        },
        deep: true,
        immediate: true,
      },
      signatureList: {
        handler(val) {
          // console.log(this.fieldPath)
          // console.trace(val)
        },
        deep: true,
        immediate: true,
      },
    },
    mounted() {
      // if (this.value) {
      //   this.signatureList = JSON.parse(this.value)
      // }
    },
    methods: {
      // ...mapMutations('signature', [
      //   'setSignatureConfig',
      //   'setSignatureStatus',
      // ]),
      handleSure() {
        const { secretFree } = this.getNodeProperties()
        if (!this.signaturePassword) {
          this.$message.error('请输入签章使用密码')
          return
        }

        this.reqFunc(this.signaturePassword, secretFree)
      },
      handleClose() {
        this.dialogVisible = false
        this.signaturePassword = ''
      },

      getSignature(password, secretFree) {
        this.$requestConfig.getCurrentSeal(password, secretFree).then((res) => {
          if (res.state) {
            this.reloadSignatures(res.value)
            setTimeout(() => {
              // this.setSignatureStatus('success')
              this.$store.commit('signature/setSignatureStatus', 'success')
            }, 300)
          } else {
            this.$message.error(res.message)
            this.$store.commit('signature/setSignatureStatus', 'fail')
          }
        })
      },
      getShowSignature(item) {
        if (!item.signature)
          return this.$message.warning('未获取到签章，请检查签章配置！')
        if (!this.showSignatureMap[item.signature]) {
          this.$set(item, 'imgSrc', this.$requestConfig.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) {
        let username = this.$store.state.user.username
        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: 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>
  .el-icon-close::before {
    content: none;
  }
  .vbl-height {
    line-height: 32px;
    height: 32px;
  }
  .delete-img {
    position: absolute;
  }
  .signature {
    display: flex;
    align-items: center;
    &:hover {
      .delete-img {
        width: 14px;
        height: 14px;
        right: 0;
        top: 0;
        background: #000;
        border-radius: 0 0 0 14px;

        .el-icon-close {
          &::before {
            content: '\e6db';
          }
          display: block;
          font-size: 12px;
          position: absolute;
          right: -1px;
          color: #fff;
        }
      }
    }
    ::v-deep {
      div[aria-invalid='true'] .el-input__inner,
      div[aria-invalid='true'] .el-input__inner:focus {
        border-color: #f56c6c;
      }
      .el-tag {
        position: relative;
        min-width: 120px;
        // width: 100%;
        margin-right: 7px;
        height: 32px;
        line-height: 30px;
        color: #666;
        background-color: transparent;
        border-color: #ebeef5;
        cursor: pointer;
        .signature-image {
          // width: 80px;
          // height: 28px;
          height: 100%;
        }
      }
    }
  }
  .icon-shenpiyijian {
    border: none !important;
  }

  .ht-subTable {
    justify-content: center;
    flex-direction: column;
    ::v-deep {
      .el-tag {
        margin: 0 !important;
      }
      .el-tag + .el-tag {
        margin-top: 10px !important;
      }
    }
  }
</style>
<style lang="scss">
  .ht-signature-dialog {
    .inputs {
      width: 100% !important;
    }
    .ht-signature-dialog-lable {
      margin-bottom: 25px;
    }

    .el-dialog__body {
      padding: 20px;
      border-top: 0;
    }
    .el-dialog__footer {
      padding: 0 20px 20px;
      border-top: 0;
    }
  }
</style>
