<template>
  <vue-scroll>
  <div class="container-box">
    <el-button type="primary" @click="showDialogFn" size="medium">
      {{
        $t("message.laborMange.add") + $t("message.laborMange.attendanceArea")
      }}
    </el-button>
    <el-button type="primary" @click="getAttendenceTypeFn" size="medium">
      {{ $t("message.laborMange.attendanceMode") }}
    </el-button>
    <div class="listBox">
      <div class="fence-info" v-for="(item, index) in list" :key="index">
        <div class="fence-info-image">
          <img src="@/assets/images/map.png" />
        </div>
        <div class="fence-info-label">
          <div class="fence-info-title">
            {{ $t("message.laborMange.attendanceArea") }}{{ index + 1 }}
          </div>
          <div class="fence-info-text">
            {{ $t("message.laborMange.addressDetails") }}：{{ item.addr }}
          </div>
          <div class="fence-info-text">
            {{ $t("message.laborMange.effectiveRange") }}：{{
              item.areaType == 1
                ? item.standArea + $t("message.laborMange.meter")
                : $t("message.laborMange.custom")
            }}
          </div>
        </div>
        <div class="fence-info-close" @click="deleteFn(item.id)">
          <i class="el-icon-close"></i>
        </div>
      </div>
    </div>
    <el-dialog
      :modal-append-to-body="false"
      :title="
        $t('message.laborMange.add') + $t('message.laborMange.attendanceArea')
      "
      :visible.sync="cardDialog"
      width="667px"
    >
      <div class="dialog_content">
        <div class="mapBox">
          <div class="coordinate-picking">
            <div style="width: calc(100% - 160px)">
              <el-input
                size="medium"
                v-model="addForm.addr"
                id="tipinput"
                :placeholder="$t('message.laborMange.pleaseChoose')"
              >
                <el-button slot="append" icon="el-icon-search"></el-button>
              </el-input>
              <!-- <el-button type="primary" size="medium" @click="search">查询</el-button> -->
            </div>
            <div v-show="addForm.areaType == 2">
              <span
                @click="
                  mapOperateType = 1;
                  exitEditFn();
                "
              >
                <img
                  v-show="mapOperateType == 1"
                  src="@/assets/images/map-operate-move.png"
                  alt=""
                />
                <img
                  v-show="mapOperateType != 1"
                  src="@/assets/images/map-operate-move2.png"
                  alt=""
                />
              </span>
              <span
                @click="
                  mapOperateType = 2;
                  drawRectangle();
                "
              >
                <img
                  v-show="mapOperateType == 2"
                  src="@/assets/images/map-operate-rect.png"
                  alt=""
                />
                <img
                  v-show="mapOperateType != 2"
                  src="@/assets/images/map-operate-rect2.png"
                  alt=""
                />
              </span>
              <span
                @click="
                  mapOperateType = 3;
                  drawPolygon();
                "
              >
                <img
                  v-show="mapOperateType == 3"
                  src="@/assets/images/map-operate-polygon.png"
                  alt=""
                />
                <img
                  v-show="mapOperateType != 3"
                  src="@/assets/images/map-operate-polygon2.png"
                  alt=""
                />
              </span>
            </div>
          </div>
          <div id="container"></div>
        </div>
        <div class="addrTitle">{{ addForm.addr }}</div>
        <el-form size="medium" :model="addForm" ref="cardForm">
          <el-form-item :label="$t('message.laborMange.rangeType')" prop="areaType">
            <el-radio-group v-model="addForm.areaType" @change="changeAreaType">
              <el-radio :label="1">{{$t('message.laborMange.criticalDistrict')}}</el-radio>
              <el-radio :label="2">{{$t('message.laborMange.custom')+$t('message.laborMange.area')}}</el-radio>
            </el-radio-group>
            <el-select
              v-model="addForm.standArea"
              :placeholder="$t('message.laborMange.pleaseChoose')"
              style="margin-left: 40px"
              v-show="addForm.areaType == 1"
              @change="drawCircle()"
            >
              <el-option
                v-for="item in options"
                :key="item"
                :label="item + $t('message.laborMange.meter')"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('message.laborMange.companies')" prop="enterpriseId">
            <el-select
              v-model="addForm.enterpriseId"
              :placeholder="$t('message.laborMange.notSelectedThisApplies')"
              filterable
              :clearable="true"
            >
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.enterpriseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <div class="dialog-footer">
            <el-button
              class="cancleBtn"
              @click="cardDialog = false"
              icon="el-icon-circle-close"
              size="medium"
              >{{ $t("message.personnelPosition.cancel") }}
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="saveCardFn"
              size="medium"
              >{{ $t("message.personnelPosition.determine") }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog
      :modal-append-to-body="false"
      :title="$t('message.laborMange.attendanceMode')"
      :visible.sync="configDialog"
      width="667px"
    >
      <div class="dialog_content">
        <el-form size="medium" :inline="true">
          <el-form-item :label="$t('message.laborMange.clockInWay')">
            <el-radio-group
              v-model="needPhotoForAttend"
              @change="saveAttendType"
            >
              <el-radio :label="0">{{$t('message.laborMange.positioningPunching')}}</el-radio>
              <el-radio :label="1">{{$t('message.laborMange.positioningPunching')}}+{{$t('message.laborMange.faceRecognition')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('message.laborMange.similarityGreaterThan')" v-show="needPhotoForAttend == 1">
            <el-input-number
              v-model="faceScore"
              @change="saveAttendType"
              :min="50"
              :max="100"
              :label="$t('message.laborMange.linkText')"
              :controls="false"
              :placeholder="$t('message.laborMange.default60')"
              style="width: 80px; margin-right: 15px"
            ></el-input-number>
            <!-- <el-input v-model="faceScore" class="input" placeholder="默认60" style="width: 80px;margin-right: 15px" type="number" max="100" min="1" @blur="saveAttendType"></el-input>
                     %认为是同一人，否则不是同一人-->%{{$t('message.laborMange.canBeSuccessful')}}
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</vue-scroll>
</template>
<script>
import {
  electricFenceListApi,
  electricFenceAddApi,
  electricFenceDeleteApi,
} from "@/assets/js/api/laborPerson";
import {
  editProjectConfigListApi,
  getProjectConfigListApi,
} from "@/assets/js/api/project";
import { getCooperatorListApi } from "@/assets/js/api/cooperationUnit";
var mouseTool;
var objs = [];
export default {
  data() {
    return {
      list: [],
      cardDialog: false,
      addForm: {
        addr: "",
        areaType: 1,
        locationList: [
          {
            fenceId: 0,
            id: 0,
            latitude: "",
            longitude: "",
            sortNum: 0,
          },
        ],
        projectSn: "",
        standArea: 100,
        enterpriseId: "",
      },
      locationList: [],
      options: [30, 50, 100, 200, 300],
      map: null,
      mapOperateType: 1,
      needPhotoForAttend: 0, //手机打卡是否需要图片，0否，1是
      configDialog: false,
      faceScore: 60,
      companyList: [],
    };
  },
  mounted() {
    this.getCooperatorList();
    this.loadData();
  },
  methods: {
    //获取企业列表数据
    getCooperatorList() {
      let data = {
        projectSn: this.$store.state.projectSn,
        pageNo: 1,
        pageSize: 100,
        // enterpriseTypeId: this.enterpriseTypeId,
        enterpriseName: "",
      };
      getCooperatorListApi(data).then((res) => {
        this.companyList = res.result.records;
      });
    },
    getAttendenceTypeFn() {
      this.configDialog = true;
      getProjectConfigListApi({ projectSn: this.$store.state.projectSn }).then(
        (res) => {
          if (res.result) {
            this.needPhotoForAttend = res.result[0].phoneClockImageType;
            this.faceScore = res.result[0].faceScore;
          }
        }
      );
    },
    saveAttendType() {
      editProjectConfigListApi({
        projectSn: this.$store.state.projectSn,
        phoneClockImageType: this.needPhotoForAttend,
        faceScore: this.faceScore,
      }).then((res) => {
        this.$message.success(this.$t('message.laborMange.saveSuccess'));
      });
    },
    showDialogFn() {
      this.cardDialog = true;
      this.addForm.areaType=1
      var detail = this.$store.state.currentProDetail;
      this.addForm.addr =
        detail.provinceName +
        detail.cityName +
        detail.areaName +
        detail.projectAddress;
      this.$nextTick(() => {
        this.initMap();
      });
    },
    loadData() {
      electricFenceListApi({ projectSn: this.$store.state.projectSn }).then(
        (res) => {
          this.list = res.result;
        }
      );
    },
    initMap() {
      var that = this;
      //地图加载
      this.map = new AMap.Map("container", {
        resizeEnable: true,
      });
      var geocoder = new AMap.Geocoder({});
      //输入提示
      var autoOptions = {
        input: "tipinput",
      };
      this.auto = new AMap.Autocomplete(autoOptions);
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      }); //构造地点查询类
      AMap.event.addListener(this.auto, "select", this.select); //注册监听，当选中某条记录时会触发
      mouseTool = new AMap.MouseTool(this.map);
      mouseTool.on("draw", function (event) {
        // event.obj 为绘制出来的覆盖物对象
        console.log("覆盖物对象绘制完成", event.obj.getPath());

        let overlaysList = that.map.getAllOverlays("polygon");

        if (overlaysList.length > 1) {
          that.map.remove(overlaysList[0]);
        }

        that.locationList = [];
        var pathArr = event.obj.getPath();
        pathArr.forEach((element) => {
          that.locationList.push({
            longitude: element.lng,
            latitude: element.lat,
          });
        });
      });
      geocoder.getLocation(this.addForm.addr, function (status, result) {
        if (status === "complete" && result.geocodes.length) {
          var lnglat = result.geocodes[0].location;
          console.log(result.geocodes[0]);
          // var arr = lnglat.split(',')
          that.locationList = [
            {
              longitude: lnglat.lng,
              latitude: lnglat.lat,
            },
          ];
          that.drawCircle();
        } else {
          alert("error");
        }
      });
      this.map.on("click", (e) => {
        console.log(
          "您在 [ " +
            e.lnglat.getLng() +
            "," +
            e.lnglat.getLat() +
            " ] 的位置单击了地图！"
        );
        if (this.addForm.areaType == 1) {
          this.locationList = [];
          this.locationList.push({
            longitude: e.lnglat.getLng(),
            latitude: e.lnglat.getLat(),
          });
          var lnglatXY = new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat());
          geocoder.getAddress(lnglatXY, function (status, result) {
            console.log(status, result);
            that.addForm.addr = result.regeocode.formattedAddress;
          });
          this.drawCircle();
        } else {
          this.locationList.push({
            longitude: e.lnglat.getLng(),
            latitude: e.lnglat.getLat(),
          });
        }
      });
    },
    select(e) {
      console.log("select", e);
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name); //关键字查询查询
    },
    //清空地图
    clearFn() {
      this.map.clearMap();
    },
    changeAreaType() {
      this.locationList = [];
      this.clearFn();
    },
    //添加点标记
    addMarker() {
      // 创建一个 Icon
      var startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(25, 34),
        // 图标的取图地址
        image:
          "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        // 图标所用图片大小
        imageSize: new AMap.Size(25, 34),
        // 图标取图偏移量
        // imageOffset: new AMap.Pixel(-9, -3)
      });
      var marker = new AMap.Marker({
        icon: startIcon,
        position: [
          this.locationList[0].longitude,
          this.locationList[0].latitude,
        ],
        size: new AMap.Size(25, 34),
        // offset: new AMap.Pixel(-13, -30)
      });
      marker.setMap(this.map);
    },
    exitEditFn() {
      mouseTool.close();
    },
    //画圆
    drawCircle() {
      if (this.locationList.length == 0) {
        return;
      }
      this.clearFn();
      this.addMarker();
      var circle = new AMap.Circle({
        center: [this.locationList[0].longitude, this.locationList[0].latitude],
        radius: this.addForm.standArea, //半径
        borderWeight: 2,
        strokeColor: "#6caffc",
        strokeOpacity: 1,
        strokeWeight: 2,
        fillOpacity: 0.6,
        strokeStyle: "solid",
        // strokeDasharray: [10, 10],
        // 线样式还支持 'dashed'
        fillColor: "#6caffc",
        zIndex: 50,
      });

      circle.setMap(this.map);
      // 缩放地图到合适的视野级别
      this.map.setFitView([circle]);
    },
    //绘制矩形
    drawRectangle() {
      this.clearFn();
      mouseTool.rectangle({
        strokeColor: "#6caffc",
        // strokeOpacity: 0.5,
        strokeWeight: 2,
        fillColor: "#6caffc",
        fillOpacity: 0.6,
        // strokeStyle还支持 solid
        strokeStyle: "solid",
        // strokeDasharray: [30,10],
      });
    },
    drawPolygon() {
      this.clearFn();
      mouseTool.polygon({
        strokeColor: "#6caffc",
        strokeOpacity: 1,
        strokeWeight: 2,
        // strokeOpacity: 0.2,
        fillColor: "#6caffc",
        fillOpacity: 0.6,
        // 线样式还支持 'dashed'
        strokeStyle: "solid",
        // strokeStyle是dashed时有效
        // strokeDasharray: [30,10],
      });
    },
    saveCardFn() {
      if (this.locationList.length == 0) {
        this.$message.error(this.$t('message.laborMange.noAttendanceAreaSet'));
        return;
      }
      this.addForm.locationList = this.locationList;
      this.addForm.projectSn = this.$store.state.projectSn;
      let json = JSON.parse(JSON.stringify(this.addForm));
      if (json.enterpriseId == null || json.enterpriseId == "") {
        json.enterpriseId = 0;
      }
      electricFenceAddApi(json).then((res) => {
        this.cardDialog = false;
        this.loadData();
      });
    },
    deleteFn(id) {
      this.$confirm(this.$t('message.laborMange.deleteAreaHint'), this.$t('message.laborMange.hint'), {
        confirmButtonText: this.$t('message.laborMange.confirm'),
        cancelButtonText: this.$t('message.laborMange.cancel'),
        type: "warning",
      })
        .then(() => {
          electricFenceDeleteApi({ id: id }).then((res) => {
            this.$message({
              type: "success",
              message:this.$t('message.laborMange.deleteSuccess'),
            });
            this.loadData();
          });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },
  },
};
</script>
<style lang="less" scoped>

.fence-info {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  box-shadow: 6px 6px 20px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
  overflow: hidden;
  position: relative;
  display: flex;
  background-color: white;
  .fence-info-image {
    font-size: 0;
    margin-right: 30px;
  }
  .fence-info-label {
    display: flex;
    flex-direction: column;
    justify-content: center;
    color: #666;
    line-height: 1;
  }
  .fence-info-close {
    cursor: pointer;
    position: absolute;
    top: 20px;
    right: 20px;
  }
  .fence-info-title {
    font-size: 16px;
    margin-bottom: 30px;
  }
  .fence-info-text {
    margin-bottom: 16px;
  }
}
.coordinate-picking {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;

  // .el-input {
  //     width: 20%;
  //     margin: 0 10px 0 5px;
  // }

  // .el-button {
  //     margin-right: 10px;
  // }
}

#container {
  width: 100%;
  height: 400px;
}
.addrTitle {
  font-size: 16px;
  line-height: 56px;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 20px;
}
</style>