<template>
  <div class="two-code">
    <main-page
      left-arrow
      :loading="loading"
      @click-left="handleClickLeft"
    >  
    <div class="mx-4 pt-14 pb-4">
      <div class="shadow-md rounded overflow-hidden" id="qrcode">
        <div class="bg-color-primary text-center h-24 pt-6">
          <div class="text-white flex-initial">{{entName}}</div>
        </div>
        <div class="bg-white">
          <div class="flex flex-row justify-around">
            <div class="pt-7 w-1/2 px-5">
              <!-- <van-image class="w-32 h-32"        
                :src="require('@/assets/icons/y-code.png')"
              /> -->
              <div class="w-32 h-32">
                <vue-qr
                  :logoSrc="require('@/assets/icons/js.png')"
                  :text="qrCodeText"
                  :margin="2"
                  :size="400"
                />
              </div>
            </div>
            <div class="w-1/2 space-y-2 flex-col text-base text-left pt-7 px-4">
              <div class="text-lg font-bold pb-1">{{ joinInfo.name || '张三' }}</div>
              <div class="flex items-start">
                <div class="flex-shrink-0 w-12">职位：</div>
                <div class="flex-1">{{ joinInfo.position }}</div>
              </div>
              <div class="flex items-start">
                <div class="flex-shrink-0 w-12">部门：</div>
                <div class="flex-1"> {{depInfo.name}}</div>
              </div>              
              <div>{{ formatDate(Number(joinInfo.joinTime)*1000, 'YYYY-MM-DD') || '2021-09-05' }}</div>
            </div>
          </div>
          <div class=" text-center text-gray-400 pb-8 pt-4">扫描二维码加入{{entName}}</div>
        </div>
      </div>
      <div class="w-24 mt-4 ml-auto">
        <c-button @click="saveQrcode">保存</c-button>
      </div>
      <div class="mt-4 border text-sm text-text-secondary border border-border rounded break-all p-2">
        {{copyText}}
      </div>
      <div class="flex mt-4 items-center justify-between">
        <div class="text-sm text-color-primary bg-color-primary-light px-6 py-2.5 rounded flex-shrink-0">仅适用于网页版打开</div>
        <div class="w-24">
          <c-button
            id="copyBtn"
            :data-clipboard-text="copyText"
            data-clipboard-action="copy"
            @click="copy">复制</c-button>
        </div>
      </div>
      <c-button type="secondary" class="mt-4" @click="handleClickLeft">进入组织架构</c-button>
    </div>  
    </main-page>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Image } from 'vant'
import { formatDate } from '@/util/FormatDate'
import VueQr from 'vue-qr'
import html2canvas from 'html2canvas'
import { Department } from '@/Interface'
import { transferFile } from '@/util/TransferFile'
interface JoinInfoType{
  depId: string
  entId:string
  expiration:number
  hash:string
  inviterId:string
  joinTime:number
  name:string
  oaServer:string
  phone:string
  position:string
}
Vue.use(Image)
export default Vue.extend({  
  name: 'Two-code',
    data() {
    return {
      formatDate,
      entName:'',
      joinInfo: {} as JoinInfoType,
      qrCodeText:'',
      loading: false,
      depInfo: {} as Department,
      imgUrl: ''
    }
  },
  components: {
    'main-page': () => import('@/layout/main-page.vue'),
    'code-icon':()=>import('@/components/common/Icon.vue'),
    'c-button': () => import('@/components/common/c-button.vue'),
    VueQr,
  },
  async created() {
    // console.log(Mock, 'mock')
    this.joinInfo = this.$store.state.acceptJoin 
    console.log(this.joinInfo);
    
    const urloutput = await this.outputUrl(this.joinInfo)
    this.qrCodeText = JSON.stringify(this.joinInfo) 
    let url = window.location.origin + '/team/confirm-join'
    this.qrCodeText = `${url}?${urloutput}`
    
    this.dpr()
    // this.drawCanvas()
    this.entName = JSON.parse(localStorage.getItem('ENT_INFO') as string).name
    console.log(this.joinInfo, 'joinInfo')
    this.getDepInfo(this.joinInfo.entId, this.joinInfo.depId)
  },
  computed: {
    copyText(): string {
      return `我和${this.entName}的小伙伴都在警书等你，用这个专属链接加入我们吧！ ${this.qrCodeText}`
    }
  },
  methods: {
    outputUrl(item:Object){
      let res =''
      const arr =  Object.entries(item)
      arr.map((i,index)=>{
        let string 
        if(index+1<arr.length){
            string = `${i[0]}=${encodeURIComponent(i[1])}&`
        }else{
          string = `${i[0]}=${encodeURIComponent(i[1])}`
        }
         res += string
      })
      return res
    },
    handleClickLeft() {
      this.$router.push('/team/team-frame')
    },
    dpr() {
      if (window.devicePixelRatio && window.devicePixelRatio > 1) {
        return window.devicePixelRatio
      }
      return 1
    },
    async drawCanvas(selector: string) {
      this.imgUrl = ''
      // 获取节点
      const dom = document.getElementById(selector) as HTMLDivElement
      // 获取节点高度
      const {width, height} = dom?.getBoundingClientRect()
      // 获取像素比
      const scaleBy = this.dpr()
      // 创建canvas
      const canvas = document.createElement('canvas')
      canvas.width = width * scaleBy
      canvas.height = height * scaleBy
      // canvas.style.width = `${width}px`
      // canvas.style.height = `${height}px`
      // const context = canvas.getContext('2d')
      // context?.scale(1, 1)
      return await html2canvas(dom, {canvas}).then(() => {
        const url = canvas.toDataURL('image/png')
        // const file = transferFile(url, 'file')
        // const imgUrl = URL.createObjectURL(file)
        this.imgUrl = url
        const a =document.createElement('a')
        const event = new MouseEvent('click')
        a.download = '邀请码'
        a.href = url
        a.dispatchEvent(event)
      })
    },
    async saveQrcode() {
      await this.drawCanvas('qrcode')
    },
    copy() {
      const clipboard = new this.$util.clipboard('#copyBtn')
      clipboard.on('success', () => {
        this.$toast('已经复制到剪切板')
      })
      clipboard.on('error', () => {
        this.$toast('复制失败')
      })
    },
    getDepInfo(entId: string, depId: string) {
      this.loading=true
      this.$service.department.getDep({
        entId,
        id: depId
      }).then((res: any) => {
        this.loading=false
        const {data} = res
        if(data.code === this.$global.success) {
          this.depInfo = data.data
        }else {
          this.$toast(data.msg)
        }
      })
    }
  }
})
</script>

<style lang="less">
  
</style>
