<template>
  <div style="cursor: default; width: 99%">
    <div class="search-box">
      <search-bar
        @fun="getDisplayType"
        :displayType="displayType"
        @fun2="getIDName"
        @fun3="getIsOnline"
        ref="screenData"
      >
        <template slot="search-box">
          <template v-if="userType == 1">
            <el-select
              v-model="queryInfo.dver"
              class="select01"
              clearable
              size="mini"
              placeholder="请选择设备版本"
              @change="searchChange()"
            >
              <el-option
                v-for="item in dverGather"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </template>
      </search-bar>
      <!-- <el-button
        class="devicePlant"
        type="primary"
        size="mini"
        v-btnRight:pestRanking="$route.path"
        @click="devicePlant"
        >害虫排名</el-button
      >
      <el-button
        class="pestAll"
        type="primary"
        size="mini"
        v-btnRight:pestAnalysis="$route.path"
        @click="pestAll"
        >害虫分析</el-button
      > -->
    </div>

    <template v-if="displayType == 1">
      <el-row :gutter="10" v-loading="loading">
        <el-col
          :xs="24"
          :sm="24"
          :md="12"
          :lg="8"
          :xl="6"
          v-for="item in equipList"
          :key="item.imei"
        >
          <el-card class="box-card">
            <equip-item :is_online="item.device_status">
              <span
                slot="set"
                class="superOperate el-icon-setting"
                @click="equipOperation(item)"
              ></span>
              <span slot="title">虫情测报</span>
              <div slot="content" class="content">
                <p :title="item.device_name">
                  <i class="iconfont icon-biaoqian"></i>
                  设备名称：{{
                    (item.device_name == "" ? "无" : item.device_name)
                      | ellipsis
                  }}
                </p>
                <p>
                  <i class="iconfont icon-yonghu"></i>
                  设备ID：{{ item.imei }}
                </p>
                <p class="onlineState">
                  <i class="iconfont icon-diannao"></i>在线状态：
                  <span
                    :class="{
                      red: item.is_online == 0,
                      green: item.is_online == 1,
                    }"
                  >
                    {{ equipStateDict.is_online.value[item.is_online] }}
                  </span>
                </p>
                <p>
                  <i class="iconfont icon-yonghu"></i>
                  隶属海关组织 :
                  <span v-if="item.org_list.length == 1">{{
                    item.org_name
                  }}</span>
                  <el-popover
                    ref="popover"
                    placement="right"
                    title=""
                    width="150"
                    trigger="hover"
                    v-else
                  >
                    <div class="popover-content" v-html="content"></div>
                    <span @mouseover="orglisthover(item)" slot="reference"
                      >{{ item.org_list[0].org_name }}...</span
                    >
                  </el-popover>
                </p>
                <p>
                  <i class="iconfont icon-biaoqian"></i>
                  所属监测点 : {{ item.point_name}}
                </p>
                <p>
                  <i class="iconfont icon-shijian"></i>
                  最新上报时间 : {{ (item.uptime * 1000) | formatTime }}
                </p>
                <p :title="item.address">
                  <i class="iconfont icon-dizhi"></i>
                  地址 : {{ (item.address || "无") | ellipsis }}
                </p>
                <p v-if="userType == 1">
                  <i class="iconfont icon-chouchongbug"></i>
                  识别 :
                  <el-select
                    @change="operationDiscern($event, item.imei, item.disable)"
                    class="my-el-select"
                    style="width: 100px; border: 0; font-size: 15px"
                    size="mini"
                    v-model="item.insectVal"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="itemA in insectOptions"
                      :key="itemA.value"
                      :label="itemA.label"
                      :value="itemA.value"
                    >
                    </el-option>
                  </el-select>
                </p>
                <p class="btns" style="width: 367px">
                  <i class="iconfont icon-yemiancaozuo"></i>
                  <el-button
                    v-btnRight:seePicture="$route.path"
                    size="mini"
                    type="info"
                    @click="
                      viewPhotoDialog(
                        item.imei,
                        item.d_id,
                        item.device_name,
                        item.address
                      )
                    "
                    >查看图片</el-button
                  >
                  <el-button
                    v-btnRight:deviceControl="$route.path"
                    size="mini"
                    type="warning"
                    @click="
                      EquipControl(item.d_id, item.imei, item.device_name)
                    "
                    >设备控制</el-button
                  >
                  <el-button
                    v-btnRight:pestStatistics="$route.path"
                    size="mini"
                    type="success"
                    @click="
                      showTimeControlDialog(item.d_id, item.imei, item.disable)
                    "
                    >害虫统计</el-button
                  >
                  <el-button
                    v-btnRight:dataDetails="$route.path"
                    size="mini"
                    type="danger"
                    @click="dataDetails(item.imei, item.d_id, item)"
                    >数据详情</el-button
                  >
                  <!-- <el-button
                    v-show="userType == 1"
                    v-btnRight:dataDetails="$route.path"
                    :type="item.disable == '0' ? 'warning' : 'danger'"
                    size="mini"
                    @click="operationDiscern(item.id, item.disable)"
                    >{{
                      item.disable == "0" ? "开启识别" : "关闭识别"
                    }}</el-button
                  > -->
                </p>
              </div>
            </equip-item>
          </el-card>
        </el-col>
      </el-row>
    </template>
    <template v-if="displayType == 2">
      <el-card class="box-card">
        <el-table
          v-loading="loading"
          :data="equipList"
          stripe
          style="width: 100%"
        >
          <el-table-column prop="device_name" label="设备名称" width="180">
            <template slot-scope="scope">{{
              scope.row.device_name == "" ? "无" : scope.row.device_name
            }}</template>
          </el-table-column>
          <el-table-column prop="device_id" label="设备ID" width="180">
            <template slot-scope="scope">{{ scope.row.imei }}</template>
          </el-table-column>
          <el-table-column prop="device_status" label="在线状态">
            <template slot-scope="scope">
              <p style="color: #17bb89" v-if="scope.row.is_online == 1">在线</p>
              <p style="color: #eb6765" v-if="scope.row.is_online == 0">离线</p>
            </template>
          </el-table-column>
          <el-table-column prop="dtype" label="组织">
            <template slot-scope="scope">
              <span v-if="scope.row.org_list.length == 1">{{
                scope.row.org_list[0].org_name
              }}</span>
              <el-popover
                ref="popover"
                placement="right"
                title="组织列表"
                width="150"
                trigger="hover"
                v-else
              >
                <div class="popover-content" v-html="content"></div>
                <span @mouseover="orglisthover(scope.row)" slot="reference"
                  >{{ scope.row.org_list[0].org_name }}...</span
                >
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="status_time" label="最新上报时间">
            <template slot-scope="scope">{{
              (scope.row.uptime * 1000) | formatTime
            }}</template>
          </el-table-column>
          <el-table-column prop="address" label="地址">
            <template slot-scope="scope" :title="scope.row.address">{{
              scope.row.address || "无" | ellipsis
            }}</template>
          </el-table-column>
          <el-table-column label="操作" width="400">
            <template slot-scope="scope">
              <el-button
                v-btnRight:seePicture="$route.path"
                size="mini"
                type="info"
                @click="
                  viewPhotoDialog(
                    scope.row.imei,
                    scope.row.d_id,
                    scope.row.device_name,
                    scope.row.address
                  )
                "
                >查看图片</el-button
              >
              <el-button
                v-btnRight:deviceControl="$route.path"
                size="mini"
                type="warning"
                @click="
                  EquipControl(
                    scope.row.d_id,
                    scope.row.imei,
                    scope.row.device_name
                  )
                "
                >设备控制</el-button
              >
              <el-button
                v-btnRight:pestStatistics="$route.path"
                size="mini"
                type="success"
                @click="
                  showTimeControlDialog(
                    scope.row.d_id,
                    scope.row.imei,
                    scope.row.disable
                  )
                "
                >害虫统计</el-button
              >
              <!-- <el-button
                v-btnRight:dataDetails="$route.path"
                size="mini"
                type="danger"
                @click="dataDetails(scope.row.imei, scope.row.d_id, scop.row)"
                >数据详情</el-button
              > -->
              <el-button
                v-btnRight:dataDetails="$route.path"
                size="mini"
                type="danger"
                @click="dataDetails(scope.row.imei, scope.row.d_id, scope.row)"
                >数据详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </template>
    <!-- 暂无数据 -->
    <div
      class="expertDiagnosis_referral_units_not"
      v-if="equipList.length <= 0 && displayType == 1"
    >
      <img
        :src="$imghost + zanwu"
        alt
        class="expertDiagnosis_referral_units_notImg"
      />
    </div>
    <el-pagination
      v-if="equipList.length > 0"
      background
      :page-size="8"
      layout="prev, pager, next, jumper"
      :total="totalNum"
      :current-page="queryInfo.page"
      @current-change="changePage"
    ></el-pagination>
    <!-- 设备控制对话框 -->
    <el-dialog
      title="设备控制"
      :visible.sync="equipControlDialogVisible"
      @close="resetEquipControlDialogClosed"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="handAddForm">
        <el-form
          ref="equipContrlRef"
          :model="equipContrlForm"
          label-position="right"
          label-width="150px"
        >
          <el-form-item label="设备编号:">
            <el-input disabled v-model="equipInfo.device_id"></el-input>
          </el-form-item>
          <el-form-item label="设备名称:" v-if="equipInfo.device_name">
            <el-input disabled v-model="equipInfo.device_name"></el-input>
          </el-form-item>
          <el-form-item label="设备开关：" prop="ds">
            <el-select v-model="equipContrlForm.ds">
              <el-option label="开机" :value="1"></el-option>
              <el-option label="关机" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="工作状态:" prop="ws">
						<el-select
							v-model="ws"
							placeholder="请选择工作状态"
							@change="wsChange()"
						>
							<el-option label="待机" :value="0"></el-option>
							<el-option label="工作" :value="1"></el-option>
						</el-select>
					</el-form-item> -->
          <el-form-item label="定时模式:" prop="ts">
            <el-select
              v-model="equipContrlForm.ts"
              placeholder="请选择定时模式"
            >
              <el-option label="光控" :value="0"></el-option>
              <el-option label="时控" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="equipContrlForm.ts == 1" label="开始结束时间:">
            <el-col :span="11">
              <el-time-select
                placeholder="起始时间"
                v-model="equipContrlForm.st"
                :picker-options="{
                  start: '00:00',
                  step: '01:00',
                  end: '23:00',
                }"
              ></el-time-select>
            </el-col>
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-select
                placeholder="结束时间"
                v-model="equipContrlForm.et"
                :picker-options="{
                  start: '00:00',
                  step: '01:00',
                  end: '23:00',
                }"
              ></el-time-select>
            </el-col>
          </el-form-item>
          <el-form-item
            v-if="equipContrlForm.ts != 1"
            label="定时时长(h):"
            prop="tt"
          >
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.tt"
                  show-input
                  :min="1"
                  :max="10"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="落虫时间(min):" prop="collt">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.collt"
                  show-input
                  :min="1"
                  :max="20"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="加热时间(min):" prop="htim">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.htim"
                  show-input
                  :min="1"
                  :max="20"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="加热温度(℃):" prop="hst">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.hst"
                  show-input
                  :min="75"
                  :max="120"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="高温保护阈值(℃):" prop="tph">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.tph"
                  show-input
                  :min="50"
                  :max="70"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="低温保护阈值(℃):" prop="tpl">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.tpl"
                  show-input
                  :min="-20"
                  :max="10"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="数据上传间隔(min):" prop="datt">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.datt"
                  :step="10"
                  show-input
                  :min="10"
                  :max="60"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <!-- <el-form-item label="图片分辨率:" prop="imgres">
						<el-select
							v-model="equipContrlForm.imgres"
							placeholder="请选择图片分辨率"
						>
							<el-option label="高" :value="0"></el-option>
							<el-option label="中" :value="1"></el-option>
							<el-option label="低" :value="2"></el-option>
						</el-select>
					</el-form-item> -->
          <el-form-item class="handAddFormBtn">
            <el-button type="primary" size="mini" @click="equipControlSubm()"
              >确定</el-button
            >
            <el-button size="mini" @click="equipControlDialogVisible = false"
              >取消</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- 管理员操作弹框 -->
    <el-dialog
      title="测报灯设置"
      :visible.sync="operationDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="设备名称" prop="device_name">
            <el-input v-model="ruleForm.device_name"></el-input>
          </el-form-item>
          <el-form-item label="隶属海关" prop="org_id">
            <el-cascader
              :change-on-select="true"
              v-model="ruleForm.org_id"
              :options="versionsoptions"
              :props="defaultParams"
              :clearable="true"
              placeholder="请选择隶属海关"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="所在监测点" prop="point_id">
            <el-select
              v-model="ruleForm.point_id"
              placeholder="请选择所在监测点"
            >
              <el-option
                v-for="item in traponsoptions"
                :label="item.point_name"
                :value="item.point_id"
                :key="item.point_id"
              ></el-option>
            </el-select>
          </el-form-item>
          <div class="addtrapbox" style="display: flex">
            <el-form-item label="所在纬度" prop="lng">
              <el-input v-model="ruleForm.lng"></el-input>
              <p style="height: 24px; padding-left: 16px">
                {{ ToDegrees(ruleForm.lng, "lng") }}
              </p>
            </el-form-item>
            <el-form-item label="所在纬度" prop="lat">
              <el-input v-model="ruleForm.lat"></el-input>
              <p style="height: 24px; padding-left: 16px">
                {{ ToDegrees(ruleForm.lat, "lat") }}
              </p>
            </el-form-item>
          </div>
          <div class="buttonbox">
            <el-button type="info" size="mini" @click="dingwei"
              >地图选点</el-button
            >
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      class="map_dialog"
      title="地图选点"
      :visible.sync="addLocationDialogVisible"
      width="820px"
      @closed="addLocationDialogClosed"
    >
      <el-form
        :inline="true"
        :model="locationForm"
        class="demo-form-inline"
        size="mini"
      >
        <el-form-item label="经度">
          <el-input clearable v-model="locationForm.lng"></el-input>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input clearable v-model="locationForm.lat"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="locationSearch"
            >定位</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-input
            placeholder="请输入地区检索"
            v-model="addr"
            clearable
            @change="addrChange()"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="amap-demo" id="mapContainer2" style="height: 400px"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addLocationDialogVisible = false" size="mini"
          >取 消</el-button
        >
        <el-button type="primary" @click="addLocationSubm" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import SearchBar from "@/components/SearchBar";
