<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="设备名称">
              <j-select-device placeholder="请选择设备名称" :multiple="false" v-model="queryParam.deviceId"/>
<!--              <j-search-select-tag placeholder="请选择设备名称" v-model="queryParam.deviceId" dict="bu_device,device_name,id"/>-->
            </a-form-item>
          </a-col>
<!--          <a-col :span="5">-->
<!--            <a-form-item label="传感器类型">-->
<!--              <j-dict-select-tag placeholder="请选择传感器类型" v-model="queryParam.typeId" dict-code="sensor_type"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md="5" :sm="7">-->
<!--            <a-form-item label="通讯地址">-->
<!--              <a-input placeholder="请输入通讯地址" v-model="queryParam.address"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md="5" :sm="7">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" >查询</a-button>
              <a-button @click="searchReset" style="margin-left: 8px">重置</a-button>
<!--              <a @click="handleToggleSearch" style="margin-left: 8px">-->
<!--                {{ toggleSearchStatus ? '收起' : '展开' }}-->
<!--                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>-->
<!--              </a>-->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-has="'sensor:add'">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('传感器信息表')">导出</a-button>
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
<!--        <a-button type="primary" icon="import">导入</a-button>-->
<!--      </a-upload>-->
      <!-- 高级查询区域 -->
<!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
    </div>

    <a-modal centered :width="240" v-model="visible" title="二维码" ok-text="确认"  cancel-text="打印" @ok="hideModal" >
      <img ref="print" style="max-width: 100%; max-height: 100%;" :src="this.qrCodeBase64" alt="QR Code" />
      <template slot="footer">
        <a-button type="primary" ghost @click="downCode(qrCodeBase64)">下载</a-button>
        <a-button type="primary" ghost @click="print">打印</a-button>
        <a-button type="primary" ghost @click="hideModal">确认</a-button>
      </template>

    </a-modal>
