<template>
  <transition name="slide-fade">
    <div class="station-types" v-drag>
      <div class="header">
        <span class="title">电子围栏信息</span>
        <i class="el-icon-close" @click="cancel"></i>
      </div>
      <div class="content">
        <el-form ref="form" :model="form" label-width="70px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="围栏名称">
                <el-input v-model="form.name" size="small" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="围栏类型">
                <el-select v-model="form.ruleType" placeholder="请选择围栏类型" size="small" :disabled="true">
                  <el-option :value="item.id" :label="item.name" v-for="(item, i) in typeList" :key="i"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="所属驻勤点" label-width="100px">
                <el-input v-model="form.stationName" size="small" :disabled="isStation"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="!isStation">
              <el-form-item label-width="20px">
                <el-button plain type="primary">关联驻勤点</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="时间范围">
                <el-date-picker
                  :disabled="true"
                  v-model="form.time"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  size="small"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                  type="textarea"
                  :disabled="true"
                  :rows="2"
                  v-model="form.note"
                  size="small"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item label="选择区域">
                <div class="areaContent">
                  <div
                    style="pointer-events: none"
                    class="areaContent-block"
                    @click="changeAreaType(item.id)"
                    v-for="(item, i) in areaList"
                    :key="i"
                    :class="
                      form.shapeType === item.id
                        ? 'areaContent-block-active'
                        : ''
                    "
                  >
                    <div class="areaContent-block-img">
                      <img :src="item.icon" />
                    </div>
                    <div class="areaContent-block-text">
                      {{ item.name }}
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="驻勤人员">
                <!--  <div class="btnContent">
                  <div class="btnContent-block success">添加成员</div>
                  <div class="btnContent-block primary">选择全部</div>
                  <div class="btnContent-block danger">删除选中</div>
                </div>-->
                <div class="popleNum" @click="openPeopleNum">{{ form.peopleNum }}人</div>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item label="">
                <selfTable
                  :columns="columns"
                  :dataList="tableData"
                  :index="true"
                  maxHeight="200"
                  :hasPage="false"
                  :selection="true"
                >
                </selfTable>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </div>
      <div class="footer">
        <div class="footer-left"></div>
        <div class="footer-right">
          <!-- <el-button plain type="primary" @click="cancel">取消</el-button>
          <el-button plain type="primary" @click="reset">重置</el-button>
          <el-button type="success" @click="saveRail">保存电子围栏</el-button> -->
          <el-button plain type="primary" @click="back">返回</el-button>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