// import TopModule from "@/components/TopModule";
import EquipItem from "@/components/EquipItem";
import Circulation from "../../../../static/js/equipState_dict.json";
import { isArray } from "highcharts";

export default {
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 15) {
        return value.slice(0, 15) + "...";
      }
      return value;
    },
  },
  data() {
    return {
      // 测试父传子传值
      // routerName: '虫情测报',

      zanwu: "/images/expertDiagnosis/zanwu.png",
      //图表和表格切换
      displayType: "",
      //设备列表
      equipList: [],
      dverGather: [
        { label: "全部", value: "" },
        { label: "版本1", value: "1" },
        { label: "版本2", value: "2" },
        { label: "版本3", value: "3" },
        { label: "版本4", value: "4" },
        { label: "版本5", value: "5" },
      ],
      userList: [
        { label: "用户1", value: "用户1" },
        { label: "用户2", value: "用户2" },
      ],
      d_id: "",
      device_id: "",
      ws: 0, //工作模式
      equipInfo: {
        //设备控制回显
        device_id: "",
        device_name: "",
      },
      equipContrlForm: {
        st: "",
        et: "",
        ts: 0,
        tt: null,
        collt: null,
        htim: null,
        hst: null,
        tph: null,
        // tpl: null,
        tpl: 0,
        datt: null,
        ds: 1,
        // tt: "null",
        // collt: "null",
        // htim: "null",
        // hst: 'null',
        // tph: 'null',
        // tpl: 'null',
        // datt: 'null',
        // ds: '1',
        // imgres: 0,
      },
      //参数
      queryInfo: {
        page: 1,
        is_online: null,
        dver: null,
        selectUser: "",
        f_id: "",
        ename: "",
      },
      totalNum: 0,
      //设备控制对话框
      equipControlDialogVisible: false,
      operationDialogVisible: false,
      mqttDialogVisible: false,
      mqttConfig: {
        muid: "",
        mpwd: "",
        mip: "",
        mport: "",
        mpub: "",
        msub: "",
        fuid: "",
        fpwd: "",
        fip: "",
        fport: "",
      },
      loading: true,
      equipStateDict: {}, //

      // 管理员操作 - 更换imei
      replaceImeiData: "",

      // 开始关闭识别
      typeOperation: "", //按钮类型

      // 识别功能筛选  - 仅限管理员可操作
      insectVal: "",
      insectOptions: [
        {
          value: 0,
          label: "禁用",
        },
        {
          value: 1,
          label: "识别",
        },
        {
          value: 2,
          label: "计数",
        },
      ],
      versionsoptions: [], //组织
      traponsoptions: [], //监测点
      defaultParams: {
        label: "org_name",
        value: "id",
        children: "childrens",
        multiple: true,
        checkStrictly: true,
      },
      ruleForm: {
        // org_name:"",
        device_name: "",
        org_id: [],
        point_id: "",
        lng: "",
        lat: "",
        device_name: "",
        device_id: "",
      },
      rules: {
        device_name: [
          { required: true, message: "请输入设备名称", trigger: "blur" },
        ],
        lng: [{ required: true, message: "请输入经度", trigger: "blur" }],
        lat: [{ required: true, message: "请输入纬度", trigger: "blur" }],
        org_id: [
          { required: true, message: "请选择隶属海关", trigger: "change" },
        ],
        point_id: [
          { required: true, message: "请选择所在监测点", trigger: "change" },
        ],
      },
      //地图属性
      addLocationDialogVisible: false,
      locationForm: {
        lng: "",
        lat: "",
      },
      addr: "", //搜索栏地址
      address: "", //地图上标签地址
      center: [114.05, 22.55],
      content: "",
    };
  },
  created() {
    console.log("created");
    this.displayType = String(localStorage.getItem("cbdListType") || "1");
  },
  mounted() {
    this.equipStateDict = Circulation;
    if (this.$route.query.id !== undefined) {
      this.queryInfo.f_id = this.$route.query.id;
      this.$refs.screenData.searchVal = this.$route.query.id;
    }
    console.log("mounted");
    this.getEquipList();
    this.getmon();
  },
  activated() {
    this.getEquipList();
    console.log("cbd_activated");
  },
  deactivated() {
    console.log("cbd_deactivated");
  },
  computed: {
    userType: function () {
      //获取用户类型
      return sessionStorage.getItem("myuser_type");
    },
  },
  methods: {
    getIsOnline(data) {
      this.queryInfo.is_online = data;
      this.queryInfo.page = 1;
      this.getEquipList();
    },
    getIDName(data) {
      this.queryInfo.f_id = data.f_id;
      this.queryInfo.ename = data.ename;
      this.queryInfo.page = 1;
      this.getEquipList();
    },
    getDisplayType(data) {
      this.displayType = String(data);
      localStorage.setItem("cbdListType", data);
    },
    //获取设备列表
    getEquipList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=monitor_manage.cbd_manage.cbd_list",
        data: this.qs.stringify({
          device_type_id: 3,
          page_size: 8,
          page: this.queryInfo.page,
          device_status: this.queryInfo.is_online,
          device_name: this.queryInfo.ename,
          device_id: this.queryInfo.f_id,
          dver_num: this.queryInfo.dver,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.equipList = res.data.data.data;
          // insectVal
          for (var i = 0; i < this.equipList.length; i++) {
            if (this.equipList[i].disable == 0) {
              // 禁用
              this.equipList[i].insectVal = "禁用";
            } else if (this.equipList[i].disable == 1) {
              // 识别
              this.equipList[i].insectVal = "识别";
            } else if (this.equipList[i].disable == 2) {
              // 计数
              this.equipList[i].insectVal = "计数";
            }
          }
          this.equipList.insectVal = this.totalNum = res.data.data.counts;
          this.loading = false;
        }
        // console.log(res.data.data.data)
        var data = res.data.data.data;
        for (var i = 0; i < data.length; i++) {
          if (data[i].disable == "2") {
            console.log(data[i].imei + "这是计数");
          } else if (data[i].disable == "1") {
            console.log(data[i].imei + "这是带识别的");
          }
        }
      });
    },
    //改变page
    changePage(val) {
      this.queryInfo.page = val;
      this.getEquipList();
    },
    // 数据详情
    dataDetails(e_id, d_id, data) {
      this.device_id = e_id;
      this.$router.push({
        path: `/index/DataDetails/${e_id}/${d_id}`,
        query: {
          addr: data.address,
          name: data.device_name,
        },
      });
    },
    // 查看图片
    viewPhotoDialog(id, d_id, name, addr) {
      this.device_id = id;
      this.$router.push({
        path: `/index/DataPhotos/${id}`,
        query: { d_id: d_id, name: name, addr: addr },
      });
    },
    //设备控制
    EquipControl(d_id, device_id, device_name) {
      this.d_id = d_id;
      this.equipInfo = { device_id, device_name };
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=monitor_manage.cbd_manage.cbd_control_info",
        data: this.qs.stringify({ d_id, cmd: "paramconf" }),
      }).then((res) => {
        if (res.data.data && Object.keys(res.data.data).length > 0) {
          let data = res.data.data;
          data.ds = Number(data.ds);
          data.st =
            data.st && data.st < 10 ? "0" + data.st + ":00" : data.st + ":00";
          data.et =
            data.et && data.et < 10 ? "0" + data.et + ":00" : data.et + ":00";
          // this.equipContrlForm = data;
          // console.log(data)
          var obj = {};
          console.log(data);
          console.log(data.ds);
          for (let kay in data) {
            if (typeof data[kay] == "string" && kay !== "st" && kay !== "et") {
              var a = data[kay];
              if (Number(a) < 0) {
                obj[kay] = Number(data[kay]);
              } else if (Number(a) >= 0) {
                obj[kay] = parseInt(data[kay]);
              }
            } else {
              obj[kay] = data[kay];
            }
          }
          // this.equipContrlForm = data;
          console.log(obj);
          this.equipContrlForm = obj;
        }
        this.equipControlDialogVisible = true;
      });
    },
    //设备控制提交
    equipControlSubm() {
      let newForm = Object.assign({}, this.equipContrlForm); //深拷贝
      newForm.st = newForm.st + "";
      newForm.et = newForm.et + "";
      newForm.st && newForm.st.slice(0, 2).charAt(0) != "0"
        ? newForm.st.slice(0, 2)
        : newForm.st.slice(1, 2);
      newForm.et =
        newForm.et && newForm.et.slice(0, 2).charAt(0) != "0"
          ? newForm.et.slice(0, 2)
          : newForm.et.slice(1, 2);
      console.log(newForm);

      for (let k in newForm) {
        if (typeof newForm[k] == "number") {
          newForm[k] = newForm[k] + "";
        }
      }
      newForm.st = newForm.st.replace(":00", "");
      this.$delete(newForm, "admin");

      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=monitor_manage.cbd_manage.cbd_device_control",
        data: this.qs.stringify({
          d_id: this.d_id,
          config: JSON.stringify(newForm),
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.$message.success("设备控制修改成功");
        } else {
          his.$message.error("设备控制修改失败");
        }
        this.equipControlDialogVisible = false;
      });
    },
    resetEquipControlDialogClosed() {
      this.$refs.equipContrlRef.resetFields();
      this.ws = 0;
    },
    //害虫统计
    showTimeControlDialog(d_id, id, disable) {
      this.device_id = id;
      if (sessionStorage.getItem("myuser_type") == 1) {
        // 管理员
        this.$router.push({
          path: `/index/pestsStats/${d_id}/${id}`,
          query: { disable: disable },
        });
      } else {
        // 非管理员
        if (disable == 2) {
          // 计数
          this.$router.push({
            path: `/index/PestsStatsNumber/${d_id}/${id}`,
            query: { disable: disable },
          });
        } else if (disable == 1 || disable == 0) {
          // 识别开启或关闭
          this.$router.push({
            path: `/index/pestsStats/${d_id}/${id}`,
            query: { disable: disable },
          });
        }
      }
    },
    //设备控制->工作模式切换
    wsChange() {
      this.$confirm("确定修改工作模式?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=monitor_manage.cbd_manage.cbd_device_control",
            data: this.qs.stringify({
              device_type_id: 3,
              d_id: this.d_id,
              work_type: this.ws,
            }),
          }).then((res) => {
            if (res.data.message == "") {
              this.$message({
                type: "success",
                message: "修改成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
        });
    },
    equipOperation(item) {
      console.log(item);
      this.ruleForm.device_id = item.imei;
      this.ruleForm.device_name = item.device_name;
      this.ruleForm.lng = item.lng;
      this.ruleForm.lat = item.lat;
      this.ruleForm.point_id = item.point_id;

      this.d_id = item.d_id;
      this.equipInfo = {
        device_id: item.device_id,
        device_name: item.device_name,
      };
      this.operationDialogVisible = true;

      // for (var key in this.ruleForm) {
      //   this.ruleForm[key] = e[key];
      // }
      this.ruleForm.org_id = [];
      for (var i = 0; i < item.org_list.length; i++) {
        var arr = [item.org_list[i].org_id];
        this.ruleForm.org_id.push(arr);
      }
      if (item.superior_org_list.length != 0) {
        var data = item.superior_org_list;
        for (var i = 0; i < data.length; i++) {
          // console.log(data[i])
          if (data[i].superior_org.length > 1) {
            var data2 = data[i].superior_org;
            // console.log(data2)
            for (var j = 0; j < data2.length; j++) {
              // console.log(data2[j])
              this.ruleForm.org_id[i].unshift(data2[j].org_id);
            }
          } else {
            if (data[i].superior_org.length != 0) {
              this.ruleForm.org_id[i].unshift(data[i].superior_org[0].org_id);
            }
          }
        }
      }
      console.log(this.ruleForm);
    },
    // equipBtnControl(cmd) {
    //   let loading = this.$loading({
    //     lock: true,
    //     text: "Loading",
    //     spinner: "el-icon-loading",
    //     background: "rgba(0, 0, 0, 0.7)",
    //   });
    //   if (cmd == "dtu_update") {
    //     var name = "联网模块升级";
    //   } else if (cmd == "dtu_reboot") {
    //     var name = "联网模块重启";
    //   } else if (cmd == "takephoto") {
    //     var name = "拍照";
    //   } else if (cmd == "update") {
    //     var name = "强制升级";
    //   } else if (cmd == "reboot") {
    //     var name = "强制重启";
    //   } else if (cmd == "open_shake") {
    //     var name = "强制震动开启";
    //   } else if (cmd == "close_shake") {
    //     var name = "强制震动关闭";
    //   } else if (cmd == "yfwlw") {
    //     var name = "平台切换";
    //   } else if (cmd == "imei") {
    //     var name = "修改设备号";
    //   }

    //   this.$confirm("此操作对设备进行" + name + ", 是否继续?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(() => {
    //       this.$axios({
    //         method: "POST",
    //         url: "/api/api_gateway?method=forecast.send_control.admin_device_control",
    //         data: this.qs.stringify({
    //           cmd,
    //           device_type_id: 3,
    //           d_id: this.d_id,
    //           imei: this.replaceImeiData, // 更换imei
    //         }),
    //       }).then((res) => {
    //         if (res.data.message == "") {
    //           this.$message.success("指令下发成功!");
    //         }
    //         loading.close();
    //       });
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: "info",
    //         message: name + "已取消",
    //         duration: 1500,
    //       });
    //       loading.close();
    //     });
    // },

    // 设备版本、用户筛选
    searchChange() {
      console.log(this.queryInfo.selectUser);
      this.getEquipList();
    },
    mqttControl() {
      this.mqttDialogVisible = true;
    },
    mqttDialogClosed() {
      this.$refs.mqttConfigRef.resetFields();
    },
    mqttSubm() {
      this.$refs.mqttConfigRef.validate((valid) => {
        console.log(valid);
        if (!valid) {
          return false;
        }
        let obj = {
          mqtt: {
            uid: this.mqttConfig.muid,
            pwd: this.mqttConfig.mpwd,
            ip: this.mqttConfig.mip,
            port: this.mqttConfig.mport,
            pub: this.mqttConfig.mpub,
            sub: this.mqttConfig.msub,
            keepalive: 60,
            lastwill: "/yfkj/cbd/offline/",
          },
          ftp: {
            uid: this.mqttConfig.fuid,
            pwd: this.mqttConfig.fpwd,
            ip: this.mqttConfig.fip,
            port: this.mqttConfig.fport,
          },
        };

        this.$confirm("此操作将上传修改的MQTT配置, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=monitor_manage.cbd_manage.cbd_device_control",
              data: this.qs.stringify({
                device_type_id: 3,
                d_id: this.d_id,
                cmd: "setnet",
                config: JSON.stringify(obj),
              }),
            }).then((res) => {
              if (res.data.message == "") {
                this.$message.success("提交成功");
              } else {
                this.$message.error("提交失败");
              }
            });
            this.mqttDialogVisible = false;
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
              duration: 1500,
            });
          });
      });
    },
    mqttInfo() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=monitor_manage.cbd_manage.cbd_control_info",
        data: this.qs.stringify({
          d_id: this.d_id,
          cmd: "netconf",
        }),
      }).then((res) => {
        if (res.data.message == "") {
          let { ftp, mqtt } = res.data.data;
          console.log(ftp, mqtt);
          this.mqttConfig = {
            muid: mqtt.uid,
            mpwd: mqtt.pwd,
            mip: mqtt.ip,
            mport: mqtt.port,
            mpub: mqtt.pub,
            msub: mqtt.sub,
            fuid: ftp.uid,
            fpwd: ftp.pwd,
            fip: ftp.ip,
            fport: ftp.port,
          };
        }
      });
      this.mqttDialogVisible = true;
    },
    pestAll() {
      this.$router.push("/index/tongji");
    },
    devicePlant() {
      this.$router.push("/index/deviceTongji");
    },
    // 修改设备号 - 更换imei
    replaceImei() {
      console.log(this.d_id);
      this.$prompt("请输入imei", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          this.replaceImeiData = value;
          // this.equipBtnControl("imei");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },

    // 管理员操作 - 升级文件更新
    fileUploadSectionFile(param) {
      let that = this;
      let formData = new FormData();
      formData.append("fileName", param.file);
      that
        .$axios({
          method: "POST",
          url: "api/update/save_file",
          data: formData,
        })
        .then((res) => {
          console.log(res);
          if (res.data == "OK" || res.data == "OK!") {
            this.$message({
              message: "文件上传成功",
              type: "success",
              duration: 1500,
            });
          } else {
            this.$message({
              message: res.data,
              type: "warning",
              duration: 1500,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 管理员操作 - 开启关闭识别
    operationDiscern(val, id, operation) {
      if (val == 0) {
        // 当前处于识别关闭状态
        this.$confirm("确认关闭识别状态？")
          .then((_) => {
            this.operationDiscernAxios(id, "disable");
          })
          .catch((_) => {});
      } else if (val == 1) {
        // 当前处于识别开启状态
        this.$confirm("确认开启识别状态？")
          .then((_) => {
            this.operationDiscernAxios(id, "enable");
          })
          .catch((_) => {});
      } else if (val == 2) {
        // 当前处于识别开启状态
        this.$confirm("确认开启计数状态？")
          .then((_) => {
            this.operationDiscernAxios(id, "count");
          })
          .catch((_) => {});
      }
    },
    operationDiscernAxios(id, req) {
      // ret=disable时禁用识别功能, ret=enable,时启用识别统计功能， ret =count 计数功能
      var that = this;
      that
        .$axios({
          method: "post",
          url: "/api/api_gateway?method=monitor_manage.cbd_manage.disable_cbd_discern",
          data: that.qs.stringify({
            device_id: id, // 设备号
            ret: req, // ret=disable时禁用识别功能, ret=enable,时启用识别统计功能
          }),
        })
        .then((res) => {
          if (res.data.data == true) {
            that.getEquipList(); //图片列表数据请求
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("操作失败，请重试！");
        });
    },
    submitForm(formName) {
      // console.log(isArray(this.ruleForm.org_id));
      var org_id=[];
      // if (Array.isArray(this.ruleForm.org_id)) {
      //   org_id = this.ruleForm.org_id[this.ruleForm.org_id.length - 1];
      // } else {
      //   org_id = this.ruleForm.org_id;
      // }
      if (Array.isArray(this.ruleForm.org_id)) {
        for (var i = 0; i < this.ruleForm.org_id.length; i++) {
          org_id.push(
            this.ruleForm.org_id[i][this.ruleForm.org_id[i].length - 1]
          );
        }
        // org_id = this.ruleForm.org_id[this.ruleForm.org_id.length - 1];
      } else {
        org_id = this.ruleForm.org_id;
      }
      org_id = org_id.join("/");
      console.log(this.ruleForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=monitor_manage.cbd_manage.add_device_info",
            data: this.qs.stringify({
              org_id: org_id, //                  非必传(num)                诱捕器id 修改项
              point_id: this.ruleForm.point_id, //               必传(string)               设备编号
              lat: this.ToDigital(this.ruleForm.lat), //                       必传(string)               纬度
              lng: this.ToDigital(this.ruleForm.lng), //
              device_id: this.ruleForm.device_id,
              device_name: this.ruleForm.device_name,
            }),
          }).then((res) => {
            console.log(res);
            if (res.data.data) {
              // var message = "";
              // if (this.parameter == "add") {
              //   // console.log(this.$data.addtitle)
              //   message = "添加成功！";
              // } else if (this.parameter == "modify") {
              //   message = "修改成功！";
              // }
              this.$message({
                showClose: true,
                message: "修改成功！",
                type: "success",
              });
              this.operationDialogVisible = false;
              this.getEquipList();
            } else {
              this.$message({
                showClose: true,
                message: "添加失败" + res.data.message,
                type: "warning",
              });
            }
          });
        } else {
          this.$message({
            message: "请将信息填写完全",
            type: "warning",
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.operationDialogVisible = false;
      this.$refs[formName].resetFields();
      for (var key in this.ruleForm) {
        this.ruleForm[key] = "";
      }
    },
    getmon() {
      //获取监测点列表 组织列表
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.org_list",
      }).then((res) => {
        console.log(res.data.data);
        this.versionsoptions = res.data.data.page_list; //组织
        this.traponsoptions = res.data.data.point_data;
        this.inducer_data = res.data.data.inducer_data;
      });
    },
    init() {
      console.log(document.getElementById("mapContainer2"));
      var map = new AMap.Map("mapContainer2", {
        center: this.center,
        resizeEnable: true,
        zoom: 10,
        lang: "en",
      });
      AMap.plugin(["AMap.ToolBar", "AMap.Geocoder"], () => {
        map.addControl(new AMap.ToolBar());
        this.geocoder = new AMap.Geocoder({
          city: "全国",
          radius: 1000,
        });
      });
      setTimeout(() => {
        var marker = new AMap.Marker({
          position: this.center,
        });
        console.log(this.center);
        marker.setMap(map);
      }, 1000);
      this.map = map;
      this.testevent();
    },
    addrChange() {
      //位置搜索
      var marker = new AMap.Marker();
      this.geocoder.getLocation(this.addr, (status, result) => {
        if (status === "complete" && result.geocodes.length) {
          var lnglat = result.geocodes[0].location;
          marker.setPosition(lnglat);
          this.map.add(marker);
          this.map.setFitView(marker);
          this.locationForm = {
            lat: lnglat.lat,
            lng: lnglat.lng,
          };
        } else {
          this.$message.error("根据地址查询位置失败");
        }
      });
    },
    // 地图点击事件
    testevent() {
      this.map.on("click", (ev) => {
        var lnglat = [ev.lnglat.lng, ev.lnglat.lat];
        this.locationForm = { lng: lnglat[0], lat: lnglat[1] };
        this.map.clearMap();
        var marker = new AMap.Marker({
          position: lnglat,
        });
        marker.setMap(this.map);
        this.getAddress(lnglat);
        setTimeout(() => {
          new AMap.InfoWindow({
            content: "<h5>" + "当前选中地址" + "</h5>" + this.address,
            offset: new AMap.Pixel(0, -32),
          }).open(this.map, lnglat);
        }, 100);
      });
    },
    getAddress(lnglat) {
      AMap.plugin("AMap.Geocoder", () => {
        this.geocoder.getAddress(lnglat, (status, result) => {
          if (status === "complete" && result.info === "OK") {
            this.address = result.regeocode.formattedAddress;
          }
        });
      });
    },
    addLocationSubm() {
      //点击确定
      this.ruleForm.lng = this.locationForm.lng;
      this.ruleForm.lat = this.locationForm.lat;
      console.log(this.ruleForm)
      this.addLocationDialogVisible = false;
    },
    addLocationDialogClosed() {
      //弹框关闭时
      this.locationForm = { lat: "", lng: "" };
      this.center = [];
      this.map = null;
    },
    locationSearch() {
      if (this.locationForm.lat && this.locationForm.lng) {
        let lnglat = [this.locationForm.lng, this.locationForm.lat];
        var marker = new AMap.Marker({
          position: lnglat,
        });
        marker.setMap(this.map);
      } else {
        this.$message.warning("请输入经纬度！");
        // return fasle;
      }
    },
    dingwei() {
      if (this.ruleForm.lng != "" && this.ruleForm.lng != 0) {
        this.center[0] = this.ruleForm.lng;
      }
      if (this.ruleForm.lat != "" && this.ruleForm.lat != 0) {
        this.center[1] = this.ruleForm.lat;
      }
      this.addLocationDialogVisible = true;
      setTimeout(() => {
        this.init();
      }, 500);
    },
    //度转度°分′秒″
    ToDegrees(val, type) {
      if (typeof val == "undefined" || val == "" || isNaN(val)) {
        return val;
      }
      val = val.toString();
      var A = "";
      if (type == "lng") {
        A = val > 0 ? "E" : "W";
      } else if (type == "lat") {
        A = val > 0 ? "N" : "S";
      }
      var i = val.indexOf(".");
      var strDu = i < 0 ? val : val.substring(0, i); //获取度
      var strFen = 0;
      var strMiao = 0;
      if (i > 0) {
        var strFen = "0" + val.substring(i);
        strFen = strFen * 60 + "";
        i = strFen.indexOf(".");
        if (i > 0) {
          strMiao = "0" + strFen.substring(i);
          strFen = strFen.substring(0, i); //获取分
          strMiao = strMiao * 60 + "";
          i = strMiao.indexOf(".");
          strMiao = strMiao.substring(0, i + 4); //取到小数点后面三位
          strMiao = parseFloat(strMiao).toFixed(2); //精确小数点后面两位
        }
      }
      console.log(strDu, strFen, strMiao);
      return strDu + "°" + strFen + "′" + strMiao + "″" + A;
    },
    //度°分′秒″转度
    ToDigital(lnglat) {
      console.log(lnglat);
      if (!isNaN(lnglat)) {
        return lnglat;
      }
      lnglat = lnglat.toString();
      var strDu, strFen, strMiao;
      var duindex = lnglat.indexOf("°"); //字符度的下标
      var fenindex = lnglat.indexOf("′"); //字符分的下标
      var miaoindex = lnglat.indexOf("″"); //字符秒的下标
      strDu = lnglat.slice(0, duindex);
      strFen = lnglat.slice(duindex + 1, fenindex);
      strMiao = lnglat.slice(fenindex + 1, miaoindex);
      // len = len > 6 || typeof len == "undefined" ? 6 : len; //精确到小数点后最多六位
      strDu =
        typeof strDu == "undefined" || strDu == "" ? 0 : parseFloat(strDu);
      strFen =
        typeof strFen == "undefined" || strFen == ""
          ? 0
          : parseFloat(strFen) / 60;
      strMiao =
        typeof strMiao == "undefined" || strMiao == ""
          ? 0
          : parseFloat(strMiao) / 3600;
      var digital = strDu + strFen + strMiao;
      if (digital == 0) {
        return "";
      } else {
        return digital.toFixed(6);
      }
    },
    orglisthover(e) {
      console.log(e);
      var str = ``;
      for (var i = 0; i < e.org_list.length; i++) {
        str += `<p>` + e.org_list[i].org_name + `</p>`;
      }
      this.content = str;
    },
  },
  components: {
    SearchBar,
    EquipItem,
    // TopModule
  },
};
</script>
<style lang="less" scoped>
// 去除下拉框的边框
.my-el-select /deep/ .el-input .el-input__inner {
  border: 0 !important;
}

.handAddForm {
  /deep/.el-form-item {
    margin-bottom: 8px;
  }
  .handAddFormBtn {
    text-align: right;
  }
}
.sliderParent {
  display: flex;
  .block {
    flex: 1;
    margin-right: 10px;
    /deep/.el-slider__runway,
    /deep/.el-slider__bar {
      height: 10px;
    }
  }
  > span {
    width: 40px;
  }
}
.swi-box {
  text-align: center;
  padding: 10px 0;
  label {
    color: #333;
    margin-right: 8px;
    font-size: 14px;
  }
  i.el-icon-edit {
    margin-right: 8px;
  }
}
.buttonbox {
  margin-bottom: 23px;
  padding-left: 100px;
  /deep/.el-button {
    background-color: #409eff;
    border-color: #409eff;
  }
}

.real-time {
  display: flex;
  justify-content: left;
  align-items: center;
  padding: 20px 0;
  .left {
    margin-right: 10px;
    .icon-box {
      border-radius: 50%;
      width: 46px;
      height: 46px;
      padding: 5px;
      box-sizing: border-box;
      margin-bottom: 3px;
      img {
        width: 100%;
        height: auto;
      }
    }
    .aisle {
      text-align: center;
      font-size: 14px;
      color: #666;
    }
  }
  .right {
    color: #333;
    .num {
      font-weight: 600;
      font-size: 20px;
      margin-bottom: 3px;
    }
    .unit {
      font-size: 14px;
      color: #666;
    }
  }
}
.checkData {
  text-align: right;
  font-size: 14px;
  span {
    cursor: pointer;
  }
}
.red {
  color: rgb(235, 103, 101);
}
.green {
  color: rgb(23, 187, 137);
}
.el-date-editor--time-select {
  width: 100% !important;
}
.el-form .line {
  text-align: center;
}
.el-select {
  width: 100%;
}

.tit {
  font-weight: 800;
  margin: 15px 0 8px 0;
}
.item {
  margin-bottom: 10px;
}

.onlineState {
  margin: 0 3px 0 3px;
}
.onlineState .icon-diannao {
  margin: 0 19px 0 -2px !important;
}
.search-box {
  position: relative;
  .pestAll {
    position: absolute;
    top: 1px;
    // right: 740px;
    left: 225px;
  }
  .devicePlant {
    position: absolute;
    top: 1px;
    // right: 816px;
    left: 140px;
  }
}

// 表格文字居中
/deep/.el-table th > .cell {
  text-align: center;
}

/deep/.el-table .cell {
  text-align: center;
}

// 按钮
.btns {
  /deep/.el-button--mini {
    padding: 6px 8px !important;
  }
  /deep/.el-button--info {
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
  }
}
</style>
