<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" >
      <el-form-item label="点位名称：" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入点位名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点位地址：" prop="address">
        <el-input
          v-model.trim="queryParams.address"
          placeholder="请输入点位地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="right">
        <el-button plain size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
      <br>
      <el-button
        type="primary"
        size="mini"
        @click="handleAdd"
      >新增</el-button>
    </el-form>

    <el-table v-loading="loading" :data="adminList"  style="margin-top:20px;" border>
      <el-table-column label="点位名称" align="center" prop="name"  show-overflow-tooltip />
      <el-table-column label="点位地址" align="center" prop="address"  show-overflow-tooltip />
      <el-table-column label="摄像头名称" align="center" prop="dhDeviceName"  show-overflow-tooltip />
      <el-table-column label="摄像头通道ID" align="center" prop="vidCode"  show-overflow-tooltip />
      <el-table-column label="点位标签" align="center" prop="qrCodeUrl"  show-overflow-tooltip >
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.qrCodeUrl"
            style="width: 24px; height: 24px"
            :preview-src-list="[scope.row.qrCodeUrl]"
            :src="scope.row.qrCodeUrl">
          </el-image>
    　　</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"  show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="createBy"  show-overflow-tooltip />
      <el-table-column label="修改时间" align="center" prop="updateTime"  show-overflow-tooltip />
      <el-table-column label="修改人" align="center" prop="updateBy"  show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="lans"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            class="lans"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改、新增对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="auto" >
        <el-row :gutter="10">
          <el-col :span="12" >
            <el-form-item label="点位名称" prop="name">
              <el-input v-model="form.name" placeholder="请填写点位名称" @input="onInput()" maxlength="15" show-word-limit width="30%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="点位地址" prop="address">
              <el-input v-model="form.address" placeholder="请填写点位地址" @input="onInput()" maxlength="15" show-word-limit width="30%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="摄像头名称" prop="vidCode">
              <el-select
                v-model="form.vidCode"
                placeholder="请选择摄像头名称"
                size="small"
                style="width: 160px"
              >
                <el-option
                  v-for="dict in cocalChannelList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="设备类型" prop="dwtype">
              <el-select v-model="form.dwtype"   placeholder="请选择设备类型">
                <el-option
                  v-for="item in dwtypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="点位图片上传" prop="pictureRoute">
                <el-upload
                  class="upload-demo"
                  action="#"
                  accept=".jpeg,.png,.jpg,.gif,.PNG,.JPG,.JPEG,.GIF"
                  :limit = 1
                  :on-change="handleChange"
                  :file-list="fileList"
                  >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" plain>取 消</el-button>
      </div>
    </el-dialog>
    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    /> -->
     <el-pagination
      background
      @current-change="handleCurrentChange"
      :page-sizes="[10, 15, 20, 30]"
      @size-change="handleSizeChange"
      :current-page="queryParams.pageNo"
      :page-size="queryParams.pageSize"
      layout="sizes,prev, pager, next"
      :total="totalCount"
    >
    </el-pagination>
    <div class="qrcode" ref="qrCodeUrl" style="position: absolute;z-index: -1;opacity: 0;"></div>
    <a href="" download="" id="xz" style="position: absolute;z-index: -1;opacity: 0;"></a>
  </div>
</template>
<script>
import QRCode from 'qrcodejs2'
import { fileUpload } from "@/api/uploadfile.js";
import { addInspectionPoint, delInspectionPoint, updateInspectionPoint, getInspectionPoint, exportInspectionPoint } from "@/api/MochaITOM/point";
import { getLocalChannel, } from "@/api/device/camera";

