<template>
  <div style="position: relative; width: 100%; height: 100%">
    <NavBar>
      <template slot="title">签章管理</template>
    </NavBar>
    <div class="esign-div">
      <van-tabs
        v-model="active"
        color="#409EFF"
        title-active-color="#409EFF"
        title-inactive-color="#262626"
      >
        <van-tab title="手写签名">
          <div class="esign-div_content" @click="showPop = true">
            <van-image
              v-if="electronicSealFileUrl"
              :src="electronicSealFileUrl"
            />
            <van-empty v-else :image="noImg" description="暂无签名" />
          </div>
        </van-tab>
        <van-tab title="上传签名">
          <ht-viewer v-model="electronicSeal.fileId" ref="htViewer" />
        </van-tab>
      </van-tabs>
    </div>
    <div class="password_all">
      <div>
        <van-form ref="Form">
          <van-field
            v-model="electronicSeal.oldPassWord"
            :type="electronicSealOldPassWord ? 'text' : 'password'"
            autocomplete="off"
            label="登录密码"
            placeholder="请输入登录密码"
            input-align="right"
            @click-right-icon="clickPassword('electronicSealOldPassWord')"
          >
            <template #right-icon>
              <i
                :class="
                  !electronicSealOldPassWord ? 'icon-yincang' : 'icon-xianshi'
                "
              ></i>
            </template>
          </van-field>
          <van-field
            v-model="electronicSeal.password"
            :type="electronicSealPassword ? 'text' : 'password'"
            autocomplete="off"
            label="签章密码"
            :error="false"
            placeholder="请输入签章密码"
            input-align="right"
            :rules="[
              {
                validator,
                message: '只能输入字母、数字、下划线，且以字母开头',
              },
            ]"
            @click-right-icon="clickPassword('electronicSealPassword')"
          >
            <template #right-icon>
              <i
                :class="
                  !electronicSealPassword ? 'icon-yincang' : 'icon-xianshi'
                "
              ></i>
            </template>
          </van-field>

          <van-field
            v-model="electronicSeal.confirmPwd"
            :type="electronicSealConfirmPwd ? 'text' : 'password'"
            autocomplete="off"
            label="确认密码"
            placeholder="请输入确认密码"
            input-align="right"
            :error="false"
            :rules="[
              {
                validator: validators,
                message: '两次输入的值必须相同',
              },
            ]"
            @click-right-icon="clickPassword('electronicSealConfirmPwd')"
          >
            <template #right-icon>
              <i
                :class="
                  !electronicSealConfirmPwd ? 'icon-yincang' : 'icon-xianshi'
                "
              ></i>
            </template>
          </van-field>
        </van-form>
      </div>
    </div>
    <div class="button_group">
      <van-button type="default" @click="handleReset">清空</van-button>

      <van-button
        type="info"
        :loading="loading"
        loading-text="保存中..."
        @click="handleGenerate"
      >
        保存
      </van-button>
    </div>
    <van-popup
      v-model="showPop"
      :close-on-click-overlay="false"
      round
      position="bottom"
      style="min-height: 40%"
    >
      <van-nav-bar
        title="手写签章"
        left-text="取消"
        right-text="确定"
        class="popup_header_fixed"
        @click-left="clickLeft"
        @click-right="onSave()"
      />

      <div class="content popup_header_margin">
        <vue-esign
          ref="esign"
          :is-crop="isCrop"
          :line-width="lineWidth"
          :line-color="lineColor"
          :width="800"
          :height="600"
        />
      </div>
    </van-popup>
  </div>
</template>

