<template>
  <div class="cameraAddUpdate">
    <el-dialog
      :visible.sync="dialogState"
      center
      :show-close="false"
      top="5vh"
      :close-on-click-modal="false"
    >
      <span slot="title">
        <i class="font-eighteen">{{title}}</i>
      </span>
      <el-form :model="formModel" :rules="formRule" ref="formRef" label-width="auto">
        <el-form-item label="设备名称" prop="cameraName">
          <el-input
            v-model="formModel.cameraName"
            placeholder="设备名称"
            clearable
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="设备区域" prop="cameraRegionFirstlevelArrays">
          <el-cascader
            :options="areaOptions"
            v-model="formModel.cameraRegionFirstlevelArrays"
            clearable
            :props="{ checkStrictly: true }"
            style="width:100%"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="cameraAddress">
          <el-input
            v-model="formModel.cameraAddress "
            placeholder="详细地址"
            clearable
            maxlength="150"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="IP" prop="ip">
          <el-input v-model="formModel.ip" placeholder="ip" clearable></el-input>
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="formModel.port" placeholder="端口" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="formModel.userName"
            placeholder="用户名"
            clearable
            maxlength="30"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passwd">
          <el-input
            v-model="formModel.passwd"
            placeholder="密码"
            clearable
            maxlength="30"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="idBrand">
          <el-select
            style="width:100%"
            v-model="formModel.idBrand"
            @change="rtspip"
            placeholder="请选择活动区域"
          >
            <el-option
              v-for="(item,key) of this.cameraBrand"
              :label="item.dictLabel"
              :key="key"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="型号" prop="version">
          <el-input
            v-model="formModel.version"
            placeholder="型号"
            clearable
            maxlength="30"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="RTSP地址" prop="rtspUrl">
          <el-input
            v-model="formModel.rtspUrl"
            placeholder="RTSP"
            clearable
            maxlength="150"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="摄像头经度：" required>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item prop="cameraLongitude">
                <el-input
                  v-model="formModel.cameraLongitude"
                  placeholder="经度"
                  clearable
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="摄像头纬度：" prop="cameraLatitude">
                <el-input
                  v-model="formModel.cameraLatitude"
                  placeholder="纬度"
                  clearable
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                <!-- <el-button type="primary" @click="getMap">点击定位坐标信息</el-button> -->
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="confirmClick()" :disabled="disabledState">确认</el-button>
        <el-button @click="cancelClick()">取消</el-button>
      </span>
    </el-dialog>

    <!-- rtsp://username:password@ip:port/ch1/main/av_stream 地图 -->
    <el-dialog
      title="获取经纬度信息"
      width="800px"
      center
      @close="isEdit = false"
      class="dialog dialogAdd"
      custom-class="custom-dialog"
      :visible.sync="mapOpen"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <div>
        <el-row style="margin:1rem" :gutter="20">
          <el-col :span="11">
            <div style prop="date1">
              经度：
              <el-input
                style="width:12rem"
                disabled
                v-model="longitude"
                placeholder="经度"
                clearable
                show-word-limit
              ></el-input>
            </div>
          </el-col>
          <el-col :span="11">
            <div style="margin-left:2rem" label="摄像头纬度：" prop="date2">
              纬度：
              <el-input
                style="width:12rem"
                disabled
                v-model="latitude"
                placeholder="纬度"
                clearable
                show-word-limit
              ></el-input>
            </div>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="getlatitude()">确定</el-button>
          </el-col>
        </el-row>
        <div>
          <baidu-map
            class="map"
            :scroll-wheel-zoom="true"
            :center="{lng: 103.931057 , lat: 30.755467}"
            :zoom="15"
          >
            <bm-marker
              :position="position"
              @dragend="positions"
              :dragging="true"
              animation="BMAP_ANIMATION_BOUNCE"
            >
              <bm-label
                content="鼠标拖拽小红点"
                :labelStyle="{color: 'red', fontSize : '16px'}"
                :offset="{width: -50, height: -35}"
              />
            </bm-marker>
          </baidu-map>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import debounce from "lodash/debounce";
