zhangwencui
8 小时以前 aef408c91928a8dfeb28a3f48190ead32aeb45d1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<template>
  <el-dialog v-model="dialogVisible"
             :title="dialogTitle"
             width="700px"
             :close-on-click-modal="false">
    <el-form ref="formRef"
             :model="form"
             :rules="rules"
             label-width="120px"
             class="mt8">
      <!-- 部门选择 -->
      <el-form-item label="部门"
                    prop="sysDeptId">
        <el-tree-select v-model="form.sysDeptId"
                        :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }"
                        value-key="id"
                        placeholder="请选择部门"
                        check-strictly
                        style="width: 100%"
                        :disabled="['edit', 'view'].includes(operationType)" />
      </el-form-item>
      <!-- 地点信息 -->
      <!-- <el-form-item label="地点名称"
                    prop="locationName">
        <el-input v-model="form.locationName"
                  placeholder="请输入地点名称"
                  :disabled="operationType === 'view'" />
      </el-form-item> -->
      <!-- 打卡范围 -->
      <el-form-item label="打卡范围(m)"
                    prop="radius">
        <el-input-number v-model="form.radius"
                         :min="10"
                         :max="1000"
                         :step="10"
                         placeholder="请输入打卡范围"
                         :disabled="operationType === 'view'" />
      </el-form-item>
      <!-- 高德地图选择 -->
      <el-form-item label="打卡位置"
                    prop="longitude">
        <div class="map-container">
          <div class="map-header"
               style="margin-bottom: 10px">
            <!-- <el-button @click="getCurrentLocation">
              <el-icon>
                <Position />
              </el-icon>
              当前位置
            </el-button> -->
            <!-- <span style="margin-left: 10px; color: #909399;font-size: 12px;">点击地图选择位置</span> -->
          </div>
          <div id="map-container"
               class="map"
               ref="mapContainer"></div>
          <div class="coordinates-info mt10">
            <el-input v-model="form.longitude"
                      readonly
                      placeholder="经度"
                      style="width: 140px; margin-right: 10px" />
            <el-input v-model="form.latitude"
                      readonly
                      placeholder="纬度"
                      style="width: 140px; margin-right: 10px" />
            <!-- <el-input v-model="form.locationName"
                      placeholder="地点名称"
                      style="width: calc(100% - 290px)" /> -->
          </div>
        </div>
      </el-form-item>
      <el-form-item label="地点名称"
                    prop="locationName">
        <el-input v-model="form.locationName"
                  :disabled="operationType === 'view'"
                  placeholder="请输入地点名称" />
      </el-form-item>
      <!-- 上下班时间 -->
      <el-form-item label="上班时间"
                    prop="startAt">
        <el-time-picker v-model="form.startAt"
                        format="HH:mm"
                        value-format="HH:mm"
                        placeholder="请选择上班时间"
                        :disabled="operationType === 'view'" />
      </el-form-item>
      <el-form-item label="下班时间"
                    prop="endAt">
        <el-time-picker v-model="form.endAt"
                        format="HH:mm"
                        value-format="HH:mm"
                        :picker-options="{
      minTime: form.startAt
    }"
                        placeholder="请选择下班时间"
                        :disabled="operationType === 'view'" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary"
                   @click="submitForm"
                   v-if="operationType !== 'view'">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
 