<script>
  import vueEsign from 'vue-esign'
  import NavBar from '@/components/NavBar.vue'
  import req from '@/utils/request'
  import { Notify } from 'vant'
  import HtViewer from './HtViewer.vue'
  export default {
    components: {
      NavBar,
      vueEsign,
      HtViewer,
    },

    data() {
      return {
        noImg: require('../assets/images/noImage.png'),
        showPop: false,
        lineWidth: 4,
        lineColor: '#000000',
        bgColor: '#ffffff',
        resultImg: '',
        isCrop: true,
        electronicSealFileUrl: '',
        electronicSeal: {
          fileId: '',
          password: '',
        },
        active: 0,
        loading: false,
        electronicSealConfirmPwd: false,
        electronicSealPassword: false,
        electronicSealOldPassWord: false,
      }
    },
    mounted() {
      this.getElectronicSeal()
    },
    methods: {
      validators(val) {
        if (val === this.electronicSeal.password) {
          return true
        }
        return false
      },
      validator(val) {
        return /^[a-zA-Z][a-zA-Z0-9_]*$/.test(val)
      },
      clickPassword(da) {
        this[da] = !this[da]
      },
      clickLeft() {
        this.$refs.esign.reset()
        this.showPop = false
      },
      onSave() {
        this.$refs.esign.generate().then((res) => {
          this.electronicSealFileUrl = res
          this.clickLeft()
        })
      },
      handleReset() {
        this.electronicSeal.oldPassWord = ''
        this.electronicSeal.confirmPwd = ''
        this.electronicSeal.password = ''

        this.electronicSealFileUrl = ''

        this.electronicSeal.fileId = ''
        // this.$refs.htViewer.remove()
      },
      getElectronicSeal() {
        // 获取当前登录用户的签章图片
        req
          .get(
            window.context.uc + '/uc/electronicSeal/v1/getSealByCurrentUserId'
          )
          .then((response) => {
            if (response) {
              this.electronicSeal = response
              this.$store
                .dispatch('menu/downloadImg', response.fileId)
                .then((res) => {
                  if (res != '') {
                    this.electronicSealFileUrl = res
                  }
                })
            }
          })
          .then(() => {})
      },
      handleGenerate() {
        // if (this.active == 0 && !this.electronicSealFileUrl) {
        //   Notify({ type: 'warning', message: '请先手写签名！' })
        //   return
        // } else if (this.active == 1 && !this.electronicSeal.fileId) {
        //   Notify({ type: 'warning', message: '请先上传签名图片！' })
        //   return
        // }
        if (!this.electronicSeal.oldPassWord) {
          Notify({ type: 'warning', message: '请输入登录密码！' })
          return
        }
        if (!this.electronicSeal.password) {
          Notify({ type: 'warning', message: '请输入签章密码！' })
          return
        }
        if (!this.electronicSeal.confirmPwd) {
          Notify({ type: 'warning', message: '请输入确认密码！' })
          return
        }
        if (this.electronicSeal.password != this.electronicSeal.confirmPwd) {
          Notify({ type: 'warning', message: '签章密码与确认密码不一致！' })
          return
        }
        this.$refs.Form.validate()
          .then(() => {
            let electronicSealClone = _.cloneDeep(this.electronicSeal)
            delete electronicSealClone.confirmPwd
            // 验证通过
            if (this.active == 0) {
              this.loading = true
              let formData = new FormData()

              if (this.electronicSealFileUrl) {
                let file = this.base64ToFile(
                  this.electronicSealFileUrl,
                  this.getuuid()
                )

                formData.append('files', file)
                req
                  .post(
                    window.context.portal + '/system/file/v1/fileUpload',
                    formData
                  )

                  .then((resp) => {
                    const { fileId } = resp
                    electronicSealClone.fileId = fileId
                    return fileId
                  })
                  .then(() => {
                    return req.post(
                      window.context.uc + '/uc/electronicSeal/v1/userSave',
                      electronicSealClone
                    )
                  })
                  .then((resp) => {
                    if (resp.state) {
                      Notify({ type: 'success', message: resp.message })
                      this.getElectronicSeal()
                      this.$router.push('personal')
                    } else {
                      Notify({ type: 'warning', message: resp.message })
                    }
                  })
                  .catch((message) => {
                    Notify({ type: 'warning', message })
                  })
                  .finally(() => (this.loading = false))
              } else {
                electronicSealClone.fileId = ''
                req
                  .post(
                    window.context.uc + '/uc/electronicSeal/v1/userSave',
                    electronicSealClone
                  )
                  .then((resp) => {
                    if (resp.state) {
                      Notify({ type: 'success', message: resp.message })
                      this.getElectronicSeal()
                      this.$router.push('personal')
                    } else {
                      Notify({ type: 'warning', message: resp.message })
                    }
                  })
                  .catch((message) => {
                    Notify({ type: 'warning', message })
                  })
                  .finally(() => (this.loading = false))
              }
            } else {
              this.loading = true
              req
                .post(
                  window.context.uc + '/uc/electronicSeal/v1/userSave',
                  electronicSealClone
                )
                .then((resp) => {
                  if (resp.state) {
                    Notify({ type: 'success', message: resp.message })
                    this.getElectronicSeal()
                    this.$router.push('personal')
                  } else {
                    Notify({ type: 'warning', message: resp.message })
                  }
                })
                .finally(() => (this.loading = false))
            }
          })
          .catch(() => {
            //验证失败
          })
      },
      base64ToFile(urlData, fileName) {
        let arr = urlData.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let bytes = atob(arr[1]) // 解码base64
        let n = bytes.length
        let ia = new Uint8Array(n)
        while (n--) {
          ia[n] = bytes.charCodeAt(n)
        }
        return new File([ia], fileName, { type: mime })
      },
      getuuid() {
        // 随机获取值 当作文件名称
        var s = []
        var hexDigits = '0123456789abcdef'
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
        }
        s[14] = '4'
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
        s[8] = s[13] = s[18] = s[23] = '-'

        this.uuidA = s.join('')
        return this.uuidA
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/styles/matterButton.scss';
  .esign-div {
    background-color: #ffffff;
    height: 246px;
    &_content {
      margin: 16px 16px 50px;
      border: 1px solid #e6e6e6;
      border-radius: 8px 8px 8px 8px;
      height: 140px;
      overflow: hidden;
      .van-image,
      .van-empty {
        width: 100%;
        height: 100%;
      }
      ::v-deep {
        .van-empty__image {
          width: 72px;
          height: 52px;
        }
        .van-empty__description {
          padding: 0;
          margin: 0;
        }
      }
    }
  }

  .button_group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: absolute;
    margin: 0 16px;
    bottom: 10px;
    width: calc(100% - 32px);
    .van-button {
      width: 163px;
      height: 42px;
      border: 1px solid #e6e6e6;
      border-radius: 8px 8px 8px 8px;
    }
  }
  ::v-deep {
    .van-field__label {
      font-size: 14px;
      width: 70px;
    }
    .van-tab--active {
      .van-tab__text {
        color: #409eff;
      }
    }
    .popup_header_fixed {
      border-bottom: 0.02667rem solid #e6e6e6;
    }
    .van-field__right-icon {
      font-size: 16px;
    }
  }
  .password_all {
    margin: 12px 0px;
    background: #ffffff;
    & > div {
      padding: 12px 0px;
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 44px);
  }
</style>
