<template>
  <div class="innerMargin">
      <el-card class="box-card">
      <div style="cursor: default">
        <div class="search-box">
          <div class="filter-box">
            <el-select
              size="small"
              v-model="queryInfo.device_type_id"
              clearable
              placeholder="请选择设备类型"
              @change="searchChange()"
            >
              <el-option label="杀虫灯" value="2"></el-option>
              <el-option label="测报灯" value="3"></el-option>
              <el-option label="智能性诱" value="4"></el-option>
              <el-option label="环境监测" value="5"></el-option>
              <el-option label="监控设备" value="6"></el-option>
              <el-option label="孢子仪" value="7"></el-option>
              <el-option label="性诱设备" value="8"></el-option>
              <el-option label="糖醋测报" value="9"></el-option>
              <el-option label="灾害预警" value="1112"></el-option>
            </el-select>
            <el-input
              style="cursor: pointer"
              size="small"
              clearable
              @change="searchChange()"
              placeholder="请输入设备ID"
              v-model="queryInfo.f_id"
            >
              <i slot="suffix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>
          <el-date-picker
            style="cursor: pointer"
            size="small"
            @change="DateChange()"
            v-model="timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </div>
        <el-row :gutter="10">
          <el-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="4"
            v-for="item in dataList"
            :key="item.id"
          >
            <el-card class="box-card pad0">
              <i class="del-icon el-icon-delete" @click="delEquip(item.d_id)"></i>
              <div class="img-box">
                <template v-if="item.device_type_id == '2'">
                  <img src="@/assets/images/equipdistribute/scdIconOn.png" />
                </template>
                <template v-if="item.device_type_id == '3'">
                  <img src="@/assets/images/equipdistribute/cbdIconOn.png" />
                </template>
                <template v-if="item.device_type_id == '4'">
                  <img src="@/assets/images/equipdistribute/znxyOn.png" />
                </template>
                <template v-if="item.device_type_id == '5'">
                  <img src="@/assets/images/equipdistribute/hjjcIconOn.png" />
                </template>
                <template v-if="item.device_type_id == '6'">
                  <img src="@/assets/images/equipdistribute/jkIconOn.png" />
                </template>
                <template v-if="item.device_type_id == '7'">
                  <img src="@/assets/images/equipdistribute/bzyIconOn.png" />
                </template>
                <template v-if="item.device_type_id == '8'">
                  <img src="@/assets/images/equipdistribute/xyOn.png" />
                </template>
                <template v-if="item.device_type_id == '9'">
                  <img src="@/assets/images/equipdistribute/tccbOn.png" />
                </template>
                <template v-if="item.device_type_id == '11'">
                  <img src="@/assets/images/equipdistribute/warnOn11.png" />
                </template>
                <template v-if="item.device_type_id == '12'">
                  <img src="@/assets/images/equipdistribute/warnOn12.png" />
                </template>
                <div class="equipName">
                  <span>
                    {{ item.device_name || "无" }}
                  </span>
                  <span class="editNameIcon" @click="modifyName(item.device_id, item.device_name)">
                    <i class="el-icon-edit-outline"></i>
                  </span>
                </div>
              </div>
              <div class="detail">
                <p>
                  设备ID
                  <span>{{ item.device_id }}</span>
                </p>
                <p>
                  适配用户
                  <span>{{ item.device_user || "无" }}</span>
                </p>
                <p v-if="item.name">
                  设备组名称
                  <span>{{ item.name || "无" }}</span>
                </p>
                <p v-else>
                  设备名称
                  <span>{{ item.device_name || "无" }}</span>
                </p>
                <p>
                  位置
                  <span>{{ item.device_location || "无" }}</span>
                </p>
                <p>
                  设备添加时间
                  <span>{{ (item.creat_time * 1000) | formatTime }}</span>
                </p>
              </div>
              <div class="bottom">
                <span v-if="item.device_type_id == '11' || item.device_type_id == '12'" @click="modifyGroupName(item.device_id, item.device_name)">
                  <i class="el-icon-edit-outline"></i> 修改设备组
                </span>
                <span @click="addPosition(item.device_id, item.lng, item.lat)">
                  <i class="el-icon-location-outline"></i> 添加位置
                </span>
                <span @click="addFault(item.device_id, item.device_type_id)">
                  <i class="el-icon-edit-outline"></i> 故障上报
                </span>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <!-- 暂无数据 -->
        <div class="expertDiagnosis_referral_units_not" v-if="dataList.length <= 0">
          <img
            :src="$imghost + zanwu"
            alt
            class="expertDiagnosis_referral_units_notImg"
          />
        </div>
        <el-pagination
          v-if="dataList.length > 0"
          background
          layout="prev, pager, next, jumper"
          :page-size="12"
          :total="totalNum"
          @current-change="changePage"
        ></el-pagination>
        <!-- 添加定位弹框 -->
        <el-dialog
          class="map_dialog"
          title="添加定位"
          :visible.sync="addLocationDialogVisible"
          width="800px"
          top="180px"
          @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"></div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addLocationDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addLocationSubm">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 故障上报  -->
        <el-dialog
          class="map_dialog"
          title="故障上报"
          v-if="addFaultDialogVisible"
          :visible.sync="addFaultDialogVisible"
          width="500px"
          @closed="addLocationDialogClosed"
        >
          <el-form
            ref="editFaultform"
            :rules="editFaultrules"
            :model="editFault"
            label-width="80px"
          >
            <el-form-item label="设备ID">
              <el-input v-model="editFault.imei" disabled></el-input>
            </el-form-item>
            <el-form-item label="联系人" prop="user">
              <el-input v-model="editFault.user"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="tel">
              <el-input
                type="text"
                maxlength="11"
                v-model="editFault.tel"
              ></el-input>
            </el-form-item>
            <el-form-item label="故障原因" prop="detail">
              <el-input type="textarea" v-model="editFault.detail"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addFaultDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addFaultSubm">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import AMap from "AMap";