<script setup>
  import { ref, reactive, computed, watch, onMounted, nextTick } from "vue";
  import { ElMessage } from "element-plus";
  import { Position } from "@element-plus/icons-vue";
  import { deptTreeSelect } from "@/api/system/user.js";
  import { addAttendanceRule } from "@/api/personnelManagement/attendanceRules.js";
 
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    operationType: {
      type: String,
      default: "add",
    },
    row: {
      type: Object,
      default: () => ({}),
    },
  });
  // const pickerOptions = ref({ minTime: form.value.startAt });
 
  const emit = defineEmits(["update:modelValue", "close"]);
 
  const dialogVisible = computed({
    get: () => props.modelValue,
    set: val => emit("update:modelValue", val),
  });
 
  const dialogTitle = computed(() => {
    if (props.operationType === "add") return "新增打卡规则";
    if (props.operationType === "edit") return "编辑打卡规则";
    return "查看打卡规则";
  });
 
  // 表单数据
  const formRef = ref();
  const form = reactive({
    id: "",
    sysDeptId: "",
    locationName: "",
    longitude: "",
    latitude: "",
    radius: 100,
    startAt: "09:00",
    endAt: "18:00",
  });
 
  // 表单验证规则
  const rules = {
    sysDeptId: [{ required: true, message: "请选择部门", trigger: "change" }],
    locationName: [
      { required: true, message: "请输入地点名称", trigger: "blur" },
    ],
    longitude: [{ required: true, message: "请选择打卡位置", trigger: "blur" }],
    latitude: [{ required: true, message: "请选择打卡位置", trigger: "blur" }],
    radius: [{ required: true, message: "请输入打卡范围", trigger: "blur" }],
    startAt: [{ required: true, message: "请选择上班时间", trigger: "change" }],
    endAt: [
      { required: true, message: "请选择下班时间", trigger: "change" },
      {
        validator: (rule, value, callback) => {
          if (form.startAt && value) {
            const startParts = form.startAt.split(":");
            const endParts = value.split(":");
            const startTime =
              parseInt(startParts[0]) * 60 + parseInt(startParts[1]);
            const endTime = parseInt(endParts[0]) * 60 + parseInt(endParts[1]);
            if (endTime <= startTime) {
              callback(new Error("下班时间不能早于上班时间"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
        trigger: "change",
      },
    ],
  };
 
  // 部门选项
  const deptOptions = ref([]);
 
  // 地图相关
  const mapContainer = ref(null);
  let map = null;
  let marker = null;
  let circle = null;
 
  // 获取部门列表
  const fetchDeptOptions = () => {
    deptTreeSelect().then(response => {
      deptOptions.value = filterDisabledDept(
        JSON.parse(JSON.stringify(response.data))
      );
    });
  };
 
  // 过滤禁用的部门
  const filterDisabledDept = deptList => {
    return deptList.filter(dept => {
      if (dept.disabled) {
        return false;
      }
      if (dept.children && dept.children.length) {
        dept.children = filterDisabledDept(dept.children);
      }
      return true;
    });
  };
 
  // 初始化地图
  const initMap = () => {
    nextTick(() => {
      if (window.AMap && mapContainer.value) {
        // 初始化地图
        map = new window.AMap.Map(mapContainer.value, {
          zoom: 16,
          center: [116.397428, 39.90923], // 默认北京
        });
 
        // 添加控件
        window.AMap.plugin(["AMap.ToolBar", "AMap.Scale"], function () {
          map.addControl(new window.AMap.ToolBar());
          map.addControl(new window.AMap.Scale());
        });
 
        // 添加标记
        marker = new window.AMap.Marker({
          position: [116.397428, 39.90923],
          draggable: true,
          cursor: "move",
          title: "拖拽定位",
        });
        map.add(marker);
 
        // 添加圆形范围
        circle = new window.AMap.Circle({
          center: [116.397428, 39.90923],
          radius: form.radius,
          strokeColor: "#3366FF",
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: "#3366FF",
          fillOpacity: 0.2,
        });
        map.add(circle);
 
        // 监听标记拖拽
        marker.on("dragend", e => {
          const position = e.lnglat;
          const lng = position.getLng();
          const lat = position.getLat();
          form.longitude = lng;
          form.latitude = lat;
          updateCircle(position);
        });
 
        // 监听标记拖拽开始
        marker.on("dragstart", () => {
          map.setDefaultCursor("move");
        });
 
        // 监听标记拖拽结束
        marker.on("dragend", () => {
          map.setDefaultCursor("default");
        });
 
        // 监听地图点击
        map.on("click", e => {
          const position = e.lnglat;
          const lng = position.getLng();
          const lat = position.getLat();
          form.longitude = lng;
          form.latitude = lat;
          updateMarker(position);
          updateCircle(position);
        });
 
        // 尝试获取当前位置并设置为地图中心
        if (navigator.geolocation && !form.longitude && !form.latitude) {
          navigator.geolocation.getCurrentPosition(
            position => {
              console.log("获取到当前位置:", position);
              const { longitude, latitude } = position.coords;
              const currentPosition = [longitude, latitude];
              map.setCenter(currentPosition);
              updateMarker(currentPosition);
              updateCircle(currentPosition);
              form.longitude = longitude;
              form.latitude = latitude;
            },
            error => {
              console.log("获取位置失败,使用默认位置");
            }
          );
        } else if (form.longitude && form.latitude) {
          // 如果有数据,设置到地图
          const position = [form.longitude, form.latitude];
          map.setCenter(position);
          updateMarker(position);
          updateCircle(position);
        }
      }
    });
  };
 
  // 更新标记位置
  const updateMarker = position => {
    if (marker) {
      marker.setPosition(position);
    }
  };
 
  // 更新圆形范围
  const updateCircle = position => {
    if (circle) {
      circle.setCenter(position);
      circle.setRadius(form.radius);
    }
  };
 
  // 获取当前位置
  const getCurrentLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        position => {
          const { longitude, latitude } = position.coords;
          form.longitude = longitude;
          form.latitude = latitude;
          if (map) {
            map.setCenter([longitude, latitude]);
            updateMarker([longitude, latitude]);
            updateCircle([longitude, latitude]);
          }
 
          // 逆地理编码获取地址
          if (window.AMap) {
            // 加载Geocoder插件
            window.AMap.plugin("AMap.Geocoder", function () {
              const geocoder = new window.AMap.Geocoder();
              geocoder.getAddress([longitude, latitude], (status, result) => {
                if (status === "complete" && result.regeocode) {
                  form.locationName = result.regeocode.formattedAddress;
                }
              });
            });
          }
        },
        error => {
          ElMessage.error("获取位置失败,请手动选择");
        }
      );
    } else {
      ElMessage.error("浏览器不支持地理定位");
    }
  };
 
  // 监听半径变化
  watch(
    () => form.radius,
    newValue => {
      if (circle) {
        circle.setRadius(newValue);
      }
    }
  );
 
  // 监听上班时间变化,触发下班时间校验
  watch(
    () => form.startAt,
    () => {
      if (formRef.value && form.endAt) {
        formRef.value.validateField("endAt");
      }
    }
  );
 
  // 监听弹窗显示
  watch(
    () => dialogVisible.value,
    newValue => {
      if (newValue) {
        // 重置表单
        Object.assign(form, {
          id: "",
          sysDeptId: "",
          locationName: "",
          longitude: "",
          latitude: "",
          radius: 100,
          startAt: "09:00",
          endAt: "18:00",
        });
 
        // 如果是编辑或查看,填充数据
        if (props.operationType !== "add" && props.row.id) {
          // 处理时间格式,确保是HH:mm格式
          const rowData = { ...props.row };
          if (rowData.startAt && rowData.startAt.includes(":")) {
            rowData.startAt = rowData.startAt.split(":").slice(0, 2).join(":");
          }
          if (rowData.endAt && rowData.endAt.includes(":")) {
            rowData.endAt = rowData.endAt.split(":").slice(0, 2).join(":");
          }
          Object.assign(form, rowData);
        }
 
        // 初始化地图
        setTimeout(() => {
          initMap();
        }, 100);
      }
    }
  );
 
  // 提交表单
  const submitForm = () => {
    formRef.value.validate(valid => {
      if (valid) {
        const submitData = {
          ...form,
          // 转换时间格式,确保只保留时分部分
          startAt: form.startAt
            ? `${form.startAt.split(":").slice(0, 2).join(":")}`
            : null,
          endAt: form.endAt
            ? `${form.endAt.split(":").slice(0, 2).join(":")}`
            : null,
        };
 
        if (props.operationType === "add") {
          addAttendanceRule(submitData).then(() => {
            ElMessage.success("新增成功");
            emit("close");
          });
        } else if (props.operationType === "edit") {
          addAttendanceRule(submitData).then(() => {
            ElMessage.success("更新成功");
            emit("close");
          });
        }
      }
    });
  };
 
  // 初始化
  onMounted(() => {
    fetchDeptOptions();
  });
</script>
 
<style scoped lang="scss">
  .map-container {
    width: 100%;
  }
 
  .map {
    width: 100%;
    height: 400px;
    border: 1px solid #e4e7ed;
  }
 
  .coordinates-info {
    display: flex;
    gap: 10px;
  }
 
  .coordinates-display {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
 
  .mt10 {
    margin-top: 10px;
  }
 
  .mt8 {
    margin-top: 8px;
  }
</style>