<template>
  <div>
    <div class="qr-code-wrap">
      <el-alert
        class="top-tips"
        title="提醒：选择分组后，会自动生成相应的分组二维码，居民扫码后直接进入该分组（若未选择分组，则自动生成未分组二维码，居民扫码后进入默认未分组）"
        type="warning"
        show-icon
      >
      </el-alert>
      <div class="qr-group">
        <p class="label-name">二维码分组：</p>
        <template v-for="(labelItem, index) in labelsInfoList" :key="index">
          <el-tag size="small">{{ labelItem.labelName }}</el-tag>
        </template>
        <el-tag size="small" class="choose-group" @click="handleChooseGroup"
          >+ 选择分组</el-tag
        >
      </div>
      <div class="qr-pic-wrap">
        <div class="qr-box">
          <div class="pic">
            <canvas id="msg"></canvas>
            <el-button
              icon="el-icon-download"
              class="qr-download-btn"
              @click="handleQRDownloadModal"
              >下载二维码</el-button
            >
          </div>
          <p class="time-limit">
            有效期：{{ qrCodeInfo.beginTime }}-{{ qrCodeInfo.endTime }}
          </p>
          <el-button
            icon="el-icon-refresh"
            class="refresh-btn"
            size="small"
            @click="handleRefreshCode"
            >刷新有效期</el-button
          >
        </div>
      </div>
      <div class="border-space"></div>
      <div class="increased-steps-wrap">
        <div class="label-title">居民添加流程</div>
        <img
          src="../../../../assets/image/patient-add-flow-path.png"
          alt=""
          class="flow-path"
        />
      </div>
    </div>
    <!-- 选择分组 弹窗 -->
    <el-dialog
      class="choose-label-wrap"
      :title="showDownloadQRModal == false ? '选择分组' : '下载二维码'"
      v-model:visible="showChooseLabelModal"
      width="680px"
      :close-on-click-modal="false"
      center
    >
      <p class="under-title-tips">
        选择分组后，会自动生成相应的分组二维码，居民扫码后直接进入该分组
      </p>
      <el-row class="row-in-line">
        <el-button
          size="small"
          class="clear-select"
          :disabled="choosedLabelList.length < 1"
          @click="handleClearSelect"
          >清空选择</el-button
        >
        <template v-if="!showDownloadQRModal">
          <el-button
            type="primary"
            class="right"
            size="small"
            @click="handleGoToLabelManage"
            >分组管理</el-button
          >
          <p class="tips">未找到分组可去分组管理新建分组</p>
        </template>
      </el-row>
      <div class="list-wrap">
        <el-checkbox-group v-model:value="choosedLabelList">
          <template v-for="item in labelNameList">
            <el-checkbox v-if="item.labelId != 0" :label="item.labelId" border>
              {{ item.labelName }}
            </el-checkbox>
          </template>
        </el-checkbox-group>
      </div>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseChooseLabelModal" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="handleAfterChooseLabel"
            size="small"
            >{{
              showDownloadQRModal == false ? '确 定' : '确定下载'
            }}</el-button
          >
          <a
            :href="imgHref"
            ref="downLoadBtn"
            id="downLoadBtn"
            download="二维码.png"
          ></a>
        </span>
      </template>
    </el-dialog>
    <!-- 重新加载当前分组列表 -->
    <el-dialog
      class="reload-label-modal"
      v-model:visible="showReloadLabelModal"
      width="320px"
      :show-close="false"
      :close-on-click-modal="false"
      center
    >
      <p class="tips">
        您刚才跳转到分组管理页面进行新建分组，请点击下方按钮刷新数据
      </p>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleReloadLabel"
            >重新加载</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import {
  getQRCode,
  refreshCode,
  getLabelList,
  getLabelsInfo,
  downloadQRCode,
} from '@/utils/patients/patientsapi'