export default {
  data() {
    var cameraLatitudes = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入经度"));
      } else {
        if (value > 90 || value < -90) {
          callback(new Error("请输入正确的经度（-90至90）"));
        }
        callback();
        
      }
    };
    var cameraLongitudes = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入纬度"));

      } else {
        if (value > 180 || value < -180) {
          
          callback(new Error("请输入正确的纬度（-180至180）"));
        }

        callback();
      }
    };
    return {
      position: { lng: 103.931057, lat: 30.755467 },
      mapOpen: false,
      // 新增 编辑摄像头确认按钮状态
      disabledState: false,
      // 新增和修改的隐藏显示
      dialogState: false,
      // 标题
      title: "",
      formModel: {
        port: "",
        cameraLatitude: "", //纬度
        cameraLongitude: "", //经度
        cameraName: "",
        cameraRegionFirstlevelArrays: [],
        cameraAddress: "",
        ip: "",
        userName: "",
        passwd: "",
        idBrand: "",
        version: "",
        rtspUrl: ""
      },
      formRule: {
        cameraName: [
          {
            required: "true",
            message: "请输入设备名称",
            trigger: "blur"
          }
        ],
        cameraRegionFirstlevelArrays: [
          {
            required: "true",
            message: "请输入设备区域",
            trigger: "change"
          }
        ],
        cameraLongitude: [
          {
            validator: cameraLongitudes,
            trigger: "blur"
          },
          {
            validator: cameraLongitudes,
            trigger: "change"
          }
        ],
        cameraLatitude: [
          {
            validator: cameraLatitudes,
            trigger: "blur"
          },
          {
            validator: cameraLatitudes,
            trigger: "change"
          }
        ],
        ip: [
          {
            required: "true",
            message: "请输入IP",
            trigger: "blur"
          },
          {
            pattern:
              "^((25[0-5]|2[0-4]\\d|[1]{1}\\d{1}\\d{1}|[1-9]{1}\\d{1}|\\d{1})($|(?!\\.$)\\.)){4}$",
            message: "IP格式错误",
            trigger: "blur"
          }
        ],

        idBrand: [
          {
            required: "true",
            message: "请输入品牌",
            trigger: "change"
          }
        ],
        version: [
          {
            required: "true",
            message: "请输入型号",
            trigger: "blur"
          }
        ],
        rtspUrl: [
          {
            required: "true",
            message: "请输入RTSP地址",
            trigger: "blur"
          }
          // {
          // 	pattern: "rtsp:\/\/\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}",
          // 	message: "RTSP格式错误",
          // 	trigger: "blur"
          // }
        ]
      },
      //摄像头品牌
      cameraBrand: [],
      // 区域类型列表
      areaOptions: [],
      // 位置类型列表
      // areaTypeList: [],
      // 新增/修改
      type: "",
      latitude: 30.755467, //纬度
      longitude: 103.931057 //经度
    };
  },
  created() {
    // 获取区域
    this.$http.get("/camera/getRegion").then(res => {
      if (res.data.code === 0) {
        this.areaOptions = res.data.data;
      }
    });
    this.$http.get("sys/dict/data/findByType/cameraBrand").then(res => {
      if (res.data.code === 0) {
        this.cameraBrand = res.data.data;
      }
    });
  },
  methods: {
    rtspip() {
      if (this.formModel.idBrand == "1214018558680039425") {
        console.log(this.formModel.idBrand);
        //rtsp://username:password@ip:port/ch1/main/av_stream
        this.formModel.rtspUrl = `rtsp://${this.formModel.userName}:${this.formModel.passwd}@${this.formModel.ip}:${this.formModel.port}/ch1/main/av_stream`;
      } else if (this.formModel.idBrand == "1214018820136173569") {
        //rtsp://username:password@ip
        this.formModel.rtspUrl = `rtsp://${this.formModel.userName}:${this.formModel.passwd}@${this.formModel.ip}`;
      } else if (this.formModel.idBrand == "1214813295771058178") {
        //rtsp://username:password@ip:port/video1
        this.formModel.rtspUrl = `rtsp://${this.formModel.userName}:${this.formModel.passwd}@${this.formModel.ip}:${this.formModel.port}/video1`;
      } else if (this.formModel.idBrand == "1214813701007933442") {
        ///rtsp://ip
        this.formModel.rtspUrl = `rtsp://${this.formModel.ip}`;
      }
    },
    getlatitude() {
      this.formModel.cameraLatitude = this.latitude; //纬度
      this.formModel.cameraLongitude = this.longitude; //经度
      this.mapOpen = false;
    },
    //获取地图经纬度
    positions(type, target, pixel, point) {
      this.latitude = type.point.lat;
      this.longitude = type.point.lng;
    },
    getMap() {
      this.mapOpen = true;
    },
    init(param1, id) {
      this.dialogState = true;
      this.disabledState = false;
      this.type = param1;
      if (param1 === "add") {
        this.title = "新建摄像头";
        this.$nextTick(() => {
          this.$refs.formRef.resetFields();
        });
      } else {
        this.title = "修改摄像头";
        this.$http.get(`/camera/findById/${id}`).then(res => {
          if (res.data.code === 0) {
            // 回显转换
            this.formModel = res.data.data;
            this.formModel.cameraRegionFirstlevelArrays = this.formModel.cameraRegionFirstlevelArrays
              .join()
              .split(",");
          } else {
            console.log(res);
          }
        });
      }
    },
    // 确认编辑
    confirmClick: debounce(function() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.disabledState = true;
          this.$http
            .post(
              `/camera/${this.type === "add" ? "insert" : "update"}`,
              this.formModel
            )
            .then(res => {
              this.disabledState = false;
              if (res.data.code === 0) {
                this.dialogState = false;
                this.type === "add"
                  ? this.$message.success("新增成功")
                  : this.$message.success("修改成功");
                this.$emit("refreshClick", this.type);
              } else if (res.data.code == 60001) {
                this.$message.warning(res.data.message);
              } else {
                console.log(res);
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }),
    // 取消编辑
    cancelClick() {
      this.$refs.formRef.resetFields();
      this.dialogState = false;
    }
  }
};
</script>

<style scoped>
.map>>>.anchorBL,
 .map>>>.anchorTR,
 .map>>>.BMap_zlHolder {
  display: none;
  visibility: hidden;
 }
.map {
  height: 500px;
  margin: 1rem;
}
i {
  font-style: normal;
  font-family: "Noto Sans SC";
  color: #333;
}

.font-eighteen {
  font-size: 18px;
}
</style>
