<template>
  <div class="content-container goaf">
    <el-row class="tool-bar">
      <el-col :span="3" class="left">
        <div class="content-title">
          采空区
        </div>
      </el-col>
      <el-col :span="21" class="right">
        <el-select v-model="conditions.goafOrebelt" class="search-input m-right-15" filterable placeholder="矿带" clearable @change="changeArea(1)">
          <el-option v-for="(item,index) in goafOrebelts" :key="index" :value="item" :label="item" />
        </el-select>
        <el-select v-model="conditions.goafOrebody" class="search-input m-right-15" filterable placeholder="矿体" clearable @change="changeArea(2)">
          <el-option v-for="(item,index) in goafOrebodys" :key="index" :value="item.goafOrebody" :label="item.goafOrebody" />
        </el-select>
        <el-select v-model="conditions.goafOreheight" class="search-input m-right-15" filterable placeholder="中段" clearable @change="changeArea(3)">
          <el-option v-for="(item,index) in goafOreheights" :key="index" :value="item.goafOreheight" :label="item.goafOreheight" />
        </el-select>
        <el-select v-model="conditions.goafId" class="search-input m-right-15" filterable placeholder="采空区编号" clearable @change="changeArea(4)">
          <el-option v-for="item in goafNames" :key="item.goafId" :value="item.goafId" :label="item.goafName" />
        </el-select>
        <el-button type="primary" style="margin-right: 10px;" @click="getData">查询</el-button>
        <!-- <el-button type="primary" @click="batchDown">批量下载二维码</el-button> -->
      </el-col>
    </el-row>

    <el-row class="m-top-15">
      <el-table v-loading="listLoading" class="page-table" border fit :data="dataList">
        <el-table-column type="index" label="序号" header-align="center" align="center" width="60" />
        <el-table-column prop="goafOrebelt" label="矿带">
          <template v-slot="{row}">
            <span>{{ convertNum(row.goafOrebelt) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goafOrebody" label="矿体" />
        <el-table-column prop="goafOreheight" label="中段" />
        <el-table-column prop="goafName" label="采空区名称" />
        <el-table-column prop="positionName" label="检查表" header-align="center" align="center">
          <template v-slot="{row}">
            <!-- <span v-if="!isNull(row.goafChecklistId)" class="icon iconfont icon-erweima" style="color:#fff" @click="showQrcode(row)" /> -->
            <span v-if="row.goafChecklistIsbind===1">{{ row.goafChecklistTitle }}</span>
            <span v-else>未绑定</span>
          </template>
        </el-table-column>
        <el-table-column prop="goafInfoRemak" label="备注" align="right">
          <template v-slot="{row}">
            <span>{{ row.goafInfoRemak||'--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="180">
          <template v-slot="{row}">
            <el-button size="mini" type="text" style="color:#1B81FF" @click="showDetail(row)">详情</el-button>
            <el-button v-if="row.goafChecklistIsbind===0" size="mini" type="text" style="color:#1B81FF" @click="handleUpdate(row)">绑定</el-button>
            <el-button v-else size="mini" type="text" style="color:#E44E2D" @click="handleDelete(row)">解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container" style="float:right;margin-right:40px;">
        <pagination v-show="total>0" :total="total" :page.sync="conditions.page" :limit.sync="conditions.limit" @pagination="getData" />
      </div>
    </el-row>
    <check-list-bind ref="bind" @formSuccess="getData" />
    <detail ref="detail" />
    <QrCode ref="qrcode" />
    <div id="qrcode" ref="qrcodeModal" style="position:fixed;top:-9999px;" />
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import JSZip from 'jszip'
import saveAs from 'file-saver'
import QRCode from 'qrcodejs2'
import { getGoafBaseInfoByPage, updateGoaf, getGoafBaseInfo } from '@/api/goaf/info'
import { Pagination } from '@/components'
import { NumConvertLM } from '@/utils'
import { QrCode } from '@/components'
// import checkListBind from '@/views/goaf/info/components/Goaf'
import checkListBind from './components/checkListBind.vue'
import Detail from '@/views/goaf/info/components/detail'
var zip = new JSZip()
export default {
  components: { Pagination, QrCode, checkListBind, Detail },
  data() {
    return {
      dataList: [],
      total: 0,
      listLoading: false,
      goafList: [],
      goafOrebelts: [],
      goafOrebodys: [],
      goafOreheights: [],
      goafNames: [],
      conditions: {
        page: 1,
        limit: 10,
        goafId: '',
        goafOrebelt: '',
        goafOrebody: '',
        goafOreheight: ''
      }
    }
  },
  created() {
    this.getData()
    getGoafBaseInfo().then((res) => {
      const goafOrebelts = res.data.map(item => item.goafOrebelt)
      this.goafOrebelts = [...new Set(goafOrebelts)]
      this.goafList = res.data
    })
  },
  methods: {
    convertNum(num) {
      return num ? NumConvertLM(num) : '--'
    },
    getData() {
      this.listLoading = true
      if (this.conditions.goafOrebelt === '') delete this.conditions.goafOrebelt
      if (this.conditions.goafOrebody === '') delete this.conditions.goafOrebody
      if (this.conditions.goafOreheight === '') delete this.conditions.goafOreheight
      if (this.conditions.goafName === '') delete this.conditions.goafName
      getGoafBaseInfoByPage(this.conditions).then((resp) => {
        this.listLoading = false
        const { code, msg, data, total } = resp
        if (code === 0) {
          this.dataList = data
          this.total = total
        } else {
          this.$message.error(msg)
        }
      })
    },
    changeArea(type) {
      const goafs = this.deeepClone(this.goafList)
      let goafOrebodys = this.deeepClone(this.goafOrebodys)
      let goafOreheights = this.deeepClone(this.goafOreheights)
      let goafNames = this.deeepClone(this.goafNames)
      if (type === 1) {
        goafOrebodys = goafs.filter(item => item.goafOrebelt === this.conditions.goafOrebelt)
        this.goafOrebodys = goafOrebodys
        this.goafOreheights = []
        this.goafNames = []
        this.conditions.goafOrebody = ''
        this.conditions.goafOreheight = ''
        this.conditions.goafName = ''
        this.conditions.goafId = ''
      } else if (type === 2) {
        goafOreheights = goafs.filter(item => (item.goafOrebody === this.conditions.goafOrebody) && (item.goafOrebelt === this.conditions.goafOrebelt))
        this.goafOreheights = goafOreheights
        this.goafNames = []
        this.conditions.goafOreheight = ''
        this.conditions.goafName = ''
        this.conditions.goafId = ''
      } else if (type === 3) {
        goafNames = goafs.filter(item => (item.goafOreheight === this.conditions.goafOreheight) && (item.goafOrebody === this.conditions.goafOrebody) && (item.goafOrebelt === this.conditions.goafOrebelt))
        this.goafNames = goafNames
        this.conditions.goafName = ''
        this.conditions.goafId = ''
      } else {
        for (let i = 0; i < goafNames.length; i++) {
          if (this.conditions.goafId === goafNames[i].goafId) {
            this.conditions.goafName = goafNames[i].goafName
          }
        }
      }
      this.$forceUpdate()
    },
    isNull(val) {
      if (val !== undefined && val !== 'undefined' && val !== null && val !== '' && val !== ' ') {
        return false
      }
      return true
    },
    showQrcode(row) {
      this.$refs.qrcode.draw(row.goafChecklistId)
    },
    batchDown() { /* 点击按钮获取制作二维码素材*/
      const content = JSON.parse(JSON.stringify(this.dataList))
      this.downloadMaterial(content)
    },

    downloadMaterial(content) { // 下载物料
      this.batch(content, '检查表')
    },

    async batch(arr, fileName) {
      const self = this
      window.loading = this.$loading({
        lock: true,
        text: '制作二维码中!',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      zip = new JSZip()
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        await self.drawQrcode(item.type, item.goafChecklistId).catch(() => {
          window.loading.close()
          this.$message.error('导出失败')
        })
        await self.packMaterial(`${item.goafOrebelt}-${item.goafOrebody}-${item.goafOreheight}-${new Date().getTime()}`).catch(() => {
          window.loading.close()
          this.$message.error('导出失败')
        })
      }
      zip.generateAsync({
        type: 'blob'
      }).then((blob) => {
        saveAs(blob, fileName + '二维码物料.zip')
        window.loading.close()
      })
    },
    drawQrcode(url, sleep) { // 绘制二维码
      this.$refs.qrcodeModal.innerHTML = ''
      return new Promise((resolve) => {
        new QRCode('qrcode', {
          width: 400,
          height: 400,
          text: url.toString()
        })
        setTimeout(function() {
          resolve()
        }, sleep || 300)
      })
    },

    packMaterial(name) { // 打包处理
      if (!name) name = 'xxx'
      return new Promise((resolve, reject) => {
        html2canvas(document.getElementById('qrcode'), {
          backgroundColor: null,
          useCORS: true,
          dpi: 500,
          scale: 5
        }).then((canvas) => {
          let dataURL = canvas.toDataURL('photo/png')
          dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, '')
          zip.file(name + '.jpg', dataURL, { base64: true })
          resolve()
        }).catch((e) => {
          reject(e)
        })
      })
    },
    showDetail(data) {
      this.$refs['detail'].showDetailModel(JSON.parse(JSON.stringify(data)))
    },
    // "Edit Risk" Model
    handleUpdate(data) {
      this.$refs['bind'].showEditModel(JSON.parse(JSON.stringify(data)))
    },
    // Delete Action
    handleDelete(data) {
      const { goafName } = data
      const formData = JSON.parse(JSON.stringify(data))
      formData.goafChecklistId = ''
      formData.goafChecklistTitle = ''
      formData.goafChecklistIsbind = 0
      this.$confirm(`此操作将解绑该数据${goafName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateGoaf(formData).then((resp) => {
          const { msg } = resp
          this.getData()
          this.$message.success(msg)
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    deeepClone(params) {
      return JSON.parse(JSON.stringify(params))
    }
  }
}
</script>
  <style lang="scss" scoped>
      @import "icon/iconfont.css";
      .content-container {
          background: #193142FF;
          margin: 10px 10px 10px 0;
          padding: 15px;
          height: calc(100vh - 90px);
          box-sizing: border-box;
          .content-title {
              font-size: 18px;
              font-weight: bold;
              color: #FFFFFF;

              font-weight: bold;
              background: linear-gradient(0deg, #FFFFFF 0%, #98A8B7 100%);
              background-clip: text;
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
          }

          .tool-bar {

              .left {
                  float: left;
              }

              .right {
                  float: right;
                  text-align: right;
              }

              .title {
                  line-height: 36px;
                  font-size: 26px;
              }

              .search-input {
                  width: 200px !important;
              }
          }

          .el-dropdown {
              margin: 0 10px;
          }
      }
  </style>
  <style lang="scss">
  .goaf .el-table__body tr.hover-row>td {
    background-color: #306379;
  }
  .goaf{
        .page-table{
          height: calc(100vh - 260px);
          overflow-y: auto;
        }
      }
  </style>