<!--    <div v-show="this.qrcodeStatus">-->
<!--        <img :src="this.qrCodeBase64" alt="QR Code" />-->
<!--    </div>-->

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{x:true}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="text" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleQrCode(record)" v-has="'sensor:code'">二维码</a>
          <a-divider type="vertical" v-has="'sensor:code'"/>
          <a @click="handleEdit(record)" v-has="'sensor:edit'">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown v-has="'sensor:del'">
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay" >
              <a-menu-item >
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>


    <buSensor-modal ref="modalForm" @ok="modalFormOk"></buSensor-modal>
  </a-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import BuSensorModal from './modules/BuSensorModal'
  // import BuSensorMeasurementsList from './BuSensorMeasurementsList'
  import BuSensorDataList from './BuSensorDataList'
  import '@/assets/less/TableExpand.less'
  import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
  import JSelectDevice from '@comp/jeecgbiz/JSelectDevice'
  import JSelectSensor from '@comp/jeecgbiz/JSelectSensor'
  import { getAction, putAction } from '../../api/manage'
  export default {
    name: "BuSensorList",
    mixins:[JeecgListMixin],
    components: {
      // BuSensorMeasurementsList,
      BuSensorDataList,
      BuSensorModal,
      JSuperQuery,
      JSelectDevice,
      JSelectSensor,
    },
    data () {
      return {
        description: '传感器信息表管理页面',
        timer: null,
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'设备名称',
            align:"center",
            dataIndex: 'deviceName',
          },
          {
            title:'传感器名称',
            align:"center",
            dataIndex: 'name',
          },
          {
            title:'传感器二维码',
            align:"center",
            dataIndex: 'code',
            scopedSlots: { customRender: 'imgSlot' },
          },
          {
            title:'传感器类型',
            align:"center",
            dataIndex: 'typeId_dictText',
          },
          {
            title:'传感器类型id',
            align:"center",
            dataIndex: 'typeId',
          },
          {
            title:'检测项目',
            align:"center",
            dataIndex: 'checkItem',
          },
          {
            title:'传感器顺序',
            align:"center",
            dataIndex: 'dataUnit'
          },
          {
            title:'传感器安装位置',
            align:"center",
            dataIndex: 'location'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/sensor/buSensor/list",
          delete: "/sensor/buSensor/delete",
          deleteBatch: "/sensor/buSensor/deleteBatch",
          exportXlsUrl: "/sensor/buSensor/exportXls",
          importExcelUrl: "sensor/buSensor/importExcel",
          // powerRemind :"sensor/buSensor/powerRemind",
          queryById:"/sensor/buSensor/queryById",
          qrCode:"/qrcode/getQRCodeBase64",
          edit: "/sensor/buSensor/edit",
        },
        dictOptions:{
         typeId:[],
         deviceId:[],
        },
        qrCodeBase64:"",
        qrcodeStatus:false,
        visible: false,
        codeId:'',
        codeTitle:'',
        /* 分页参数 */
        // ipagination:{
        //   current: 1,
        //   pageSize: 10,
        //   pageSizeOptions: ['10', '20', '50'],
        //   showTotal: (total, range) => {
        //     return range[0] + "-" + range[1] + " 共" + total + "条"
        //   },
        //   showQuickJumper: true,
        //   showSizeChanger: true,
        //   total: 0
        // },
        // selectedMainId:'',
        superFieldList:[],
      }
    },
    created() {
      // this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    // mounted() {
    //   if(this.timer){
    //     clearInterval(this.timer)
    //   }else{
    //     this.timer=setInterval(()=>{
    //       this.powerRemind() //传感器电池电压过低弹窗提示
    //       //获取数据
    //       // this.loadData();
    //     },6000000)
    //   }
    // },
    methods: {
      // powerRemind() {
      //   getActions(this.url.powerRemind,'get').then((res) => {
      //     if (res.success) {
      //       this.$message.success(res.message);
      //       this.loadData(1);
      //       this.syncHeadNotic(id)
      //     } else {
      //       that.$message.warning(res.message);
      //     }
      //   })
      // },
      // syncHeadNotic(anntId){
      //   getAction("sys/annountCement/syncNotic",{anntId:anntId})
      // },
      initDictConfig(){
        // initDictOptions('sensor_type').then((res) => {
        //   if (res.success) {
        //     this.$set(this.dictOptions, 'typeId', res.result)
        //   }
        // })
        // initDictOptions('').then((res) => {
        //   if (res.success) {
        //     this.$set(this.dictOptions, 'deviceId', res.result)
        //   }
        // })
      },
      // clickThenSelect(record) {
      //   return {
      //     on: {
      //       click: () => {
      //         this.onSelectChange(record.id.split(","), [record]);
      //       }
      //     }
      //   }
      // },
      // onClearSelected() {
      //   this.selectedRowKeys = [];
      //   this.selectionRows = [];
      //   this.selectedMainId=''
      // },
      // onSelectChange(selectedRowKeys, selectionRows) {
      //   this.selectedMainId=selectedRowKeys[0]
      //   this.selectedRowKeys = selectedRowKeys;
      //   this.selectionRows = selectionRows;
      // },
      // loadData(arg) {
      //   if(!this.url.list){
      //     this.$message.error("请设置url.list属性!")
      //     return
      //   }
      //   //加载数据 若传入参数1则加载第一页的内容
      //   if (arg === 1) {
      //     this.ipagination.current = 1;
      //   }
      //   var params = this.getQueryParams();//查询条件
      //   this.loading = true;
      //   getAction(this.url.list, params).then((res) => {
      //     if (res.success) {
      //       this.dataSource = res.result.records;
      //       this.ipagination.total = res.result.total;
      //     }
      //     if(res.code===510){
      //       this.$message.warning(res.message)
      //     }
      //     this.loading = false;
      //   })
      // },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'useTime',text:'使用时间',dictCode:''})
        fieldList.push({type:'string',value:'deviceId',text:'设备ID',dictCode:''})
        this.superFieldList = fieldList
      },

      handleQrCode(record){
        if(record.code!=null&&record.code!==""&&record.code!==undefined){
          getAction(this.url.queryById,{id:record.id}).then((res)=>{
            this.qrCodeBase64 = res.result.code
            this.codeId = ''
            this.codeTitle= record.deviceName
            this.visible = true
          });
        }else{
          getAction(this.url.qrCode,{content:record.id}).then((res)=>{
            this.qrCodeBase64 = res.data
            this.codeId = record.id
            this.codeTitle= record.deviceName
            this.visible = true
          });
        }
      },
      hideModal() {
        if(this.codeId!==''){
          const formData = { code: this.qrCodeBase64, id: this.codeId }
          putAction(this.url.edit, formData).then((res) => {
            if (res.success) {
              this.loadData();
            } else {
              this.$message.warning(res.message);
            }
          }).finally(() => {
            this.visible = false;
          })
        }else {
          this.visible = false;
        }
      },
      //打印
      print() {
        this.$print(this.$refs.print,{type: "html", targetStyles: ["*"],ignoreElements: ["no-print"]})
      },
      //下载
      downCode(content) {
        let aLink = document.createElement('a');
        let blob = this.base64ToBlob(content); //new Blob([content]);
        let evt = document.createEvent("HTMLEvents");
        console.log("点击下载",evt)
        evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        aLink.download = this.codeTitle;
        aLink.href = URL.createObjectURL(blob);
        // aLink.dispatchEvent(evt);
        aLink.click()
      },
      //base64转blob
      base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
      }


    }
  }
</script>
<style scoped>

</style>