<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"
          style="width: 140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点位地址:" prop="address">
        <el-input
          v-model.trim="queryParams.address"
          placeholder="请输入点位地址"
          clearable
          size="small"
          style="width: 140px"
          @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"
        v-hasPermi="['system:admin:add']"
      >新增</el-button>
      <el-button
        plain
        size="mini"
        :loading="exportLoading"
        @click="handleExport"
        v-hasPermi="['system:admin:export']"
      >导出</el-button>
    </el-form>
    <el-table v-loading="loading" :data="adminList" border style="margin-top:20px">
      <el-table-column label="点位名称" align="left" prop="spotName"  show-overflow-tooltip />
      <el-table-column label="所属单位" align="left" prop="companyName"  show-overflow-tooltip />
      <el-table-column label="点位地址" align="left" prop="spotAddress"  show-overflow-tooltip />
      <!-- <el-table-column label="设备类型" align="left" prop="phone"  show-overflow-tooltip /> -->
      <el-table-column label="点位标签" align="left" prop="spotLabelRoute"  show-overflow-tooltip >
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.spotLabelRoute"
            style="width: 24px; height: 24px"
            :preview-src-list="['https://smartpark.caih.com/dmapi/archive/' + scope.row.spotLabelRoute]"
            :src="'https://smartpark.caih.com/dmapi/archive/' + scope.row.spotLabelRoute">
          </el-image>
    　　</template>
      </el-table-column>
      <el-table-column label="点位图片" align="left" prop="pictureRoute"  show-overflow-tooltip >
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.pictureRoute"
            style="width: 24px; height: 24px"
            :preview-src-list="['https://smartpark.caih.com/dmapi/archive/' + scope.row.pictureRoute]"
            :src="'https://smartpark.caih.com/dmapi/archive/' + scope.row.pictureRoute">
          </el-image>
    　　</template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="remarks"  show-overflow-tooltip />
      <el-table-column label="最新更新时间" align="left" prop="latestChangeTime"  show-overflow-tooltip />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            class="lans"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:admin:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            class="lans"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:admin:remove']"
          >删除</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="20">
          <el-col :span="12" >
            <el-form-item label="点位名称" prop="spotName">
              <el-input v-model="form.spotName" placeholder="请填写点位名称" @input="onInput()" maxlength="15" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称" prop="companyCode">
                  <el-select
                    v-model="form.companyCode"
                    placeholder="请选择单位名称"
                    size="small"
                    style="width: 160px"
                  >
                    <el-option
                      v-for="dict in companyList"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="点位地址" prop="spotAddress">
              <el-input v-model="form.spotAddress" placeholder="请填写点位地址" @input="onInput()" maxlength="15" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="设备编号" prop="data1">
              <el-input v-model="form.data1" placeholder="请填写设备编号" @input="onInput()" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请填写备注" @input="onInput()" maxlength="30" show-word-limit />
            </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"
    />
    <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 { BASEPATH } from "@/assets/js/common.js";
import { listChannel } from "@/api/system/product";
import { getDeviceType } from "@/api/business/deviceMange";
import { fileUpload } from "@/api/business/uploadfile.js";
import { addInspectionPoint, delInspectionPoint, updateInspectionPoint, getInspectionPoint, exportInspectionPoint } from "@/api/business/OM/MochaITOM/point";
import { YearMonthDateSFN } from "@/assets/js/dataFormate.js";
export default {
  name: "Floor",
  data() {
    return {
      exportLoading:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        address:undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        spotName: [
          { required: true, message: "点位名称不能为空",  trigger: "blur"  }
        ],
        spotAddress: [
          { required: true, message: "点位地址不能为空",  trigger: "blur"  }
        ],
        data1: [
          { required: true, message: "设备编号不能为空",  trigger: "blur"  }
        ],

        companyCode: [
          { 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,//二维码
      loading:true,
    };
  },
  created() {
    this.getList();//初始化table
  },
  methods: {
    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, Date.now() + '.jpg');
      formData.append('multipart',blob, Date.now() + '.jpg');
      fileUpload(formData).then(response => {
        this.form.spotLabelRoute = 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
           this.$refs.form.clearValidate('pictureRoute')
        });
      }
    },
    //强制el-input刷新
    onInput(){
        this.$forceUpdate();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        name:undefined,
        current:1,
        size:10
      }
      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.records;
        this.total = response.data.total;
        this.loading = false;
      });
      /* 公司列表 */
      listChannel(this.queryParams).then(response => {
        if(response.data.records.length>0){
          this.companyList = response.data.records.map(val =>{
            return {
              dictValue:val.ownerId,
              dictLabel:val.ownerName,
              address:val.ownerAddress,
            }
          })
        }
      });
      //设备类型
      getDeviceType({current:1,size:100}).then(response =>{
        this.dwtypeList = response.data.records.map(val=>{
          return {
            id:val.id,
            name:val.typeName
          }
        });
      })
    },

    /** 修改按钮操作 */
    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.latestChangeTime = YearMonthDateSFN()
          this.form.spotType = 1
          this.form.userName = 1
          this.loading = true
          if (this.form.id != undefined) {
            updateInspectionPoint(this.form).then(response => {
              this.loading = false,
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(()=>{
              this.loading = false
            })
          } else {
            this.form.spotLabelAnalysis = new Date().getTime()
            this.creatQrCode(this.form.spotLabelAnalysis)
          }
        }
      });
    },
    /**新增 */
    addData(){
      addInspectionPoint(this.form).then(response => {
        this.loading = false
        if(response.status == "SUCCESS"){
          this.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        }
      }).catch((err)=>{
        this.loading = false
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInspectionPoint(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).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>
