<template>
  <div
    v-if="permission !== 'n'"
    class="ht-handle-signature"
    :class="{ 'ht-mobile-signature-wrap': isMobile }"
  >
    <div v-if="!isMobile" class="esign">
      <div v-if="inputWriteable">
        <el-button @click="showSignature">编辑签名</el-button>
        <input
          v-model="currentUrl"
          v-validate="inputValidate"
          type="hidden"
          :name="inputName"
          :data-vv-as="name"
        />
      </div>
      <div v-if="imgList && imgList.length > 0">
        <div class="upload-photo">
          <li
            v-for="(item, $index) in imgList"
            :key="$index"
            @mouseover="mouseoverImg()"
            @mouseout="mouseoutImg()"
          >
            <img
              ref="img"
              :src="item.url"
              class="hover-follow-theme-border-color"
              style="object-fit: contain; width: 100%; height: 100%"
            />
            <div v-if="inputWriteable" ref="imgDelete" class="delete-img">
              <i class="el-icon-close" @click="handleReset()"></i>
            </div>
          </li>
        </div>
      </div>
    </div>
    <template v-else>
      <div v-if="inputWriteable" class="btn_wrap">
        <input
          v-model="currentUrl"
          v-validate="inputValidate"
          type="hidden"
          :name="inputName"
          :data-vv-as="name"
        />
        <div class="edit-btn btn-item" @click="showSignature">
          <ht-icon name="mobileEdit"></ht-icon>
          <span class="btn-text">编辑签章</span>
        </div>
        <div class="del-btn btn-item" @click="handleReset">
          <ht-icon name="mobileDel"></ht-icon>
          <span class="btn-text">清空</span>
        </div>
      </div>
      <ul class="signature-content">
        <li
          v-for="(item, $index) in imgList"
          :key="$index"
          class="signature-item"
        >
          <img :src="item.url" class="signature-img" />
        </li>
      </ul>
    </template>

    <el-dialog
      v-if="!isMobile"
      width="700px"
      height="400px"
      title="编辑签名"
      :visible.sync="dialogVisible"
      :before-close="beforeCloseDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div>
        <vue-esign
          ref="esign"
          class="esignature"
          style="border: 1px dashed #c2c1c1; width: 100%"
          :height="300"
          :is-crop="isCrop"
          :line-width="lineWidth"
          :line-color="lineColor"
          :bg-color.sync="bgColor"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="beforeCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleGenerate">确 定</el-button>
      </div>
    </el-dialog>
    <van-action-sheet
      v-if="isMobile"
      v-model="dialogVisible"
      class="user-mobile__selector"
      title="编辑签名"
      @close="beforeCloseDialog"
    >
      <vue-esign
        ref="esign"
        class="esignature"
        style="border: 1px dashed #c2c1c1; margin: auto"
        :width="370"
        :height="300"
        :is-crop="isCrop"
        :line-width="lineWidth"
        :line-color="lineColor"
        :bg-color.sync="bgColor"
      />
      <div class="footer">
        <div class="btn" @click="handleGenerate">确认</div>
      </div>
    </van-action-sheet>
  </div>
