<!--  -->
<template>
  <div class="maintainbox">
    <div class="maintainbox_search">
      <el-input
        v-model="monitorname"
        placeholder="请输入监测点名称"
        size="mini"
      ></el-input>
      <el-button type="info" @click="search" size="mini">搜索</el-button>
      <el-button
        type="info"
        size="mini"
        @click="(addtraptf = true), (addtitle = '新增监测点')"
        >添加监测点</el-button
      >
      <el-button type="info" size="mini" @click="downloadtf = true"
        >导入监测点</el-button
      >
    </div>
    <el-card class="box-card" style="margin-top: 15px">
      <div class="cbdboxs_table" v-loading="loading">
        <el-table :data="tableData" style="width: 100%" :stripe="true" :height="48*13">
          <el-table-column prop="index" label="序号"> </el-table-column>
          <el-table-column
            prop="point_name"
            label="监测点名称"
          ></el-table-column>
          <el-table-column prop="lng" label="经度">
            <template slot-scope="scope">
              <span>{{ ToDegrees(scope.row.lng, "lng") }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="lat" label="纬度">
            <template slot-scope="scope">
              <span>{{ ToDegrees(scope.row.lat, "lat") }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="messages" label="简介"></el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <span
                style="color: #409eff; margin-right: 5px;cursor: pointer;"
                @click="alter(scope.row)"
                >编辑</span
              >
              <span
                style="color: #409eff; margin-right: 5px;cursor: pointer;"
                @click="deletemain(scope.row)"
                >删除</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        background
        layout="prev, pager, next,jumper"
        :total="total"
        :page-size="20"
        @current-change="pageChange"
        :current-page="page"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      :title="addtitle"
      :visible.sync="addtraptf"
      width="580px"
      @close="resetForm('ruleForm')"
      :close-on-click-modal="false"
    >
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="监测点名称" prop="point_name">
            <el-input v-model="ruleForm.point_name"></el-input>
          </el-form-item>
          <div class="addtrapbox">
            <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-item label="监测点描述" prop="messages">
            <el-input type="textarea" v-model="ruleForm.messages"></el-input>
          </el-form-item>
        </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"
        :disabled="releaseTF"
          >{{ releaseTF ? "发布中..." : "确 定" }}</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      class="map_dialog"
      title="地图选点"
      :visible.sync="addLocationDialogVisible"
      width="820px"
      @closed="addLocationDialogClosed"
      :close-on-click-modal="false"
    >
      <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>
    <el-dialog title="导入监测点" :visible.sync="downloadtf" width="500px" :close-on-click-modal="false">
      <div class="downloadbox">
        <div class="downloadbox_item">
          <p class="title">导入监测点</p>
          <!-- <el-input placeholder="请输入内容" v-model="input1">
          <template slot="prepend">Http://</template>
        </el-input> -->
          <el-upload
            action=""
            :auto-upload="false"
            accept=".xlsx, .xls"
            :show-file-list="false"
            :on-change="handle"
          >
            <el-button type="success" size="mini">点击上传</el-button>
          </el-upload>
          <el-input
            v-model="downloadinput"
            placeholder="请输入内容"
            :disabled="true"
            size="mini"
          ></el-input>
        </div>
        <p class="tishi">
          <span>注：请先下模板，在模板中填入数据上传</span
          ><span @click="download">下载模板</span>
        </p>
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="downloadtf = false">取 消</el-button>
        <el-button type="primary" @click="downloadtf = false">确 定</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    var checklnglat = (rule, value, callback) => {
      if (isNaN(value)) {
        callback(new Error("请输入数字"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      monitorname: "", //搜索 监测点名称
      addtraptf: false, //添加框
      loading: false, //加载框
      page: 1, //页码
      total: 10, //数据总条数，
      tableData: [],
      ruleForm: {
        point_name: "",
        lng: "",
        lat: "",
        messages: "",
      },
      rules: {
        point_name: [
          { required: true, message: "请输入诱捕器名称", trigger: "blur" },
        ],
        lng: [
          { required: true, message: "请输入经度", trigger: "blur" },
          //   { validator: checklnglat, trigger: "blur" },
        ],
        lat: [
          { required: true, message: "请输入纬度", trigger: "blur" },
          //   { validator: checklnglat, trigger: "blur" },
        ],
        // messages: [
        //   { required: true, message: "请输入监测点描述", trigger: "blur" },
        // ],
      },
      addtitle: "新增监测点",
      point_id: "",
      //地图属性
      addLocationDialogVisible: false,
      locationForm: {
        lng: "",
        lat: "",
      },
      addr: "", //搜索栏地址
      address: "", //地图上标签地址
      center: [114.05, 22.55],
      releaseTF:false,
      downloadinput:"",
      downloadtf:false
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getmaintainlist() {
      this.loading = true;
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=monitor_manage.maintain.checkpoint_list",
        data: this.qs.stringify({
          page_item: 20,
          page: this.page,
          point_name: this.monitorname, //              非必传(string)     诱剂名称 搜索项
        }),
      }).then((res) => {
        this.loading = false;
        console.log(res.data.data);
        this.total = res.data.data.total_item;
        this.tableData = res.data.data.page_list;
        for (var i = 0; i < this.tableData.length; i++) {
          this.tableData[i]["index"] = i + 1;
        }
      });
    },
    search() {
      this.getmaintainlist();
    },
    pageChange(e) {
      //当页码更改时
      // console.log(e)
      this.page = e;
      this.getmaintainlist();
    },
    submitForm(formName) {
      console.log(this.ruleForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addtitle == "新增监测点") {
            this.releaseTF = true
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=monitor_manage.maintain.checkpoint_add",
              data: this.qs.stringify({
                point_name: this.ruleForm.point_name, //                  非必传(num)                诱捕器id 修改项
                lat: this.ToDigital(this.ruleForm.lat), //                       必传(string)               纬度
                lng: this.ToDigital(this.ruleForm.lng), //                       必传(string)               经度
                messages: this.ruleForm.messages,
              }),
            }).then((res) => {
              console.log(res);
              if (res.data.data) {
                if (document.getElementsByClassName("el-message").length == 0) {
                this.$message({
                  showClose: true,
                  message: "添加成功！",
                  type: "success",
                });
                }
                this.addtraptf = false;
                this.getmaintainlist();
              } else {
                if (document.getElementsByClassName("el-message").length == 0) {
                this.$message({
                  showClose: true,
                  message: "添加失败" + res.data.message,
                  type: "warning",
                });
                }
              }
              this.releaseTF = false
            });
          } else if (this.addtitle == "修改监测点") {
            this.releaseTF = true
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=monitor_manage.maintain.checkpoint_modify",
              data: this.qs.stringify({
                point_id: this.point_id,
                point_name: this.ruleForm.point_name, //                  非必传(num)                诱捕器id 修改项
                lat: this.ToDigital(this.ruleForm.lat), //                       必传(string)               纬度
                lng: this.ToDigital(this.ruleForm.lng), //                       必传(string)               经度
                messages: this.ruleForm.messages,
              }),
            }).then((res) => {
              console.log(res);
              if (res.data.data) {
                if (document.getElementsByClassName("el-message").length == 0) {
                this.$message({
                  showClose: true,
                  message: "修改成功！",
                  type: "success",
                });
                }
                this.addtraptf = false;
                this.getmaintainlist();
              } else {
                if (document.getElementsByClassName("el-message").length == 0) {
                this.$message({
                  showClose: true,
                  message: "修改失败" + res.data.message,
                  type: "warning",
                });
                }
              }
              this.releaseTF = false
            });
          }
        } else {
          if (document.getElementsByClassName("el-message").length == 0) {
          this.$message({
            message: "请将信息填写完全",
            type: "warning",
          });
          }
          return false;
        }
      });
    },
    resetForm(formName) {
      this.addtraptf = false;
      this.$refs[formName].resetFields();
      for (var key in this.ruleForm) {
        this.ruleForm[key] = "";
      }
    },
    alter(data) {
      console.log(data);
      this.ruleForm.point_name = data.point_name;
      this.ruleForm.lng = data.lng;
      this.ruleForm.lat = data.lat;
      this.ruleForm.messages = data.messages;
      this.addtitle = "修改监测点";
      this.addtraptf = true;
      this.point_id = data.point_id;
    },
    deletemain(data) {
      var str = "您确定删除编号为<" + data.point_name + ">的监测点吗？";
      this.$confirm(str, "删除监测点", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=monitor_manage.maintain.checkpoint_delete",
            data: this.qs.stringify({
              point_id: data.point_id,
            }),
          }).then((res) => {
            console.log(res);
            if (res.data.data) {
              if (document.getElementsByClassName("el-message").length == 0) {
              this.$message({
                showClose: true,
                message: "删除成功!",
                type: "success",
              });
              }
              this.getmaintainlist();
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
              this.$message({
                showClose: true,
                message: "删除失败，" + res.data.message,
                type: "warning",
              });
              }
            }
          });
        })
        .catch(() => {
          if (document.getElementsByClassName("el-message").length == 0) {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          }
        });
    },
    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 {
          if (document.getElementsByClassName("el-message").length == 0) {
          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;
      this.addLocationDialogVisible = false;
    },
    addLocationDialogClosed() {
      //弹框关闭时
      // this.locationForm = { lat: "", lng: "" };
      this.center = [114.05, 22.55];
      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 {
        if (document.getElementsByClassName("el-message").length == 0) {
        this.$message.warning("请输入经纬度！");
        }
        // return fasle;
      }
    },
    dingwei(data) {
      if (this.ruleForm.lng != "" && this.ruleForm.lng != 0) {
        if (isNaN(this.ruleForm.lng)) {
          this.center[0] = this.ToDigital(this.ruleForm.lng);
        } else {
          this.center[0] = this.ruleForm.lng;
        }
      }
      if (this.ruleForm.lat != "" && this.ruleForm.lat != 0) {
        if (isNaN(this.ruleForm.lat)) {
          this.center[1] = this.ToDigital(this.ruleForm.lat);
        } else {
          this.center[1] = this.ruleForm.lat;
        }
      }
      console.log(this.center)
      this.addLocationDialogVisible = true;
      setTimeout(() => {
        // console.log(this.center);
        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) {
      if (!isNaN(lnglat)) {
        return lnglat;
      }
      console.log(lnglat);
      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);
      }
    },
    handle(ev) {
      this.downloadinput = ev.name;
      var datas = new FormData();
      datas.append("username", localStorage.getItem("username"));
      datas.append("file", ev.raw);
      this.$axios({
        method: "POST",
        url: "/api/monitor_point_export",
        data: datas,
        responseType: "blob",
      }).then((res) => {
        console.log(res);
        this.downloadFile(res, "allot_result.xls");
      });
    },
    download() {
      //下载模板
      console.log(22222)
      window.location.href =
        // this.$deriveData +
        "http://192.168.1.17:12345/api/monitor_point_export";
    },
    downloadFile(res, name) {
      let link = document.createElement("a");
      link.href = window.URL.createObjectURL(new Blob([res.data]));
      link.target = "_blank";
      //文件名和格式
      link.download = name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getmaintainlist();
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.maintainbox_search {
  display: flex;
  /deep/.el-input {
    width: 220px;
    margin-right: 15px;
  }
}
.addtrapbox {
  display: flex;
}
.buttonbox {
  margin-bottom: 23px;
  padding-left: 100px;
}
/deep/.el-button--info {
  background-color: #409eff;
  border-color: #409eff;
}
.downloadbox {
  .downloadbox_item {
    display: flex;
    .title {
      width: 100px;
      line-height: 28px;
    }
    .el-input {
      width: 250px;
      margin-left: 15px;
    }
  }
  .tishi {
    padding-left: 100px;
    margin-top: 15px;
    display: flex;
    justify-content: space-between;
    color: #409eff;
    span:last-child {
      cursor: pointer;
    }
  }
}

// 文本域样式更改
/deep/.el-textarea__inner {
  font-family:  "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
}
</style>