<template>
  <div class="app-container">
    <el-form :model="query" ref="query" :inline="true"  >
      <el-form-item label="分区名称:" >
          <el-input
            v-model="query.dkAreaName"
            placeholder="请输入分区名称"
            clearable
          ></el-input>
      </el-form-item>
      <el-form-item label="防区名称:" >
          <el-input
            v-model="query.dkZoneName"
            placeholder="请输入防区名称"
            clearable
          ></el-input>
      </el-form-item>
       <el-form-item label="布防状态:" >
          <el-select
            v-model="query.dkZoneStatus"
            placeholder="请选择布防状态"
            clearable
            size="small"
            style="width: 100px"
          >
            <el-option
              v-for="dict in defenseStatus2"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
      </el-form-item>
      <el-form-item class="right" >
        <el-button  plain size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="
            queryPerimeterDevice({
              pageNo: 1,
              pageSize: pageSize,
              dkAreaName: query.dkAreaName,
              dkZoneName: query.dkZoneName,
              dkZoneStatus: query.dkZoneStatus,})"
          >搜索</el-button
        >
      </el-form-item>
      <br>
      <el-button type="primary" size="mini"  @click="handleAdd()" >新增</el-button>
    </el-form>
    <!-- <el-divider></el-divider> -->
    <el-table
      v-loading="loading"
      :data="tableData"
      stripe
      style="margin-top:20px"
      id="out-table"
      border
    >
      <el-table-column label="序号" align="center" prop="index"  show-overflow-tooltip >
        <template slot-scope="scop">
          {{scop.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="设备编号" align="center" prop="connId"  show-overflow-tooltip />
      <el-table-column label="设备名称" align="center" prop="name"  show-overflow-tooltip />
      <el-table-column label="分区名称" align="center" prop="dkAreaName"  show-overflow-tooltip />
      <el-table-column label="防区名称" align="center" prop="dkZoneName"  show-overflow-tooltip />
      <el-table-column label="设备状态" align="center" prop="status"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span  :class="scope.row.status == '1' ? 'success' : scope.row.status == '1' ? 'warning' : 'danger' ">{{scope.row.status == "1" ? "在线" : "下线"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="布防状态" align="center" prop="dkZoneStatus"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span :class="scope.row.dkZoneStatus == '布防' ? 'success' :  scope.row.dkZoneStatus == '撤防' ? 'warning' : 'info'">{{scope.row.dkZoneStatus}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"  show-overflow-tooltip />
      <el-table-column label="操作" width="150" fixed="right" >
        <template slot-scope="scope">
          <el-button class="lans" @click="handleUpdate(scope.row)" :disabled="scope.row.status != '1' || scope.row.dkZoneStatus != '布防' && scope.row.dkZoneStatus != '撤防'">编辑</el-button>
          <el-button
           class="hongs"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @current-change="handleCurrentChange"
      :page-sizes="[10, 15, 20, 30]"
      @size-change="handleSizeChange"
      :current-page="pageNo"
      :page-size="pageSize"
      layout="sizes,prev, pager, next"
      :total="totalCount"
    >
    </el-pagination>
    <!-- 新增对话框 -->
    <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="connId">
              <el-input v-model="form.connId" placeholder="请输入设备编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分区名称" prop="dkAreaName">
              <el-input v-model="form.dkAreaName" placeholder="请输入分区名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="防区名称" prop="dkZoneName">
              <el-input v-model="form.dkZoneName" placeholder="请输入防区名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!-- <el-col :span="12" >
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="form.status"  size="small" placeholder="请选择设备状态">
                <el-option
                  v-for="dict in deviceStatus"
                  :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="dkZoneStatus">
              <el-select v-model="form.dkZoneStatus"  size="small" placeholder="请选择设防状态">
                <el-option
                  v-for="dict in defenseStatus"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </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>
    <!-- 修改对话框 -->
    <el-dialog :title="title" :visible.sync="open1" width="600px" append-to-body :before-close="cancel" :close-on-click-modal="false">
      <el-form ref="form1" :model="form" :rules="rules1" label-width="auto" >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编号" prop="connId">
              <el-input v-model="form.connId" placeholder="请输入设备编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分区名称" prop="dkAreaName">
              <el-input v-model="form.dkAreaName" placeholder="请输入分区名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="防区名称" prop="dkZoneName">
              <el-input v-model="form.dkZoneName" placeholder="请输入部署位置" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!-- <el-col :span="12" >
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="form.status"  size="small" placeholder="请选择设备状态">
                <el-option
                  v-for="dict in deviceStatus"
                  :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="dkZoneStatus">
              <el-select v-model="form.dkZoneStatus"  size="small" placeholder="请选择设防状态">
                <el-option
                  v-for="dict in defenseStatus"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </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>
    <!-- 确认对话框 -->
    <el-dialog :title="title2" :visible.sync="open2" width="600px" append-to-body :before-close="cancel2" :close-on-click-modal="false">
      <p style="margin-top:-10px;font-weight:700">下列防区布防状态将被修改</p>
      <el-row :gutter="10">
        <el-col :span="12"  v-for="(item, index) in fq" :key="index" style="line-height:30px">{{item.dkAreaName}} -- {{item.dkZoneName}}</el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2" plain>取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
// 引入导出Excel表格依赖
import FileSaver from "file-saver";
import api from "@/api/device/guard";
// import XLSX from "xlsx";
import axios from "axios";

export default {
  name: "javascriptthree",
  data() {
    return {
      // 状态数据字典
      // deviceStatus: [
      //   {
      //     dictLabel: "在线",
      //     dictValue: 1,
      //   },
      //   {
      //     dictLabel: "下线",
      //     dictValue: 0,
      //   }
      // ],
      defenseStatus:[
        {
          dictLabel: "布防",
          dictValue: "布防",
        },
        {
          dictLabel: "撤防",
          dictValue: "撤防",
        },
      ],
      defenseStatus2:[
        {
          dictLabel: "布防",
          dictValue: "布防",
        },
        {
          dictLabel: "撤防",
          dictValue: "撤防",
        },
        {
          dictLabel: "旁路",
          dictValue: "旁路",
        },
      ],
      query: {

      },
      loading: true,
      multipleSelection: [],

      dialogFormVisible: false,

      formLabelWidth: "130px",

      //input设备名称查询
      device_name: "",
      //动态按钮name
      el_button: "新 增",
      //存储动态列
      cols: [],
      //存储查询列表数据
      tableData: [],
      //存储列表总数
      totalCount: 0,
      //存储开始页
      pageNo: 1,
      //存储每页几条
      pageSize: 15,
      //存储新增动态form数据
      insert_data: [],
      //存储修改状态数据
      update_state: [],
      update_value: "",
      update_win: false,
      //表格自适应高度
      tableHeight: undefined,
      open:false,
      open1:false,
      title:undefined,
      form:{},
      // 表单校验
      rules: {
        connId:[
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        name:[
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        dkAreaName:[
          { required: true, message: "分区名称不能为空", trigger: "blur" }
        ],
        dkAreaName: [
          { required: true, message: "防区名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "设备状态不能为空", trigger: ["blur",'change'] }
        ],
        dkZoneStatus: [
          { required: true, message: "设防状态不能为空", trigger: ["blur",'change'] }
        ],

      },
      // 表单校验
      rules1: {
        // connId:[
        //   { required: true, message: "设备编号不能为空", trigger: "blur" }
        // ],
        // name:[
        //   { required: true, message: "设备名称不能为空", trigger: "blur" }
        // ],
        // dkAreaName:[
        //   { required: true, message: "分区名称不能为空", trigger: "blur" }
        // ],
        // dkAreaName: [
        //   { required: true, message: "防区名称不能为空", trigger: "blur" }
        // ],
        status: [
          { required: true, message: "设备状态不能为空", trigger: ["blur",'change'] }
        ],
        dkAreaStatus: [
          { required: true, message: "设防状态不能为空", trigger: ["blur",'change'] }
        ],
      },
      fq:[],
      title2:"防区列表",
      open2:false
    };
  },
  created() {
    this.queryPerimeterDevice({
      pageNo: this.pageNo,
      pageSize: this.pageSize,
    });
  },
  mounted() {

  },
  methods: {
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
     /** 编辑按钮操作 */
    handleUpdate(row){
      this.form = JSON.parse(JSON.stringify(row))
      this.open1 = true;
      this.title = "修改";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open1 = false;
      this.loading = false
      this.reset();
    },
    // 取消按钮
    cancel2() {
      this.open2 = false;
      setTimeout(()=>[
        this.fq = []
      ],1000)

    },
      /** 重置按钮操作 */
      resetQuery() {
        this.query = {
          pageNo: 1,
          pageSize:15
        },
        this.handleQuery();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.handleCurrentChange(1);
      },
    insert_add() {
      this.el_button = "新增";
      this.insert();
      this.dialogFormVisible = true;
      this.update_win = false;
    },
    //新增和修改区域入侵告警设备
    submitForm() {
      if(this.title == "新增"){
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.loading = true
            this.form.status =1
              api
                .addPerimeterDevice(this.form).then((response) => {
                  if(response.status == "SUCCESS"){
                    this.$message.success("新增成功");
                    this.open = false;
                    this.queryPerimeterDevice({
                      pageNo: this.pageNo,
                      pageSize: this.pageSize,
                    });
                  }else{
                    this.queryPerimeterDevice({
                      pageNo: this.pageNo,
                      pageSize: this.pageSize,
                    });
                  }
                });
          }
        })
      }else{
        this.$refs["form1"].validate(valid => {
          if (valid) {
            this.loading = true
            let arr = []
            api.queryPerimeterDevice({dkAreaName:this.form.dkAreaName,pageSize:200,pageNo:1}).then((response1) => {
              if(response1.data.pageList.length>0){
                let data = response1.data.pageList
                this.title2 = this.form.dkAreaName
                for(let i=0;i<data.length;i++){
                  if(data[i].dkZoneStatus == "布防" || data[i].dkZoneStatus == "撤防"){
                    // this.fq.push(data[i])
                    arr.push(data[i])
                  }
                }
                // if(this.fq.length>1){
                if(arr.length>0){
                  for(let i =0;i<arr.length;i++){
                    if(arr[i].connId == arr[arr.length-1].connId){
                      this.fq.push(arr[i])
                    }
                  }
                  this.open2 = true
                }else{
                  this.submitForm2()
                }
              }
            })
            // api.sf({device:JSON.stringify({"nMachine":Number(this.form.connId),"nAreaNo":Number(this.form.dkAreaNo),"operateType":operateType})}).then((response) => {

            // })
          }
        })
      }
    },
    submitForm2() {
      let operateType = undefined
      // console.log(this.form.dkZoneStatus)
      if(this.form.dkZoneStatus == "布防"){
        operateType = 1
      }else{
        operateType = 3
      }
            api.sf({device:JSON.stringify({"nMachine":Number(this.fq[0].connId),"nAreaNo":Number(this.form.dkAreaNo),"operateType":operateType})}).then((response) => {

            })
      // axios.post( "http://10.208.0.198:8888", {"nMachine":Number(this.form.connId),"nAreaNo":Number(this.form.dkAreaNo),"operateType":operateType},{
      //   timeout: 10000,
      //   headers:{
      //     'content-type':"application/x-www-form-urlencoded"
      //   }
      // })
        api
          .updatePerimeterDevice(this.form).then((response) => {
            if(response.status == "SUCCESS"){
              this.open1 = false;
              this.open2 = false;
              setTimeout(()=>[
                this.fq = []
              ],1000)
              setTimeout(()=>{
                this.$message.success("修改成功");

                this.queryPerimeterDevice({
                  pageNo: this.pageNo,
                  pageSize: this.pageSize,
                });
              },5000)

            }else{
              this.open1 = false;
              this.open2 = false;
              this.queryPerimeterDevice({
                pageNo: this.pageNo,
                pageSize: this.pageSize,
              });
              setTimeout(()=>[
                this.fq = []
              ],1000)
            }
          });
    },
    //分页查询
    handleCurrentChange(val) {
      this.pageNo = val;
      this.queryPerimeterDevice({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        dkAreaName: this.query.dkAreaName,
        dkZoneName: this.query.dkZoneName,
        dkZoneStatus: this.query.dkZoneStatus,
      });
    },
    //改变每条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.queryPerimeterDevice({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        dkAreaName: this.query.dkAreaName,
        dkZoneName: this.query.dkZoneName,
        dkZoneStatus: this.query.dkZoneStatus,
      });
    },
    //查询区域入侵告警设备登记信息
    queryPerimeterDevice(data) {
      api.queryPerimeterDevice(data).then((response) => {
        if (response.status == "SUCCESS") {
          if (response.data.pageList) {
            this.tableData = response.data.pageList;
            this.totalCount = response.data.totalCount;
            this.loading = false;
          }
        }
      });
    },
    handleDelete(index, row) {
      this.$confirm("确定删除该数据吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.perimeterAlarmDel({ id: row.id }).then((response) => {
            this.$message.success("删除成功");
            this.queryPerimeterDevice({
              pageNo: this.pageNo,
              pageSize: this.pageSize,
            });
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    //定义导出Excel表格事件
    exportExcel() {
      /* 从表生成工作簿对象 */
      // var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
      // /* 获取二进制字符串作为输出 */
      // var wbout = XLSX.write(wb, {
      //   bookType: "xlsx",
      //   bookSST: true,
      //   type: "array",
      // });
      // try {
      //   FileSaver.saveAs(
      //     //Blob 对象表示一个不可变、原始数据的类文件对象。
      //     //Blob 表示的不一定是JavaScript原生格式的数据。
      //     //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
      //     //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
      //     new Blob([wbout], { type: "application/octet-stream" }),
      //     //设置导出文件名称
      //     "sheetjs.xlsx"
      //   );
      // } catch (e) {
      //   if (typeof console !== "undefined") console.log(e, wbout);
      // }
      // return wbout;
    },
    batchDelete() {
      let multData = this.multipleSelection;
      let tableData = this.tableData;
      let multDataLen = multData.length;
      let tableDataLen = tableData.length;

      for (let i = 0; i < multDataLen; i++) {
        for (let y = 0; y < tableDataLen; y++) {
          if (JSON.stringify(tableData[y]) == JSON.stringify(multData[i])) {
            //判断是否相等，相等就删除
            this.tableData.splice(y, 1);
          }
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>
<style>
.el-select{
  width:auto !important
}
</style>