</template>
<script>
  import permission from '@/mixins/permission.js'
  import inputName from '@/mixins/inputName.js'
  import form from '@/mixins/form.js'
  import script from '@/mixins/script.js'
  import vueEsign from './Esign.vue'
  import mobileMode from '@/mixins/mobileMode.js'

  export default {
    name: 'HtHandSignature',
    components: { vueEsign },
    mixins: [permission, inputName, form, script, mobileMode],
    props: {
      value: String,
      name: String,
      penColor: String,
      backgroundColor: String,
    },
    data() {
      return {
        lineWidth: 5,
        lineColor: '#000000',
        bgColor: '',
        isCrop: false,
        dialogVisible: false,
        currentUser: {},
        imgList: [],
        currentUrl: '',
      }
    },
    watch: {
      imgList: {
        handler: function (newVal) {
          this.$emit('input', JSON.stringify(newVal))
        },
        deep: true,
      },
    },
    created() {
      if (this.penColor) {
        this.lineColor = this.penColor
      }
      if (this.backgroundColor) {
        this.bgColor = this.backgroundColor
      }
      if (this.value) {
        this.imgList = JSON.parse(this.value)
      }
      this.$requestConfig.getCurrentUser().then((currentUserDetail) => {
        this.currentUser = currentUserDetail
        if (this.imgList && this.imgList.length > 0) {
          this.imgList.forEach((item) => {
            if (item.owner == currentUserDetail.account) {
              this.currentUrl = item.url
            }
          })
        }
      })
    },
    mounted() {
      if (this.isMobile) {
        this.addMobileTopLabelClass()
      }
    },

    methods: {
      handleReset() {
        this.imgList = this.imgList.filter(
          (item) => item.owner !== this.currentUser.account
        )
        this.currentUrl = ''
        this.$refs.esign.reset()
      },
      //生成签名
      handleGenerate() {
        let _this = this
        _this.$refs.esign
          .generate()
          .then((res) => {
            _this.dialogVisible = false
            let blob = _this.dataURLtoBlob(res)
            let formdata = new FormData()
            formdata.append('image', blob, '签名.jpg')
            this.$requestConfig
              .request({
                url: '${portal}/system/file/v1/upload',
                method: 'post',
                data: formdata,
              })
              .then((resp) => {
                if (resp.success) {
                  let url =
                    `${window.context.portal}/system/file/v1/downloadFile?fileId=` +
                    resp.fileId
                  _this.imgList = _this.imgList.filter(
                    (item) => item.owner !== _this.currentUser.account
                  )
                  _this.currentUrl = url
                  let imgItem = {
                    url: url,
                    owner: _this.currentUser.account,
                  }
                  _this.imgList.push(imgItem)
                  _this.$refs.esign.reset()
                  return
                }
              })
          })
          .catch((err) => {
            _this.$message.error('签名不能为空')
            return
          })
      },
      beforeCloseDialog() {
        this.dialogVisible = false
        this.$refs.esign.reset()
      },
      showSignature() {
        this.dialogVisible = true
      },
      // 将base64转换为blob
      dataURLtoBlob(dataurl) {
        var arr = dataurl.split(',')
        var mime = arr[0].match(/:(.*?);/)[1]
        var bstr = atob(arr[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type: mime })
      },
      // 鼠标移入图片
      mouseoverImg() {
        this.imgList.forEach((item, index) => {
          if (item.owner == this.currentUser.account) {
            this.$refs.imgDelete[index].style.display = 'block'
          } else {
            this.$refs.imgDelete[index].style.display = 'none'
          }
        })
      },
      // 鼠标移出图片
      mouseoutImg() {
        this.imgList.forEach((item, index) => {
          this.$refs.imgDelete[index].style.display = 'none'
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .ht-mobile-signature-wrap {
    .btn_wrap {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      position: absolute;
      top: -36px;
      right: 0;
      ::v-deep {
        svg {
          width: 22px;
          height: 22px;
        }
      }
      .btn-item {
        display: flex;
        align-items: center;

        .btn-text {
          font-size: 14px;
          color: #409eff;
          margin-left: 4px;
        }
      }
      .edit-btn {
        margin-right: 12px;
      }
    }
    .signature-content {
      // margin-left: -120px;
      .signature-item {
        width: 100%;
        border: 1px solid #e6e6e6;
        border-radius: 4px;
        height: 64px;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        .signature-img {
          width: 106px;
          height: 48px;
        }
      }
    }
  }
  .esign {
    max-width: 310px;
    //overflow: auto;
    padding: 0px 4px 0px 4px;
  }
  .user-mobile__selector {
    .footer {
      width: 100%;
      padding: 10px 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      .btn {
        width: 100%;
        height: 44px;
        background: #409eff;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        font-size: 14px;
        border-radius: 8px;
      }
    }
    ::v-deep {
      .van-tab--active {
        font-weight: bold;
        color: $base-color-blue;
      }
    }
    .user-mobile__title {
      font-size: 18px;
      color: #1a1a1a;
    }
    .user-mobile__close {
      float: right;
    }
    .contact-group__container {
      padding: 0 12px;
    }
    .user-contact__group {
      margin-right: 6px;
      color: #999999;
      max-width: 72px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      &::before {
        border-width: 0;
      }

      &.current {
        color: $base-color-blue;
      }

      &.current::before {
        border-width: 1px;
      }
    }
    .user-list__container {
      display: flex;
      align-items: center;

      .vue-avatar--wrapper {
        margin-left: 10px;
      }

      .selector-item__detail {
        display: flex;
        flex-direction: column;
        margin-left: 10px;

        .selector-detail__name {
          max-width: 220px;

          label {
            color: #111;
            font-size: 14px;
          }
          span {
            margin-left: 10px;
            color: #777;
          }
        }

        .selector-detail__desc {
          margin-top: 5px;

          span {
            display: inline-block;
            font-size: 12px;
            color: #777;
            max-width: 94px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          span + span {
            margin-left: 10px;
          }
        }
      }
    }

    .user-data__list {
      min-height: 400px;
    }
    .van-action-sheet__cancel {
      padding: 5px;
      background: $base-color-blue;
      color: $base-color-white;
    }
  }
  .upload-photo {
    height: 40px;
    margin-top: 8px;
    max-width: 500px;
    box-sizing: border-box;
    border-radius: 5px;
    cursor: pointer;
    margin-top: 0px;
    padding-top: 0px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;

    li {
      width: 100px;
      height: 40px;
      margin-right: 2px;
      position: relative;
      list-style: none;
      .delete-img {
        display: none;
        position: absolute;
        width: 14px;
        height: 14px;
        right: 0;
        top: 0px;
        background: black;
        border-radius: 0 0 0 14px;
        i {
          display: block;
          font-size: 12px;
          color: #fff;
        }
      }

      img {
        border: 1px solid #d9d9d9;
        border-radius: 3px;
        box-sizing: border-box;
        width: 90px;
        height: 40px;
        margin-top: 0px;
        &:hover {
          border: 1px dashed #409eff;
        }
      }
    }
  }
</style>