export default {
  name: 'qrCodeImport',
  data() {
    return {
      imgHref: '',
      showChooseLabelModal: false,
      showReloadLabelModal: false,
      showDownloadQRModal: false, //下载二维码弹窗时， 是否隐藏“选择分组”里的分组管理部分
      qrCodeInfo: {
        qrcodeUrl: '',
        beginTime: '',
        endTime: '',
        id: '',
        labelIds: '',
      },
      labelsInfoList: [], // 二维码分组 列表信息
      labelNameList: [], // 分组列表
      currentLabelList: [], // 接口返回的二维码分组id列表
      choosedLabelList: [], //          勾选的分组id列表
      forDownloadInfo: {}, // 下载用的信息
    }
  },
  created() {
    this.goToGetQRCode({
      labelIds: '',
      id: '',
      first: true,
    })
  },
  watch: {
    showChooseLabelModal: function (val) {
      if (val == false) {
        // this.labelNameList = [];
        this.choosedLabelList = []
      }
    },
  },
  methods: {
    handleCloseChooseLabelModal() {
      this.showChooseLabelModal = false
    },
    // 二维码录入
    goToGetQRCode(params, cb) {
      let justDownload = false
      if (params.hasOwnProperty('justDownload')) {
        justDownload = true
        delete params.justDownload
      }
      getQRCode(params).then((res) => {
        if (res.code == '000000') {
          let data = res.data
          if (!justDownload) {
            // 非下载二维码时
            this.qrCodeInfo = data
            if (data.labelIds && data.labelIds != '') {
              // 存在labelIds，则去请求label信息列表
              let temp = data.labelIds.split(',')
              this.currentLabelList = this.formatList(temp)
              this.handleGetLabelsInfo({
                labelIds: data.labelIds,
              })
            } else {
              this.labelsInfoList = []
              this.currentLabelList = []
            }
            this.calculateQRCode(data.qrcodeUrl)
          } else {
            // 下载二维码时，不用更新页面中的二维码信息
            // debugger;
            this.forDownloadInfo = data
            let { id, beginTime, endTime, forever } = this.forDownloadInfo
            let obj = {
              id,
              beginTime,
              endTime,
              forever,
              //                labels: [],  // ["高血压","糖尿病","脑卒中"]
              labelList: [],
            }
            let idArr = params.labelIds.split(',') // [1,3,55]
            let checkArr = this.labelNameList
            for (let i = 0; i < idArr.length; i++) {
              for (let j = 0; j < checkArr.length; j++) {
                if (idArr[i] == checkArr[j].labelId) {
                  //                    obj.labels.push( checkArr[j].labelName );
                  obj.labelList.push({
                    labelId: checkArr[j].labelId,
                    labelName: checkArr[j].labelName,
                  })
                }
              }
            }
            // console.log('obj.labels: ', obj.labels);
            cb && cb(obj)
          }
        } else {
          this.$message({
            message: '获取二维码失败，请重新再试',
            type: 'warning',
          })
        }
      })
    },
    formatList(arr) {
      return arr.map((item, index) => {
        return parseInt(item)
      })
    },
    handleGetLabelsInfo(params) {
      getLabelsInfo(params).then((res) => {
        if (res.code == '000000') {
          this.labelsInfoList = res.data
        } else {
          this.$message({
            message: '获取标签信息失败',
            type: 'warning',
          })
        }
      })
    },
    calculateQRCode(val) {
      // 获取页面的canvas
      var msg = document.getElementById('msg')
      // 将获取到的数据（val）画到msg（canvas）上
      QRCode.toCanvas(msg, val, function (error) {
        // console.log(error)
      })
    },
    handleChooseGroup() {
      // debugger;
      this.showDownloadQRModal = false
      // 回显已经选择的label
      this.choosedLabelList = this.currentLabelList
      this.goToGetGroupList()
    },
    handleRefreshCode() {
      let params = {
        labelIds: this.qrCodeInfo.labelIds,
        id: this.qrCodeInfo.id,
        first: false,
      }
      refreshCode(params).then((res) => {
        if (res.code == '000000') {
          let data = res.data
          this.qrCodeInfo = data
          if (data.labelIds && data.labelIds != '') {
            let temp = data.labelIds.split(',')
            this.currentLabelList = this.formatList(temp)
          }
        } else {
          this.$message({
            message: '获取二维码失败，请重新再试',
            type: 'warning',
          })
        }
      })
    },
    handleQRDownloadModal() {
      this.showDownloadQRModal = true
      // 回显已经选择的label
      this.choosedLabelList = this.currentLabelList
      this.goToGetGroupList()
    },
    handleAfterChooseLabel() {
      //        console.log('this.choosedLabelList ', this.choosedLabelList)
      //        console.log('this.choosedLabelList ', this.choosedLabelList.join(','))
      if (this.showDownloadQRModal == false) {
        // 选择分组时
        this.showChooseLabelModal = false
        this.goToGetQRCode({
          labelIds: this.choosedLabelList.join(','),
          id: '',
          first: false,
        })
      } else {
        // 下载二维码时
        // 获取最新二维码参数，但不影响之前的二维码参数
        this.goToGetQRCode(
          {
            labelIds: this.choosedLabelList.join(','),
            id: '',
            first: false,
            justDownload: true,
            downloadQrcode: true,
          },
          this.goToDownloadQRCode
        )
      }
    },
    goToDownloadQRCode(params) {
      // 下载二维码
      downloadQRCode(params).then((res) => {
        if (res.code == '000000') {
          this.showChooseLabelModal = false
          this.downloadFile(res.data)
        } else {
          this.$message({
            message: '下载二维码失败',
            type: 'warning',
          })
        }
      })
    },
    handleClearSelect() {
      this.choosedLabelList = []
    },
    goToGetGroupList() {
      // 获取分组列表
      let params = {
        type: 1,
      }
      if (this.labelName) {
        params.labelName = this.labelName
      }
      getLabelList(params)
        .then((data) => {
          // console.log('获取分组列表>> ', data)
          if (data.data && data.data.labelNameList) {
            this.labelNameList = data.data.labelNameList
            this.showChooseLabelModal = true
          }
        })
        .catch((err) => {
          console.log('error: ', err)
        })
    },
    handleGoToLabelManage() {
      let routeUrl = this.$router.resolve({
        path: '/patients-manage/labels-manage/labels-list',
      })
      window.open(routeUrl.href, '_blank')
      this.showReloadLabelModal = true
    },
    handleReloadLabel() {
      this.showReloadLabelModal = false
      this.goToGetGroupList()
    },
    downloadFile(src) {
      //        console.log('准备下载',src)
      this.downLoadHandle(src)
    },
    downLoadHandle(src) {
      let blobToDataURI = (blob, callback) => {
        var reader = new FileReader()
        reader.onload = (e) => {
          callback(e.target.result)
        }
        reader.readAsDataURL(blob)
      }
      var xhr = new XMLHttpRequest()
      xhr.open('GET', src, true)
      xhr.responseType = 'blob'
      xhr.onload = () => {
        if (xhr.status == 200) {
          var blob = xhr.response
          var img = document.createElement('img')
          img.onload = (e) => {
            window.URL.revokeObjectURL(img.src)
          }
          img.src = window.URL.createObjectURL(blob)
          blobToDataURI(blob, (data) => {
            //              console.log(img)
            //              console.log(data)
            document.getElementById('downLoadBtn').setAttribute('href', data)
            this.imgHref = data
            if (this.myBrowser() === 'IE' || this.myBrowser() === 'Edge') {
              //          window.event.preventDefault();
              window.event.returnValue = false
              window.download(this.imgHref, '二维码.png', 'image/png')
            }
            this.$refs.downLoadBtn.click()
            // 如果是IE浏览器
          })
        }
      }
      xhr.send()
    },
    // 判断浏览器类型
    myBrowser() {
      var userAgent = navigator.userAgent //取得浏览器的userAgent字符串
      var isOpera = userAgent.indexOf('Opera') > -1
      if (isOpera) {
        return 'Opera'
      } //判断是否Opera浏览器
      if (userAgent.indexOf('Firefox') > -1) {
        return 'FF'
      } //判断是否Firefox浏览器
      if (userAgent.indexOf('Chrome') > -1) {
        return 'Chrome'
      }
      if (userAgent.indexOf('Safari') > -1) {
        return 'Safari'
      } //判断是否Safari浏览器
      if (
        userAgent.indexOf('compatible') > -1 &&
        userAgent.indexOf('MSIE') > -1 &&
        !isOpera
      ) {
        return 'IE'
      } //判断是否IE浏览器
      if (userAgent.indexOf('Trident') > -1) {
        return 'Edge'
      } //判断是否Edge浏览器
    },
  },
}
</script>
