<template>
  <div class="data-ledger">
    <div class="left-menu">
      <div class="left-top">
        <div class="realTime-data" @click="selectChange(1)" :class="checked == 1 ? 'top-active' : ''">
          <span>列表</span>
        </div>
        <div class="alarm-data" @click="selectChange(2)" :class="checked == 2 ? 'top-active' : ''">
          <span>轨迹</span>
        </div>
      </div>
      <div v-if="checked === 1">
        <div class="list-tool">
          <el-form :inline="true" size="medium" :model="queryInfo" class="demo-form-inline" style="margin-left: 15px">
            <el-form-item>
              <el-select filterable v-model="queryInfo.devSn" placeholder="请选择" @change="devChange">
                <el-option v-for="(item, index) in nameOptions" :key="index" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-button icon="el-icon-refresh-right" class="tool-btn" style="margin-left: 15px"></el-button>
          <el-button icon="el-icon-plus" class="tool-btn" @click="handle('add', true)"></el-button>
        </div>
        <div class="labor-type">
          <div class="type-box" @click="laborChange(2)" :class="laborType == 2 ? 'laborActive' : ''">
            全部({{ devTypeTotal.count || 0 }})
          </div>
          <div class="type-box" @click="laborChange(1)" :class="laborType == 1 ? 'laborActive' : ''">
            在线({{ devTypeTotal.onlineCount || 0 }})
          </div>
          <div class="type-box" @click="laborChange(0)" :class="laborType == 0 ? 'laborActive' : ''">
            离线({{ devTypeTotal.offlineCount || 0 }})
          </div>
        </div>
        <div class="dev-list" v-if="devList.length > 0">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" style="margin-left:55px"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <div v-for="item in devList" class="choice-item" :key="item.id">
              <div class="list-type">
                <img src="@/assets/images/carPosition/carOn.png" v-if="item.type === 1 && item.online === 1" />
                <img src="@/assets/images/carPosition/carOff.png" v-if="item.type === 1 && item.online === 0" />
                <img src="@/assets/images/carPosition/personOn.png" v-if="item.type === 2 && item.online === 1" />
                <img src="@/assets/images/carPosition/personOff.png" v-if="item.type === 2 && item.online === 0" />
              </div>
              <el-checkbox
                onmouseover="this.style.background='#e2e8f8';"
                onmouseout="this.style.background='none';"
                :label="item.devSn"
                :key="item.devSn"
                style="width: 370px;padding: 5px 0 5px 55px"
              >
                {{ item.numberPlate || '' }}{{ item.personName || '' }}
              </el-checkbox>
              <div class="choice-speed" v-if="item.online === 1">16km/h</div>
            </div>
          </el-checkbox-group>
        </div>
        <div v-else style="text-align: center;margin-top:200px">暂无设备</div>
      </div>
      <div v-if="checked === 2">
        <div class="top-select">
          <el-form :inline="true" size="medium" :model="queryInfo" class="demo-form-inline">
            <el-form-item label="车辆/人员名称">
              <el-select filterable v-model="queryInfo.devSn" placeholder="请选择" @change="devChange">
                <el-option v-for="(item, index) in nameOptions" :key="index" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="track-calendar">
          <el-calendar v-model="dayValue">
            <template slot="dateCell" slot-scope="{ data }">
              <span>{{ dealMyDate(data.day, data) }}</span>
              <p :class="data.styleFlag == true ? 'preventClick' : ''" style="font-size: 14px">
                {{
                  data.day
                    .split('-')
                    .slice(2)
                    .join('')
                }}<br />
              </p>
              <div class="greenStyle">
                <!-- <span class="redStyle">{{data}}</span> -->
                <span>
                  {{
                    55.7 +
                      data.day
                        .split('-')
                        .slice(2)
                        .join('')
                  }}</span
                >
              </div>
            </template>
          </el-calendar>
        </div>
      </div>
    </div>
    <div class="right-data">
      <div class="map-top">
        <div class="map-box" id="mapContainer"></div>
        <div class="wei-lan" v-if="checked === 1">
          <div class="icon-off" v-if="!fenceShow" @click="openFence">
            <img src="@/assets/images/carPosition/iconOff.png" alt="" />
            <div>围栏</div>
          </div>
          <div class="icon-on" v-if="fenceShow" @click="fenceShow = false">
            <img src="@/assets/images/carPosition/iconOn.png" alt="" />
            <div>围栏</div>
          </div>
          <!-- **********************围栏弹窗******************************** -->
          <div class="fenceDialog" v-if="fenceShow">
            <div class="fence-dialog-modal" v-if="fenceCreateShow"></div>
            <div class="fence-box">
              <div class="close-icon" @click="closeFence">
                <i class="el-icon-close" style="font-size: 22px;color:#919398"></i>
              </div>
              <div class="fence-title">围栏</div>
              <div class="fence-tool">
                <div class="tool" @click="openFenceCreate">创建围栏</div>
                <div class="tool">删除围栏</div>
              </div>
              <div class="fence-select">
                <el-input v-model="fenceSearch" placeholder="请输入" size="small" clearable></el-input>
              </div>
              <div class="fence-radio">
                <el-checkbox :indeterminate="isIndeterminateFence" v-model="checkAllFence" @change="fenceAllChange">全选</el-checkbox>
                <vue-scroll>
                  <div style="margin: 5px 0;"></div>
                  <el-checkbox-group v-model="checkedFence" @change="fenceCitiesChange">
                    <div v-for="item in fenceList" class="choice-item" :key="item.id">
                      <el-checkbox :label="item.id" :key="item.id">{{ item.fenceName }} </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </vue-scroll>
              </div>
            </div>
            <!-- 创建围栏弹窗 -->
            <div class="fenceCreate" v-if="fenceCreateShow">
              <!-- <div class="fence-modal"></div> -->
              <div class="fenceCrete-box">
                <div class="close-icon" @click="closeFenceCreate">
                  <i class="el-icon-close" style="font-size: 22px;color:#919398"></i>
                </div>
                <div class="fence-title">创建围栏</div>
                <el-form size="medium" :model="addForm" ref="addForm" label-width="80px" :rules="formFenceRules">
                  <el-form-item label="围栏名称" prop="fenceName">
                    <el-input v-model="addForm.fenceName" placeholder="请输入"></el-input>
                  </el-form-item>

                  <el-form-item label="范围类型" prop="rangeType">
                    <el-radio-group
                      v-model="addForm.rangeType"
                      style="display: flex;justify-content:space-between;padding-top:10px;padding-right:10px"
                      @change="changeAreaType"
                    >
                      <el-radio :label="1">标准区域</el-radio>
                      <el-radio :label="2">自定义</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="区域半径" prop="areaRadius" v-if="addForm.rangeType === 1">
                    <el-input
                      type="number"
                      v-model="addForm.areaRadius"
                      placeholder="请输入"
                      :maxlength="5"
                      @input="areaRadiusChange"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="围栏形状" prop="fenceShape" v-if="addForm.rangeType === 2">
                    <div class="fence-shape">多边形</div>
                  </el-form-item>
                  <div class="create-footer">
                    <el-button class="cancleBtn" @click="fenceCreateShow = false" icon="el-icon-circle-close" size="medium"
                      >{{ $t('message.alarmValueSet.cancel') }}
                    </el-button>
                    <el-button type="primary" icon="el-icon-circle-check" @click="submitFence" size="medium"
                      >{{ $t('message.alarmValueSet.save') }}
                    </el-button>
                  </div>
                </el-form>
              </div>
            </div>
          </div>
        </div>
        <!-- **********************围栏弹窗******************************** -->

        <div class="start-track" @click="startAnimation" v-if="checked === 2">
          开始轨迹动画
        </div>
      </div>
      <!-- **********报警数据*********** -->
      <div class="alarm-bottom">
        <div class="table_wrap whiteBlock">
          <vue-scroll>
            <el-table height="650" class="tables" :data="listData" lazy row-key="id">
              <el-table-column align="center" type="index" width="200" label="序号"> </el-table-column>
              <el-table-column align="center" prop="id" label="车辆/人员名称">
                <template slot-scope="scope">
                  <div v-if="scope.row.type === 1">
                    {{ scope.row.numberPlate }}
                  </div>
                  <div v-else>
                    {{ scope.row.personName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="devSn" label="设备序号"> </el-table-column>
              <el-table-column align="center" prop="createTime" label="报警时间"></el-table-column>
              <el-table-column align="center" prop="alarmInformation" label="报警信息"></el-table-column>
            </el-table>
          </vue-scroll>
          <el-pagination
            class="pagerBox"
            style="position: absolute; top: 85%; left: 40%"
            @size-change="SizeChange"
            @current-change="CurrentChange"
            :current-page="pagInfo.pageNo"
            :page-sizes="$store.state.PAGESIZRS"
            :page-size="pagInfo.pageSize"
            layout="total, sizes, prev, pager, next"
            :total="Number(pagInfo.total)"
            background
          ></el-pagination>
        </div>
      </div>
    </div>

    <!-- 新增设备弹窗 -->
    <el-dialog
      @close="close"
      :modal-append-to-body="false"
      :title="$t('message.alarmValueSet.Popup_title')[Popup.type]"
      :visible.sync="Popup.show"
      width="667px"
    >
      <div class="dialog_content">
        <el-form
          v-if="Popup.type === 'add' || Popup.type === 'edit'"
          size="medium"
          :model="addEditForm"
          ref="addEditForm"
          label-width="120px"
          class="dialogFormBox"
          :rules="formRules"
        >
          <div class="choice-type">
            <el-radio-group v-model="addEditForm.type" :disabled="Popup.type === 'edit'">
              <el-radio :label="1">车辆定位</el-radio>
              <el-radio :label="2">人员定位</el-radio>
            </el-radio-group>
          </div>
          <el-form-item label="车牌号" prop="numberPlate" v-if="addEditForm.type === 1">
            <el-input v-model="addEditForm.numberPlate" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="personName" v-if="addEditForm.type === 2">
            <el-input :disabled="true" v-model="addEditForm.personName" placeholder="请选择">
              <el-button
                slot="append"
                icon="el-icon-plus"
                style="background: #5181F6;color: #fff;font-size: 18px"
                @click="choicePerson = true"
              ></el-button>
            </el-input>
          </el-form-item>

          <!-- 设备SN -->
          <el-form-item label="设备序号" prop="devSn">
            <el-input v-model="addEditForm.devSn" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="司机" prop="driver" v-if="addEditForm.type === 1">
            <el-input v-model="addEditForm.driver" placeholder="请输入"></el-input>
          </el-form-item>
          <div class="dialog-footer">
            <el-button class="cancleBtn" @click="Popup.show = false" icon="el-icon-circle-close" size="medium"
              >{{ $t('message.alarmValueSet.cancel') }}
            </el-button>
            <el-button type="primary" icon="el-icon-circle-check" @click="submit" size="medium"
              >{{ $t('message.alarmValueSet.save') }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import realTimeData from './realTime-data.vue'
import alarmData from './alarm-data.vue'
import { getAlarmRecordInfo, getCarDevOption, addstandardDevApi } from '@/assets/js/api/carManage'
// 围栏相关API
import {
  getFenceTypeTotal,
  getVehiclePositionFence,
  addVehiclePositionFence,
  editVehiclePositionFence,
  deleteVehiclePositionFence,
  deleteBatchVehiclePositionFence
} from '@/assets/js/api/carManage'

var mouseTool
var marker
var lineArr
export default {
  components: {
    realTimeData,
    alarmData
  },
  data() {
    return {
      devTypeTotal: {},
      fenceCreateShow: false, //创建围栏弹窗
      fenceList: ['围栏1', '围栏2', '围栏3', '围栏4', '围栏5'],
      fenceSearch: '', // 围栏搜索
      fenceShow: false, //打开围栏弹窗
      dayValue: '',
      nameOptions: [],
      checkAll: false,
      checkAllFence: false,
      checkedCities: [],
      checkedFence: [],
      devList: ['鲁U6675', '刘江', '蒋东', '鲁U9675'],
      isIndeterminate: true,
      isIndeterminateFence: true,
      checked: 1,
      devName: '',
      laborType: 2,
      map: null,
      locationList: [],
      addForm: {
        areaRadius: 100, //区域半径
        fenceName: '', //围栏名称
        addr: '',
        rangeType: 1,
        locationList: [
          {
            fenceId: 0,
            id: 0,
            latitude: '',
            longitude: '',
            sortNum: 0
          }
        ],
        projectSn: '',
        enterpriseId: ''
      },
      pagInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0 //总条数
      },
      queryInfo: {
        devSn: ''
      },
      listData: [],
      Popup: {
        type: 'add',
        show: false
      },
      addEditForm: {
        personName: '',
        numberPlate: '',
        devSn: '',
        type: 1,
        driver: ''
      },
      formFenceRules: {
        fenceName: [
          {
            required: true,
            message: this.$t('message.personnelPosition.required'),
            trigger: 'blur'
          },
          { min: 1, max: 20, message: this.$t('message.alarmValueSet.message1'), trigger: 'blur' }
        ], // 长度在 1 到 20 个字符
        areaRadius: [
          {
            required: true,
            message: this.$t('message.personnelPosition.required'),
            trigger: 'change'
          }
        ]
      },
      formRules: {
        numberPlate: [
          {
            required: true,
            message: this.$t('message.personnelPosition.required'),
            trigger: 'blur'
          },
          { min: 1, max: 20, message: this.$t('message.alarmValueSet.message1'), trigger: 'blur' }
        ], // 长度在 1 到 20 个字符
        devSn: [
          {
            required: true,
            message: this.$t('message.personnelPosition.required'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted() {
    this.initMap()
    this.getProgressListData()
    this.getCrewListData()
    this.getFenceList()
    this.getFenceType()
  },
  methods: {
    devChange() {
      this.getProgressListData()
    },
    // 获取围栏列表
    getFenceList() {
      let data = {}
      getVehiclePositionFence(data).then(res => {
        if (res.success) {
          console.log('围栏', res)
          this.fenceList = res.result
        }
      })
    },
    // 设备状态
    getFenceType() {
      let data = {
        projectSn: this.$store.state.projectSn
      }
      getFenceTypeTotal(data).then(res => {
        if (res.success) {
          console.log('设备状态', res)
          this.devTypeTotal = res.result
        }
      })
    },

    areaRadiusChange() {
      if (this.addForm.locationList.length === 1) {
        this.drawCircle()
      }
    },
    submitFence() {
      this.addForm.locationList = this.locationList
      console.log('新增围栏', this.addForm)
      let latitude = ''
      let longitude = ''
      let fenceShape = ''
      if (this.addForm.locationList.length === 1) {
        latitude = this.addForm.locationList[0].latitude
        longitude = this.addForm.locationList[0].longitude
      }
      if (this.addForm.locationList.length > 1) {
        for (let index = 0; index < this.addForm.locationList.length; index++) {
          const element = this.addForm.locationList[index]
          let currentStr = element.latitude + '|' + element.longitude
          if (this.addForm.locationList.length - 1 > index) {
            currentStr = currentStr + ','
          }
          fenceShape = fenceShape + currentStr
        }
      }
      console.log('多边形', fenceShape)
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          let params = {
            fenceName: this.addForm.fenceName,
            areaRadius: this.addForm.areaRadius,
            fenceShapeArr: JSON.stringify(this.addForm.locationList),
            fenceShape: fenceShape,
            latitude: latitude,
            longitude: longitude,
            rangeType: this.addForm.rangeType
          }
          // params.alarmPushWorkerId = this.addForm.alarmPushWorkerId.join(',');

          console.log('新增信息', params)
          addVehiclePositionFence(params).then(res => {
            if (res.success) {
              this.$message.success(res.message)
            }
          })
          this.closeFenceCreate()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 打开创建围栏弹窗
    openFenceCreate() {
      this.fenceCreateShow = true
    },
    // 关闭创建围栏弹窗
    closeFenceCreate() {
      this.fenceCreateShow = false
      ;(this.addForm = {
        areaRadius: 100, //区域半径
        fenceName: '', //围栏名称
        addr: '',
        rangeType: 1,
        locationList: [
          {
            fenceId: 0,
            id: 0,
            latitude: '',
            longitude: '',
            sortNum: 0
          }
        ],
        projectSn: '',
        enterpriseId: ''
      }),
        this.exitEditFn()
      this.clearFn()
    },
    // 打开围栏弹窗
    openFence() {
      this.fenceShow = true
    },
    // 关闭围栏弹窗
    closeFence() {
      this.fenceShow = false
    },
    // 提交人员/车辆
    submit() {
      this.$refs['addEditForm'].validate(valid => {
        if (valid) {
          let params = this.addEditForm
          // params.alarmPushWorkerId = this.addEditForm.alarmPushWorkerId.join(',');
          params.projectSn = this.$store.state.projectSn
          console.log('新增信息', this.addEditForm)
          if (this.Popup.type === 'add') {
            addstandardDevApi(params).then(result => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          } else if (this.Popup.type === 'edit') {
            console.log('编辑信息', this.addEditForm)
            // delete this.addEditForm.realTime
            editstandardDevApi(params).then(result => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          }
          this.Popup.show = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    close() {
      this.addEditForm = {
        personName: '',
        numberPlate: '',
        devSn: '',
        type: 1,
        driver: ''
      }
    },
    handle(type, show) {
      //打开弹窗前的统一处理
      this.Popup = {
        type: type,
        show: show
      }
    },
    dealMyDate(v, data) {
      if (v > this.defaultDate) {
        Object.assign(data, { styleFlag: true })
      }
    },
    SizeChange(val) {
      this.pagInfo.pageSize = val
      this.getProgressListData()
    },
    CurrentChange(val) {
      this.pagInfo.pageNo = val
      this.getProgressListData()
    },
    //获取查询下拉
    getCrewListData() {
      let onlineType = ''
      if (this.laborType !== 2) {
        onlineType = this.laborType
      }
      let data = {
        online: onlineType
      }
      getCarDevOption(data).then(res => {
        if (res.code == 200) {
          const filterArray = res.result
            .filter(item => item.numberPlate == '')
            .map(item => ({ devSn: item.devSn, personName: item.personName }))
          let nameOption = filterArray.map(item => {
            return {
              label: item.personName,
              value: item.devSn
            }
          })
          const filteredArray = res.result
            .filter(item => item.personName == null)
            .map(item => ({ devSn: item.devSn, numberPlate: item.numberPlate }))
          let carOption = filteredArray.map(item => {
            return {
              label: item.numberPlate,
              value: item.devSn
            }
          })
          this.nameOptions = nameOption.concat(carOption)
          console.log('车牌号/名字下拉', nameOption, carOption)
          this.devList = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //获取报警列表数据
    getProgressListData() {
      let data = {
        pageNo: this.pagInfo.pageNo,
        pageSize: this.pagInfo.pageSize,
        devSn: this.queryInfo.devSn
      }
      getAlarmRecordInfo(data).then(res => {
        if (res.code == 200) {
          this.listData = res.result.records
          this.pagInfo.total = res.result.total
        }
      })
    },
    laborChange(e) {
      this.laborType = e
      this.getCrewListData()
    },
    handleCheckAllChange(val) {
      let nameArr = this.devList.map(item => item.devSn)
      this.checkedCities = val ? nameArr : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.devList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.devList.length
    },
    fenceAllChange(val) {
      let nameArr = this.fenceList.map(item => item.id)
      this.checkedFence = val ? nameArr : []
      this.isIndeterminateFence = false
      console.log('全选', val)
    },
    fenceCitiesChange(value) {
      let checkedCount = value.length
      this.checkAllFence = checkedCount === this.fenceList.length
      this.isIndeterminateFence = checkedCount > 0 && checkedCount < this.fenceList.length
      console.log('选中', value)
    },
    selectChange(e) {
      this.checked = e
      if (e === 2) {
        this.trackMapInit()
      } else {
        this.initMap()
      }
    },

    // 轨迹绘制地图
    trackMapInit() {
      lineArr = [
        [116.478935, 39.997761],
        [116.478939, 39.997825],
        [116.478912, 39.998549],
        [116.478912, 39.998549],
        [116.478998, 39.998555],
        [116.478998, 39.998555],
        [116.479282, 39.99856],
        [116.479658, 39.998528],
        [116.480151, 39.998453],
        [116.480784, 39.998302],
        [116.480784, 39.998302],
        [116.481149, 39.998184],
        [116.481573, 39.997997],
        [116.481863, 39.997846],
        [116.482072, 39.997718],
        [116.482362, 39.997718],
        [116.483633, 39.998935],
        [116.48367, 39.998968],
        [116.484648, 39.999861]
      ]

      let map = new AMap.Map('mapContainer', {
        resizeEnable: true,
        center: [116.397428, 39.90923],
        zoom: 17
      })

      marker = new AMap.Marker({
        map: map,
        position: [116.478935, 39.997761],
        icon: 'https://webapi.amap.com/images/car.png',
        offset: new AMap.Pixel(-26, -13),
        autoRotation: true,
        angle: -90
      })

      // 绘制轨迹
      var polyline = new AMap.Polyline({
        map: map,
        path: lineArr,
        showDir: true,
        strokeColor: '#28F', //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      })

      var passedPolyline = new AMap.Polyline({
        map: map,
        // path: lineArr,
        strokeColor: '#AF5', //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      })

      marker.on('moving', function(e) {
        passedPolyline.setPath(e.passedPath)
      })

      map.setFitView()

      function startAnimation() {
        marker.moveAlong(lineArr, 200)
      }

      function pauseAnimation() {
        marker.pauseMove()
      }

      function resumeAnimation() {
        marker.resumeMove()
      }

      function stopAnimation() {
        marker.stopMove()
      }
    },
    startAnimation() {
      marker.moveAlong(lineArr, 200)
    },

    // 围栏定位地图
    initMap() {
      var that = this
      //地图加载
      this.map = new AMap.Map('mapContainer', {
        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 {
          console.log('获取绘制', status, result)
        }
      })
      this.map.on('click', e => {
        if (!this.fenceCreateShow) {
          console.log('还未到创建围栏弹窗')
          return
        }
        console.log('您在 [ ' + e.lnglat.getLng() + ',' + e.lnglat.getLat() + ' ] 的位置单击了地图！')
        if (this.addForm.rangeType == 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()
          })
        }
        console.log('当前位置列表', this.locationList)
      })
    },
    select(e) {
      console.log('select', e)
      this.placeSearch.setCity(e.poi.adcode)
      this.placeSearch.search(e.poi.name) //关键字查询查询
    },
    //清空地图
    clearFn() {
      this.map.clearMap()
    },
    changeAreaType(e) {
      // console.log("切换选项",e);
      if (e === 1) {
        this.drawCircle()
      } else {
        this.drawPolygon()
      }
      this.locationList = []
    },
    //添加点标记
    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.areaRadius, //半径
        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()
      console.log('绘制矩形')
      mouseTool.rectangle({
        strokeColor: '#6caffc',
        // strokeOpacity: 0.5,
        strokeWeight: 2,
        fillColor: '#6caffc',
        fillOpacity: 0.6,
        // strokeStyle还支持 solid
        strokeStyle: 'solid'
        // strokeDasharray: [30,10],
      })
    },
    drawPolygon() {
      this.clearFn()
      console.log('自定义绘制')
      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>

<!-- 组件自定义样式（需嵌套外层class） -->
<style lang="scss"></style>

<style lang="scss" scoped>
// 多边形表单
.fence-shape {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 74px;
  height: 34px;
  background: #ffffff;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #d8dbe8;
}

// 围栏弹窗
.fenceDialog {
  position: absolute;
  background: #fff;
  box-sizing: border-box;
  padding: 25px;
  left: 5%;
  top: 20px;
  width: 330px;
  height: 380px;
  .fence-dialog-modal {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0%;
    left: 0%;
    z-index: 3;
    background: rgba(39, 45, 69, 0.5);
  }
  .close-icon {
    position: absolute;
    top: 0px;
    right: 0px;
    cursor: pointer;
  }
  .fence-title {
    border-left: 4px solid #5c81ee;
    font-size: 15px;
    color: #272d45;
    padding-left: 10px;
    margin-bottom: 20px;
    font-weight: 600;
    font-family: Source Han Sans CN, Source Han Sans CN;
  }
}
.fenceCreate {
  position: absolute;
  background: #fff;
  box-sizing: border-box;
  padding: 25px;
  width: 330px;
  height: 380px;
  left: 40px;
  top: 40px;
  z-index: 5;
  // .fence-modal {
  //   position: absolute;
  //   width: 330px;
  //   height: 90px;
  //   top: -90px;
  //   left: 0%;
  //   background: rgba(39, 45, 69, 0.5);
  // }
  .fenceCrete-box {
    position: relative;
    .create-footer {
      margin: 100px 0 0 50px;
    }
  }
}
.fence-box {
  position: relative;
  .fence-tool {
    display: flex;
    justify-content: space-around;
    padding: 0 25px;
    .tool {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80px;
      height: 33px;
      font-size: 14px;
      cursor: pointer;
      background: #ffffff;
      color: #5181f6;
      border-radius: 2px 2px 2px 2px;
      border: 1px solid #5181f6;
    }
  }
  .fence-select {
    margin: 15px 0;
  }
  .fence-radio {
    height: 160px;
  }
}

.choice-type {
  display: flex;
  align-items: center;
  height: 50px;
  justify-content: center;
}
.greenStyle {
  font-size: 12px;
  margin-top: 7px;
}
#mapContainer {
  width: 100%;
  height: 100%;
}
.labor-type {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  .type-box {
    width: 92px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 28px;
    cursor: pointer;
    color: #272d45;
    background: #e2e8f8;
    border-radius: 2px 2px 2px 2px;
  }
  .laborActive {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 92px;
    height: 28px;
    color: #fff;
    background: #5181f6;
    border-radius: 2px 2px 2px 2px;
  }
}

.dev-list {
  width: 100%;
  .choice-item {
    display: flex;
    align-items: center;
    position: relative;
    height: 40px;
    cursor: pointer;
    .list-type {
      position: absolute;
      width: 15px;
      height: 15px;
      margin-left: 30px;
      margin-right: 10px;
      z-index: 2;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .choice-speed {
      display: flex;
      align-items: center;
      width: 50px;
      font-size: 14px;
      position: absolute;
      right: 5%;
    }
  }
}
.top-active {
  border-bottom: 2px solid #5181f6;
  color: #5181f6;
}
.data-ledger {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  .left-menu {
    width: 20%;
    height: 100%;
    background: #fff;
    .left-top {
      display: flex;
      border-bottom: 2px solid #dce6fd;
      .realTime-data {
        display: flex;
        align-items: center;
        width: 50%;
        height: 40px;
        justify-content: center;
        cursor: pointer;
      }
      .alarm-data {
        display: flex;
        align-items: center;
        width: 50%;
        height: 40px;
        justify-content: center;
        cursor: pointer;
      }
    }
    .list-tool {
      display: flex;
      margin-top: 20px;
      .tool-btn {
        width: 30px;
        height: 33px;
        font-size: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #5181f6;
      }
    }
  }
  .right-data {
    width: 78%;
    height: 100%;
    .map-top {
      height: 58%;
      background: #fff;
      position: relative;
      .wei-lan {
        .icon-off {
          position: absolute;
          padding-top: 5px;
          top: 8%;
          left: 1%;
          width: 48px;
          height: 48px;
          cursor: pointer;
          font-size: 14px;
          background: #ffffff;
          text-align: center;
          border-radius: 2px 2px 2px 2px;
          img {
            width: 20px;
            height: 20px;
            margin: 0 auto;
          }
        }
        .icon-on {
          position: absolute;
          padding-top: 5px;
          top: 8%;
          left: 1%;
          text-align: center;
          width: 48px;
          height: 48px;
          cursor: pointer;
          font-size: 14px;
          background: #ffffff;
          color: #5181f6;
          border-radius: 2px 2px 2px 2px;
          img {
            width: 20px;
            height: 20px;
            margin: 0 auto;
          }
        }
      }
      .start-track {
        position: absolute;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px;
        cursor: pointer;
        font-size: 14px;
        background: #ffffff;
        box-shadow: 0px 0px 10px 0px rgba(39, 45, 69, 0.2);
        bottom: 3%;
        right: 3%;
      }
    }
    .alarm-bottom {
      margin-top: 20px;
      height: 39%;
      background: #fff;
    }
  }
}

.top-select {
  margin: 30px 0 0px 30px;
}
.track-calendar {
  /deep/.el-calendar-table .el-calendar-day {
    height: 50px !important;
    text-align: center;
    padding: 0;
    padding-top: 5px;
  }
  /deep/.el-calendar-table {
    border: 1px solid #d8dbe8;
    thead {
      background: #f4f4f5;
    }
  }
  /deep/.el-calendar__header {
    border: none;
  }
  /deep/.is-selected {
    background: #5181f6;
    color: #fff;
    :hover {
      background: #5181f6;
    }
  }
}
</style>