// import { parseTime } from "@/utils/index";
import selfTable from "@/components/common/selfTable";
import { createRail, updateRail } from "@/api/security-station-rails-controller";
import { info } from "sass";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "trajectory",
  components: {
    selfTable,
  },
  props: {
    info: {
      type: Object,
      default() {
        return {};
      },
    },
    electronicFenceInfo: {
      type: Object,
      default() {
        return {};
      },
    },
    map: {
      type: Object,
      default() {
        return null;
      },
    },
  },
  watch: {
    info: {
      handler(newVal) {
        console.log(newVal);
        if (Object.keys(newVal).length !== 0) {
          this.form.stationId = newVal.id;
          this.form.peopleNum = newVal.countOfSecurityMan;
          if (Object.keys(this.electronicFenceInfo).length === 0) {
            this.form.stationName = newVal.name;
          }
          this.isStation = true;
        } else {
          this.isStation = false;
        }
      },
      immediate: true,
      deep: true,
    },
    electronicFenceInfo: {
      handler(newVal) {
        console.log("electronicFenceInfo", newVal);
        if (Object.keys(newVal).length !== 0) {
          let deepVal = JSON.parse(JSON.stringify(newVal));
          this.form.stationName = deepVal.stationName;
          this.form.id = deepVal.id;
          this.form.name = deepVal.name;
          this.form.ruleType = deepVal.ruleType;
          this.form.shapeType = deepVal.shapeType;
          this.form.shapedLocation = deepVal.shapedLocation;
          this.form.stationId = deepVal.stationId;
          this.form.time = deepVal.time;
          this.form.note = deepVal.note;
          if (deepVal.shapeType === "Circle") {
            this.setCircle(deepVal.shapedLocation);
          } else if (deepVal.shapeType === "Crib") {
            this.setPolygon(deepVal.shapedLocation);
          } else if (deepVal.shapeType === "Polygon") {
            this.setPolygon(deepVal.shapedLocation);
          }
          // this.form = newVal
          this.isAdd = false;
        } else {
          this.isAdd = true;
          this.reset();
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      isAdd: false,
      isStation: false,
      columns: [
        {
          prop: "peopleType",
          label: "成员类型",
        },
        {
          prop: "name",
          label: "成员名称",
        },
      ],
      tableData: [
        {
          id: 1,
          peopleType: "保安员",
          name: "张三",
        },
        {
          id: 2,
          peopleType: "负责人",
          name: "张三",
        },
      ],
      typeList: [
        {
          id: "Exit",
          name: "离开告警",
        },
        {
          id: "Enter",
          name: "进入告警",
        },
        // {
        //   id: "Access",
        //   name: "进出告警",
        // },
      ],
      areaList: [
        {
          id: "Crib",
          icon: require("@/assets/images/mapToolbar/electronicFence/框选.png"),
          name: "框形选择",
        },
        {
          id: "Circle",
          icon: require("@/assets/images/mapToolbar/electronicFence/圈选.png"),
          name: "圆形选择",
        },
        {
          id: "Polygon",
          icon: require("@/assets/images/mapToolbar/electronicFence/多边形选择.png"),
          name: "多边形选择",
        },
      ],
      form: {
        id: "",
        name: "",
        ruleType: "Exit",
        stationId: this.info.id,
        stationName: this.info.name,
        peopleNum: this.info.countOfSecurityMan,
        time: "",
        note: "",
        shapeType: "",
        peopleList: [],
        shapedLocation: {
          geos: [],
          radius: "",
        },
      },
      Circle: null,
      mousetool: null,
    };
  },
  methods: {
    //返回电子围栏查询
    back() {
      this.$emit("back");
      this.$emit("clearMap");
    },
    openPeopleNum() {
      this.$emit("openPeopleNum", this.info.id);
    },
    //更换区域-已不用
    changeAreaType(id) {
      let that = this;
      this.form.shapeType = id;
      if (this.mouseTool) {
        this.mouseTool.close(true);
      }
      if (id === "Circle") {
        that.drawCircle();
      } else if (id === "Crib") {
        that.drawRectangle();
      } else if (id === "Polygon") {
        that.drawPolygon();
      }
    },
    //画多边形-已不用
    drawPolygon() {
      let that = this;
      AMap.plugin(["AMap.MouseTool"], function () {
        // that.mousetool = new AMap.MouseTool(that.map);
        let mouseTool = new AMap.MouseTool(that.map);
        that.mouseTool = mouseTool;
        //添加事件
        that.mouseTool.polygon({
          strokeColor: "#E6A23C",
          strokeOpacity: 1,
          fillOpacity: 0.2,
          strokeStyle: "dashed",
          strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: "#E6A23C",
          zIndex: 50,
        });
        AMap.Event.addListener(that.mouseTool, "draw", function (e) {
          that.form.shapedLocation.geos = [];
          let coordinate = [];
          let path = e.obj.getPath();
          path.forEach((e) => {
            coordinate.push({ lon: e.getLng(), lat: e.getLat() });
          });
          that.$set(that.form.shapedLocation, "geos", coordinate);
          that.mouseTool.close(false);
        });
      });
    },
    //画圆形-已不用
    drawCircle() {
      let that = this;
      AMap.plugin(["AMap.MouseTool"], function () {
        // that.mousetool = new AMap.MouseTool(that.map);
        let mouseTool = new AMap.MouseTool(that.map);
        that.mouseTool = mouseTool;
        //添加事件
        that.mouseTool.circle({
          strokeColor: "#E6A23C",
          strokeOpacity: 1,
          fillOpacity: 0.2,
          strokeStyle: "dashed",
          strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: "#E6A23C",
          zIndex: 50,
        });
        AMap.Event.addListener(that.mouseTool, "draw", function (e) {
          that.form.shapedLocation.geos = [];
          let path = e.obj.getCenter();
          let coordinate = [];
          console.log(path);
          coordinate.push({
            lat: path.lat,
            lon: path.lng,
          });
          // path.forEach((e) => {
          //   coordinate.push({lat:e.getLng(), lon:e.getLat()});
          // });
          that.$set(that.form.shapedLocation, "geos", coordinate);
          that.$set(that.form.shapedLocation, "radius", e.obj.getRadius());
          that.mouseTool.close(false);
        });
      });
    },
    //画方形-已不用
    drawRectangle() {
      let that = this;
      AMap.plugin(["AMap.MouseTool"], function () {
        // that.mousetool = new AMap.MouseTool(that.map);
        let mouseTool = new AMap.MouseTool(that.map);
        that.mouseTool = mouseTool;
        //添加事件
        that.mouseTool.rectangle({
          strokeColor: "#E6A23C",
          strokeOpacity: 1,
          fillOpacity: 0.2,
          strokeStyle: "dashed",
          strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: "#E6A23C",
          zIndex: 50,
        });
        AMap.Event.addListener(that.mouseTool, "draw", function (e) {
          that.form.shapedLocation.geos = [];
          let coordinate = [];

          let bounds = e.obj.getOptions().bounds;
          console.log(e.obj.getOptions());
          // coordinate = [{lat: bounds.northEast.lat, lon: bounds.northEast.lng},
          // {lat: bounds.southWest.lat, lon: bounds.southWest.lng}]
          coordinate = [
            { lon: bounds.northEast.lng, lat: bounds.southWest.lat },
            { lon: bounds.northEast.lng, lat: bounds.northEast.lat },
            { lon: bounds.southWest.lng, lat: bounds.northEast.lat },
            { lon: bounds.southWest.lng, lat: bounds.southWest.lat },
          ];

          console.log("coordinate", coordinate);
          that.$set(that.form.shapedLocation, "geos", coordinate);
          that.mouseTool.close(false);
        });
      });
    },
    //显示圆形
    setCircle(data) {
      let that = this;
      let Circle = new AMap.Circle({
        center: [data.geos[0].lat, data.geos[0].lon], // 站点坐标，定位圆点位置
        radius: Number(data.radius), //Circle半径，我取得是父组件传过来的值
        borderWeight: 3,
        strokeColor: "#0E70FF",
        strokeOpacity: 1,
        strokeWeight: 6,
        // strokeOpacity: 1,
        fillOpacity: 0.2,
        strokeStyle: "dashed",
        strokeDasharray: [10, 10],
        fillColor: "#0E70FF",
        zIndex: 50,
      });
      console.log(Circle);
      Circle.setMap(that.map);
      that.Circle = Circle;
      // // 缩放地图到合适的视野级别
      that.map.setFitView([that.Circle]);
    },
    setRectangle(data) {
      console.log(data.geos);
    },
    //显示方形和多边形
    setPolygon(data) {
      console.log("=======setPolygon======", data.geos);
      let that = this;
      let path = data.geos.map((x) => [x.lon, x.lat]);
      let polygon = new AMap.Polygon({
        path,
        strokeColor: "#E6A23C",
        strokeWeight: 6,
        strokeOpacity: 1,
        fillOpacity: 0.2,
        fillColor: "#E6A23C",
        zIndex: 50,
        bubble: true,
      });
      console.log(polygon);
      polygon.setMap(that.map);
      that.map.setFitView([polygon]);
      // that.polygon = polygon
      // // 缩放地图到合适的视野级别
      // that.map.setFitView([ that.Circle ])
    },
    cancel() {
      if (this.mouseTool) {
        this.mouseTool.close(true);
      }
      this.$emit("cancel");
    },
    reset() {
      this.form.name = "";
      this.form.ruleType = "Exit";
      this.form.time = [];
      this.form.note = "";
      this.form.shapeType = "";
      this.form.shapedLocation = {
        geos: [],
        radius: "",
      };
      this.$emit("cleanFigure");
    },
    saveRail() {
      if (!this.form.name) {
        this.$message({
          message: "请输入围栏名称",
          type: "warning",
        });
        return;
      }
      if (!this.form.time[0] && !this.form.time[1]) {
        this.$message({
          message: "请输入时间范围",
          type: "warning",
        });
        return;
      }
      if (this.form.shapedLocation.geos.length === 0) {
        this.$message({
          message: "请选择围栏区域",
          type: "warning",
        });
        return;
      }
      let params = {
        name: this.form.name,
        ruleType: this.form.ruleType,
        shapeType: this.form.shapeType,
        stationId: this.form.stationId,
        id: this.form.id,
        note: this.form.note,
        beginTime: this.form.time[0],
        endTime: this.form.time[1],
        shapedLocation: this.form.shapedLocation,
      };

      if (this.isAdd) {
        createRail(params)
          .then((res) => {
            console.log("saveRail", res);
            if (this.mouseTool) {
              this.mouseTool.close(true);
            }
            this.$message({
              message: "新增成功",
              type: "success",
            });
            this.$emit("cancel");
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        updateRail(params)
          .then((res) => {
            console.log("updateRail", res);
            if (this.mouseTool) {
              this.mouseTool.close(true);
            }
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.$emit("cancel");
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    setForm({ shapedLocation, shapeType }) {
      this.form.shapedLocation = { ...{}, ...shapedLocation };
      this.form.shapeType = shapeType;
    },
  },
};
</script>
<style lang="scss" scoped>
.station-types {
  width: 580px;
  // height: 610px;
  background: #ffffff;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
  border-radius: 4px 4px 8px 8px;
  border: 2px solid #3e8dff;
  position: absolute;
  top: 50%;
  right: 10%;
  transform: translateY(-50%);
  padding: 0 24px;
  z-index: 999;

  .header {
    height: 54px;
    border-bottom: 1px solid #bdcfde;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333333;
    }

    i {
      cursor: pointer;
      font-size: 16px;
      color: #999999;
    }
  }

  .content {
    border-bottom: 1px solid #bdcfde;

    .top {
      display: flex;
      align-items: stretch;
      justify-content: flex-start;
      margin: 16px 0 19px 0;

      .location {
        width: 22px;
        height: 22px;
        background: url("~@/assets/images/mapSearch/驻勤点类型.png") no-repeat;
        background-size: 100% 100%;
        margin-right: 8px;
      }

      .title {
        font-size: 16px;
        font-weight: 500;
        color: #0e71ff;
      }
    }

    .type-icon {
      width: 16px;
      height: 16px;
    }

    .el-col {
      //   margin-bottom: 24px;
    }

    ::v-deep .el-radio {
      display: flex;
      align-items: center;

      .el-radio__label {
        display: flex;
        align-items: center;
        padding-left: 8px;
        font-size: 16px;
        color: #666666;
      }
    }

    .areaContent {
      display: flex;
      align-items: center;

      &-block {
        width: 128px;
        height: 32px;
        line-height: 32px;
        border-radius: 6px;
        opacity: 1;
        border: 1px solid #d9d9d9;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        cursor: pointer;

        &:nth-child(3) {
          margin-right: 0;
        }

        &-img {
          width: 24px;
          height: 24px;

          img {
            width: 100%;
            height: 100%;
          }
        }

        &-text {
          margin-left: 8px;
          color: #333333;
          font-size: 14px;
        }

        &-active {
          background: rgba(14, 113, 255, 0.1);
          border: 1px solid #0e71ff;
        }
      }
    }

    .popleNum {
      width: 50px;
      font-size: 14px;
      color: #0e70ff;
      text-decoration: underline;
      cursor: pointer;
    }

    .btnContent {
      display: flex;
      align-items: center;

      &-block {
        width: 128px;
        height: 32px;
        line-height: 32px;
        border-radius: 6px;
        opacity: 1;

        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        cursor: pointer;
        color: #333333;
        font-size: 14px;

        &:nth-child(3) {
          margin-right: 0;
        }
      }

      .success {
        color: #00b40c;
        border: 1px solid #00b40c;

        &:hover {
          color: #ffffff;
          background: #00b40c;
        }
      }

      .primary {
        color: #1677ff;
        border: 1px solid #1677ff;

        &:hover {
          color: #ffffff;
          background: #1677ff;
        }
      }

      .danger {
        background: #ff4d4f;
        color: #ffffff;
        border: 1px solid #ff4d4f;
      }
    }

    .btn-row {
      display: flex;
      align-items: center;

      &-btn {
        width: 38px;
        height: 38px;
        line-height: 38px;
        text-align: center;
        border-radius: 4px;
        border: 1px solid #d9d9d9;
      }

      &-btnAc {
        background: rgba(22, 119, 255, 0.1);
        border-radius: 4px;
        border: 1px solid #1677ff;
      }

      &-btnSelf {
        width: 70px;
        height: 38px;

        ::v-deep .el-input {
          width: 70px;
          height: 38px;
          line-height: 38px;
          font-weight: 500;
          color: #666666;
          font-size: 14px;
        }

        ::v-deep .el-input__inner {
          border: 0;
        }
      }
    }
  }

  .footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    margin-bottom: 20px;

    &-left {
      .del {
        color: rgba(255, 77, 79, 1);
        background-color: #ffffff;
        border-color: rgba(255, 77, 79, 1);

        &:hover {
          color: #ffffff;
          background-color: rgba(255, 77, 79, 1);
          border-color: rgba(255, 77, 79, 1);
        }

        &:focus {
          background-color: rgba(255, 77, 79, 1);
          border-color: rgba(255, 77, 79, 1);
        }
      }
    }
  }
}
</style>