export default {
  name: "Floor",
  data() {
    return {
      exportLoading:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      totalCount:undefined,
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 15,
        name: undefined,
        address:undefined,
        pageSize:15,
        pageNo:1
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "点位名称不能为空",  trigger: "blur"  }
        ],
        address: [
          { required: true, message: "点位地址不能为空",  trigger: "blur"  }
        ],
        vidCode: [
          { required: true, message: "摄像头名称不能为空",  trigger: ["blur",'change'] }
        ],
        // dwtype: [
        //   { required: true, message: "设备类型不能为空",  trigger: ["blur",'change']}
        // ],
        // pictureRoute: [
        //   { required: true, message: "文件不能为空", trigger: ["blur",'change'] }
        // ],
      },
      // 公司列表
      companyList: [],
      //责任人
      zrr:[],
      dwtypeList:[],
      num:0,
      fileList:[],
      base64:undefined,//二维码
      cocalChannelList:[],
      time:undefined
    };
  },
  created() {
    this.getList();//初始化table
  },
  methods: {
    //分页查询
    handleCurrentChange(val) {
      this.queryParams.pageNo = val;
      this.getList();
    },
    //分页查询
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    //视频通道数据
    // selectChanged(val){
    //   for(let i =0;i<this.cocalChannelList.length;i++){
    //     if(this.cocalChannelList[i].id == val){
    //       this.form.dhDeviceName = this.cocalChannelList[i].name
    //     }
    //   }
    // },
    //获取视频通道
    getLocal(){
       getLocalChannel({pageNo: 1,
        pageSize: 1500,
        unitType: 1,token:"d6790e9ac3c419f6fc8d48f8c2957afd"}).then(Response =>{
        let data = Response.data.pageList
        if(data.length>0){
          let arr = []
          for(let i = 0; i<data.length;i++){
            arr[i] = {}
            arr[i].id = data[i].id
            arr[i].name = data[i].name
          }
          this.cocalChannelList = arr
        }
      })
    },

    creatQrCode(text) {//二维码
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
          text: "点位编号:" + text, // 需要转换为二维码的内容
          width: 250,
          height: 250,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
      })
      setTimeout(()=>{
        this.base64 = window.atob(document.getElementsByClassName("qrcode")[0].getElementsByTagName("img")[0].src.split(',')[1]);
        this.handleChangeEWM(this.base64)
      },100)
    },
    handleChangeEWM(bytes){ //二维码上传
      var array = [];
      for(var i = 0; i < bytes.length; i++){
          array.push(bytes.charCodeAt(i));
      }
      var blob = new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
      var formData = new FormData();
      formData.append('file',blob,  '.jpg');
      formData.append('multipart',blob,  '.jpg');
      fileUpload(formData).then(response => {
        this.form.qrCodeUrl = response.data
        this.addData()
      });
    },
    handleChange(param){//点位图片上传
      this.num++
      if(this.num>1){
        this.num = 0
        return false
      }else{
        const formData = new FormData();
        formData.append('file', param.raw)
        formData.append('multipart', param.raw)
        fileUpload(formData).then(response => {
          this.msgSuccess("上传成功");
          this.form.pictureRoute = response.data
        });
      }
    },
    //强制el-input刷新
    onInput(){
        this.$forceUpdate();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      setTimeout(()=>{
        this.reset();
      },1000)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        name:undefined,
        current:1,
        size:15,
        pageSize:15,
        pageNo:1,

      }
      //this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {};
      //this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      getInspectionPoint(this.queryParams).then(response => {
        this.adminList = response.data.pageList;
        this.totalCount = response.data.totalCount;
        this.loading = false;
        this.getLocal()
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改";
      this.form = JSON.parse(JSON.stringify(row))
      this.form.buildId = Number(this.form.buildId)
      this.open = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
      this.list = []
    },
    /** 提交按钮 */
    submitForm(row) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.type = 1
          this.loading = true
          if (this.form.id != undefined) {
            updateInspectionPoint(this.form).then(response => {
              this.loading = false,
              this.$message.success("修改成功")
              this.open = false;
              this.getList();
            }).catch(()=>{
              this.loading = false
            })
          } else {
            this.time =  (new Date().getTime() / 1000).toFixed(0)
            this.form.qrContent = this.time
            this.creatQrCode(this.form.qrContent)
          }
        }
      });
    },
    /**新增 */
    addData(){
      addInspectionPoint(this.form).then(response => {
        this.loading = false
        if(response.status == "SUCCESS"){
          this.$message.success("新增成功")
          this.open = false;
          this.getList();
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInspectionPoint(ids);
        }).then(() => {
          this.getList();
          this.$message.success("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportInspectionPoint(this.queryParams).then(response =>{
        this.exportLoading = false;
        document.getElementById("xz").href = BASEPATH() + response.data
        document.getElementById("xz").download = response.data
        document.getElementById("xz").click()
      })
    }

  }
};
</script>