export default {
  data() {
    var checkphone = (rule, value, callback) => {
      let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value == "") {
        callback(new Error("请输入手机号"));
      } else if (!phoneReg.test(value)) {
        //引入methods中封装的检查手机格式的方法
        callback(new Error("请输入正确的手机号!"));
      } else {
        callback();
      }
    };
    return {
      zanwu: "/images/expertDiagnosis/zanwu.png",
      timeRange: "",
      queryInfo: {
        f_id: "",
        page: 1,
        device_type_id: null,
        start_time: "",
        end_time: "",
      },
      dataList: [],
      totalNum: 0,
      addr: "",
      locationForm: {
        lat: "",
        lng: "",
      },
      editFault: {
        imei: "",
        user: "",
        tel: "",
        detail: "",
        type: "",
      },
      device_id: "",
      center: [], //默认地图中心
      addLocationDialogVisible: false,
      addFaultDialogVisible: false,
      editFaultrules: {
        user: { required: true, message: "请输入联系人", trigger: "blur" },
        tel: { required: true, validator: checkphone, trigger: "blur" },
        detail: { required: true, message: "请输入故障原因", trigger: "blur" },
      },
      address: "", //地图信息框显示的地址
    };
  },
  mounted() {
    this.getList();
  },
  beforeMount() {},
  methods: {
    init() {
      var map = new AMap.Map("mapContainer2", {
        center: this.center,
        resizeEnable: true,
        zoom: 10,
        lang: "ch",
      });
      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,
        });
        marker.setMap(map);
      },1000);
      this.map = map;
      this.testevent();
    },
    // 地图点击事件
    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;
          }
        });
      });
    },
    //获取设备列表
    getList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=device.device_manage.device_info",
        data: this.qs.stringify({
          device_id: this.queryInfo.f_id,
          page: this.queryInfo.page,
          page_size: 12,
          device_type_id: this.queryInfo.device_type_id,
          start_time: this.queryInfo.start_time,
          end_time: this.queryInfo.end_time,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.dataList = res.data.data.data;
          this.totalNum = res.data.data.counts;
        }
      });
    },
    searchChange() {
      this.queryInfo.page = 1;
      this.getList();
    },
    DateChange(val) {
      this.queryInfo.page = 1;
      if (this.timeRange) {
        this.queryInfo.start_time = parseInt(
          new Date(this.timeRange[0]).getTime() / 1000
        );
        this.queryInfo.end_time = parseInt(
          new Date(this.timeRange[1]).getTime() / 1000
        );
        this.getList();
      } else {
        this.queryInfo.start_time = "";
        this.queryInfo.end_time = "";
        this.getList();
      }
    },

    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("根据地址查询位置失败");
        }
      });
    },
    // 修改设备名称
    modifyName(id, device_name) {
      let value = device_name;
      this.$prompt("", "修改设备名称", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: device_name,
      })
        .then(({ value }) => {
          if (value) {
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=forecast.worm_lamp.revise_device",
              data: this.qs.stringify({
                device_id: id,
                device_name: value,
              }),
            }).then((res) => {
              if (res.data.message == "") {
                this.getList();
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
              }
            });
          } else {
            this.$message({
              type: "info",
              message: "内容不能为空",
            });
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "取消输入",
          // });
        });
    },
    // 修改设备组名称
    modifyGroupName(id, device_name) {
      let value = device_name;
      this.$prompt("", "修改设备组名称", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: device_name,
      })
        .then(({ value }) => {
          if (value) {
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=weather.weather.warning_change",
              data: this.qs.stringify({
                device_id: id,
                name: value,
              }),
            }).then((res) => {
              if (res.data.message == "") {
                this.getList();
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
              }else{
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            });
          } else {
            this.$message({
              type: "info",
              message: "内容不能为空",
            });
          }
        })
        .catch(() => {
        });
    },
    //通过经纬度搜索定位
    locationSearch() {
      if (this.locationForm.lat && this.locationForm.lng) {
        this.map.clearMap();
        let lnglat = [this.locationForm.lng, this.locationForm.lat];
        var marker = new AMap.Marker({
          position: lnglat,
        });
        marker.setMap(this.map);
        this.map.setFitView();
        
      } else {
        this.$message.warning("请输入经纬度！");
        return fasle;
      }
    },
    //点击“添加定位”按钮
    addPosition(device_id, lng, lat) {
      this.device_id = device_id;
      this.center = [lng, lat];
      this.locationForm.lng = lng;
      this.locationForm.lat = lat;
      this.addLocationDialogVisible = true;
      setTimeout(() => {
        this.init();
      }, 0);
    },
    // 故障上报
    addFault(device_id, type) {
      this.device_id = device_id;
      this.editFault.imei = device_id;
      this.editFault.type = type;
      this.addFaultDialogVisible = true;
    },
    changePage(val) {
      console.log(val);
      this.queryInfo.page = val;
      this.getList();
    },
    //关闭定位弹框时调用
    addLocationDialogClosed() {
      this.locationForm = { lat: "", lng: "" };
      this.center = [];
      this.map = null;
    },
    //选择定位点后，提交
    addLocationSubm() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.worm_lamp.revise_device",
        data: this.qs.stringify({
          device_id: this.device_id,
          lat: this.locationForm.lat,
          lng: this.locationForm.lng,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.getList();
          this.addLocationDialogVisible = false;
          this.$message({
            type: "success",
            message: "定位成功",
          });
        } else {
          this.$message({
            type: "error",
            message: "定位失败",
          });
        }
      });
    },
    addFaultSubm() {
      this.$refs.editFaultform.validate((valid) => {
        if (valid) {
          this.$axios({
            method: "POST",
            url:
              "/api/api_gateway?method=after_sale.after_sale_manage.aftersale_apply",
            data: this.qs.stringify({
              device_id: this.device_id,
              errordesc: this.editFault.detail,
              errorimg: [],
              addr: "",
              user: this.editFault.user,
              userphone: this.editFault.tel,
              repairtime: "",
              d_type: this.editFault.type,
              is_pc: "1", //0 手机  1 电脑
              errorvideo: "",
            }),
          }).then((res) => {
            if (res.data.message == "") {
              this.$message({
                type: "success",
                message: "修改成功",
              });
              this.addFaultDialogVisible = false;
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    //删除设备
    delEquip(d_id) {
      this.$confirm("确定删除此设备么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=device.device_manage.delete_device",
            data: this.qs.stringify({
              d_id,
            }),
          }).then((res) => {
            if (res.data.message == "") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang='less' scoped>
.search-box {
  display: flex;
  justify-content: flex-left;
  justify-content: space-between;
  margin-bottom: 10px;
  .filter-box > div {
    margin-right: 15px;
  }
  .el-input {
    width: 200px;
  }
  .el-date-editor--daterange {
    width: 222px;
  }
}
.el-card.selected {
  border: 1px solid #14a478;
}
.el-card.pad0 {
  position: relative;
  .del-icon {
    display: none;
    font-size: 16px;
    position: absolute;
    right: 10px;
    top: 10px;
    color: red;
    cursor: pointer;
  }
  &:hover {
    .del-icon,.editNameIcon {
      display: inline-block;
    }
  }
  .editNameIcon{
    display: none;
  }
  .img-box {
    text-align: center;
    border-bottom: 1px solid #e1e1e1;
    padding: 20px 0;
    img {
      height: 55px;
    }
    .equipName{
      height: 30px;
      span:nth-child(1){
        line-height: 23px;
      }
      span:nth-child(2){
        cursor: pointer;
        font-size: 18px;
        font-weight: 800;
        color: green;
      }
    }
    
  }
  .detail {
    border-bottom: 1px solid #e1e1e1;
    padding: 10px 0;
    padding: 0 20px;
    p {
      display: flex;
      justify-content: space-between;
      font-size: 13px;
      line-height: 34px;
      color: #666;
    }
  }
  .bottom {
    display: flex;
    font-size: 13px;
    color: #666;
    line-height: 50px;
    span {
      flex: 1;
      text-align: center;
      cursor: pointer;
      border-left: 1px solid #e1e1e1;
      i {
        font-size: 16px;
      }
    }
    span:first-child {
      border-left: none;
    }
  }
}
.amap-demo {
  width: 100%;
  height: 400px;
}
.map_dialog /deep/ .el-dialog__body {
  padding: 20px 20px 0 20px;
}
</style>