<script>
import bridge, { isInApp } from '@/utils/bridge'
import CompSign from '@/components/CompSign'
import { queryPotocolManage } from '@/api/management'

const UPLOAD_TYPE = {
  CAMERA: 'camera',
  NATIVE: 'native',
  SIGN: 'sign'
}

const UPLOAD_ICON = {
  camera: 'camera',
  native: 'document',
  sign: 'edit'
}

export default {
  name: 'PadBridge',
  props: {
    // 是否需要加密
    security: {
      type: Boolean,
      default: false
    },
    // 上传类型,[camera, native, sign]
    uploadType: {
      type: Array,
      default: () => ([UPLOAD_TYPE.CAMERA, UPLOAD_TYPE.NATIVE])
    },
    // 当上传类型有sign的时候，需要传入此字段标识当前需要取哪个文件来签名
    signKey: {
      type: String,
      default: ''
    },
    // 附件url
    attachmentUrl: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      showPopOver: false,
      isInApp,
      showSign: false,
      showSignLoading: false,
      originUrl: '',
      fileList: []
    }
  },

  mounted() {
    // 记录当前文件上传组件
    this.elUpload = this.$slots.default[0].componentInstance
    // 如果在app中，则禁用文件选择器，使用本地的拍照上传和文件选择
    if (this.isInApp && this.elUpload.$el.querySelector('input[type=file]')) {
      this.elUpload.$el.querySelector('input[type=file]').disabled = 'disabled'
    }
  },

  methods: {
    /**
     * 拍照上传
     */
    handleTakePhoto() {
      // 如果当前是一体机
      if (this.$store.getters.deviceType === 'aio') {
        // 回调方法
        const callback = (video, type) => {
          // 如果当前拍摄的是视频
          if (type === 'video') {
            this.$message.error('请上传图片')
            return
          }
          this.uploadFile(video)
        }
        // 获取一体机
        bridge.getUvcCameraList((deviceList = []) => {
          console.log('当前读取的设备列表：', deviceList)
          // 是否有master相机
          const masterCamera = deviceList.find(device => device.productName.toLowerCase().indexOf('master') >= 0)
          // 如果当前有高拍仪的拍文件相机
          if (masterCamera) {
            bridge.openTargetUvcCamera(masterCamera, callback)
          } else {
            bridge.getUvcCamera(callback)
          }
        })
      } else {
        bridge.getCamera(this.uploadFile.bind(this))
      }
      // 关闭弹框
      this.showPopOver = false
    },

    /**
     * 选择文件上传
     */
    handleSelectFile() {
      bridge.getPhoto(this.uploadFile.bind(this))
    },

    /**
     * 触发按钮的点击事件
     * @param type 当前按钮的点击类型
     */
    async handleClick(type) {
      switch (type) {
        case UPLOAD_TYPE.CAMERA:
          this.handleTakePhoto()
          break
        case UPLOAD_TYPE.NATIVE:
          this.handleSelectFile()
          break
        case UPLOAD_TYPE.SIGN:
          // 签名的loading
          this.showSignLoading = true
          try {
            // 请求接口
            const agreements = await queryPotocolManage({ orgId: this.$store.getters.organId })
            // 源url
            const originUrlLink = agreements[this.signKey + 'Vertical']
            // 源文件路径
            this.originUrl = originUrlLink ? originUrlLink.fileUrl : ''
            // 展示签名
            this.showSign = true
          } catch (error) {
            console.error(error)
          }
          this.showSignLoading = false
          break
      }
    },

    /**
     * 上传文件
     */
    async uploadFile(file) {
      // 关闭签名按钮
      this.showSign = false
      try {
        this.elUpload.$children[0].uploadFiles([file])
      } catch (error) {
        console.error(error)
      }
    },

    /**
     * 上传文案的方式
     * @param type 当前类型
     */
    uploadText(type) {
      return {
        camera: '拍照上传',
        native: '选择文件',
        sign: '签字上传'
      }[type]
    }
  },

  render() {
    // 如果当前是app内部
    if (this.isInApp) {
      const defaultSlot = this.$scopedSlots.default()
      return (
        <div>
          <el-popover
            value={this.showPopOver}
            class='component-pad-bridge'
            placement='bottom'
            width='260'
            trigger='click'
            scopedSlots={{
              reference() {
                return defaultSlot
              }
            }}
            onInput={state => {
              this.showPopOver = state
            }}
          >
            <div class='component-pad-bridge-operation-wrapper'>
              {
                this.uploadType.map(t => {
                  return <el-button loading={t === UPLOAD_TYPE.SIGN && this.showSignLoading} icon={`el-icon-${UPLOAD_ICON[t]}`} onClick={() => this.handleClick(t)}>{this.uploadText(t)}</el-button>
                })
              }
            </div>
          </el-popover>
          <CompSign
            title={this.title}
            show={this.showSign}
            originUrl={this.originUrl}
            attachmentUrl={this.attachmentUrl}
            onClose={() => {
              this.showSign = false
            }}
            onChange={this.uploadFile}
          />
        </div>
      )
    }
    return this.$scopedSlots.default()
  }
}
</script>

<style lang="scss">
.component-pad-bridge-operation-wrapper {
  position: relative;
  overflow: hidden;
}
.component-pad-bridge-vin-image {
  background-color: #ffffff;
  width: 750px;
  height: 500px;
  padding: 20px 40px;
  position: fixed;
  top: 0px;
  left: 100vw;
  h1 {
    text-align: center;
  }
  .vin-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 16px;
  }
  .vin-content {
    font-size: 14px;
  }
}
</style>
