DeviceStep1.vue 15.5 KB
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
<template>
  <div class="step1">
    <div class="step1-form">
      <BasicForm @register="register">
        <template #addOrg="{ model, field }">
          <div style="display: flex; align-items: center">
            <div style="width: 245px">
              <a-tree-select
                v-model:value="model[field]"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="请选择组织"
                allow-clear
                tree-default-expand-all
                :tree-data="treeData"
              />
            </div>
            <div>
              <a-button type="link" @click="handleOpenOrgDrawer">新增组织</a-button>
            </div>
          </div>
        </template>
        <template #iconSelect>
          <Upload
            name="avatar"
            :show-upload-list="false"
            list-type="picture-card"
            class="avatar-uploader"
            :customRequest="customUpload"
            :before-upload="beforeUpload"
          >
            <img v-if="devicePic" :src="devicePic" alt="avatar" />
            <div v-else>
              <LoadingOutlined v-if="loading" />
              <PlusOutlined v-else />
              <div class="ant-upload-text">图片上传</div>
            </div>
          </Upload>
        </template>
        <template #snCode="{ model, field }">
          <div class="flex">
            <Input v-model:value="model[field]" />
            <a-button type="link" @click="generateSN">自动生成</a-button>
          </div>
        </template>
        <template #deviceAddress>
          <Input disabled v-model:value="positionState.address">
            <template #addonAfter>
              <EnvironmentTwoTone @click="selectPosition" />
            </template>
          </Input>
        </template>
      </BasicForm>
      <div class="flex justify-center" v-if="isUpdate">
        <a-button type="primary" @click="nextStep">下一步</a-button>
      </div>
    </div>
    <Modal
      v-model:visible="visible"
      title="设备位置"
      @ok="handleOk"
      width="800px"
      @cancel="handleCancel"
      centered
    >
      <div>
        <Form :label-col="labelCol" :colon="false" :rules="rules" :model="positionState">
          <Row :gutter="20" class="mt-4">
            <Col :span="20">
              <FormItem label="搜索位置">
                <AutoComplete
                  v-model:value="positionState.address"
                  :options="dataSource"
                  style="width: 100%"
                  placeholder="搜索位置"
                  @search="debounceSearch"
                  @select="handleSelect"
                  backfill
                />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="20" class="">
            <Col :span="10">
              <FormItem label="经度" name="longitude">
                <Input
                  @blur="redirectPosition"
                  @change="redirectPosition"
                  v-model:value="positionState.longitude"
                />
              </FormItem>
            </Col>
            <Col :span="10">
              <FormItem label="纬度" name="latitude">
                <Input
                  @blur="redirectPosition"
                  @change="redirectPosition"
                  v-model:value="positionState.latitude"
                />
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div ref="wrapRef" style="height: 300px; width: 90%" class="ml-6"></div>
      </div>
    </Modal>
    <DeptDrawer @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, unref, reactive, toRefs, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { step1Schemas } from '../../config/data';
  import { useScript } from '/@/hooks/web/useScript';
  import { Input, Upload, message, Modal, Form, Row, Col, AutoComplete } from 'ant-design-vue';
  import { EnvironmentTwoTone, PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
  import { upload } from '/@/api/oss/ossFileUploader';
  import { FileItem } from '/@/components/Upload/src/typing';
  import { BAI_DU_MAP_URL } from '/@/utils/fnUtils';
  import { generateSNCode } from '/@/api/device/deviceManager';
  import icon from '/@/assets/images/wz.png';
  import { useDebounceFn } from '@vueuse/core';
  import { validatorLongitude, validatorLatitude } from '/@/utils/rules';
  import { getOrganizationList } from '/@/api/system/system';
  import { copyTransFun } from '/@/utils/fnUtils';
  import { useDrawer } from '/@/components/Drawer';
  import DeptDrawer from '/@/views/system/organization/OrganizationDrawer.vue';

  export default defineComponent({
    components: {
      BasicForm,
      Input,
      AutoComplete,
      Upload,
      EnvironmentTwoTone,
      PlusOutlined,
      Modal,
      Form,
      FormItem: Form.Item,
      Row,
      Col,
      LoadingOutlined,
      DeptDrawer,
    },
    props: {
      isUpdate: {
        type: Boolean,
      },
    },
    emits: ['next'],
    setup(props, { emit }) {
      const orgData: any = reactive({
        treeData: [],
      });
      const getOrganizationListFunc = async () => {
        const data = await getOrganizationList();
        copyTransFun(data as any as any[]);
        orgData.treeData = data;
      };
      onMounted(async () => {
        await getOrganizationListFunc();
      });
      const { treeData } = toRefs(orgData);
      const [registerModal, { openDrawer }] = useDrawer();
      const handleOpenOrgDrawer = () => {
        openDrawer(true, {
          isUpdate: false,
        });
      };
      const handleSuccess = async () => {
        await getOrganizationListFunc();
      };
      const redirectPosition = () => {
        if (positionState.longitude && positionState.latitude) {
          var pt = new BMap.Point(positionState.longitude, positionState.latitude);
          getAddrByPoint(pt);
        }
      };
      const rules: any = {
        longitude: [{ required: true, validator: validatorLongitude, trigger: 'blur' }],
        latitude: [{ required: true, validator: validatorLatitude, trigger: 'blur' }],
      };
      const devicePic = ref('');
      const loading = ref(false);

      const [register, { validate, resetFields, setFieldsValue, getFieldsValue, updateSchema }] =
        useForm({
          labelWidth: 120,
          schemas: step1Schemas,
          actionColOptions: {
            span: 14,
          },
          labelAlign: 'right',
          showResetButton: false,
          showSubmitButton: false,
        });
      async function nextStep() {
        try {
          let values = await validate();
          console.log(values);
          values = { devicePic: devicePic.value, ...positionState, ...values };
          delete values.icon;
          delete values.deviceAddress;
          emit('next', values);
          // 获取输入的数据
        } catch (e) {}
      }

      // 图片上传
      async function customUpload({ file }) {
        if (beforeUpload(file)) {
          devicePic.value = '';
          loading.value = true;
          const formData = new FormData();
          formData.append('file', file);
          const response = await upload(formData);
          if (response.fileStaticUri) {
            devicePic.value = response.fileStaticUri;
            loading.value = false;
          }
        }
      }
      const beforeUpload = (file: FileItem) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          message.error('只能上传图片文件!');
        }
        const isLt2M = (file.size as number) / 1024 / 1024 < 5;
        if (!isLt2M) {
          message.error('图片大小不能超过5MB!');
        }
        return isJpgOrPng && isLt2M;
      };

      // 地图的弹框
      const visible = ref(false);
      const selectPosition = () => {
        visible.value = true;
        if (!positionState.longitude) {
          positionState.longitude = '104.04666605565338';
          positionState.latitude = '30.543516387560476';
          initMap(positionState.longitude, positionState.latitude);
        } else {
          initMap(positionState.longitude, positionState.latitude);
        }
      };

      let positionState = reactive<{
        longitude: string;
        latitude: string;
        description?: string;
        address: string;
        map: null;
        marker: null;
      }>({
        longitude: '',
        latitude: '',
        address: '',
        map: null,
        marker: null,
      });
      /**
       * 逆地址解析函数(根据坐标点获取详细地址)
       * @param {Object} point   百度地图坐标点,必传
       */
      function getAddrByPoint(point) {
        let geco = new BMap.Geocoder();
        geco.getLocation(point, function (res) {
          positionState.marker.setPosition(point); //重新设置标注的地理坐标
          positionState.map.panTo(point); //将地图的中心点更改为给定的点
          positionState.address = res?.address; //记录该点的详细地址信息
          positionState.longitude = point?.lng; //记录当前坐标点
          positionState.latitude = point?.lat;
        });
      }

      // 地图
      const wrapRef = ref<HTMLDivElement | null>(null);
      const { toPromise } = useScript({ src: BAI_DU_MAP_URL });

      // 初始化地图
      async function initMap(longitude, latitude) {
        await toPromise();
        await nextTick();
        const wrapEl = unref(wrapRef);
        const BMap = (window as any).BMap;
        if (!wrapEl) return;
        let preMarker = null;
        positionState;
        positionState.map = new BMap.Map(wrapEl, { enableMapClick: false });
        let myIcon = new BMap.Icon(icon, new BMap.Size(20, 30));
        const point = new BMap.Point(Number(longitude), Number(latitude));
        positionState.marker = new BMap.Marker(point, { icon: myIcon, enableDragging: true });
        if (positionState.marker) {
          positionState.map.removeOverlay(preMarker);
        }
        positionState.map.addOverlay(positionState.marker);
        preMarker = positionState.marker;
        positionState.map.centerAndZoom(point, 15);
        positionState.map.enableScrollWheelZoom(true);
        let navigationControl = new BMap.NavigationControl({
          //创建一个特定样式的地图平移缩放控件
          anchor: BMAP_ANCHOR_TOP_RIGHT, //靠右上角位置
          type: BMAP_NAVIGATION_CONTROL_LARGE, //SMALL控件类型
        });
        positionState.map.addControl(navigationControl); //将控件添加到地图

        positionState.marker.addEventListener('dragend', function (e) {
          getAddrByPoint(e.point); //拖拽结束后调用逆地址解析函数,e.point为拖拽后的地理坐标
        });
        positionState.map.addEventListener('click', (e) => {
          getAddrByPoint(e.point);
        });
      }
      const dataSource = ref<any[]>([]);
      const onSearch = (searchText: string) => {
        if (!searchText) {
          dataSource.value = [];
          return;
        }
        let local = new BMap.LocalSearch(positionState.map, {
          onSearchComplete(res) {
            //检索完成后的回调函数
            if (local.getStatus() == BMAP_STATUS_SUCCESS) {
              const searchArr = [];
              for (let i = 0; i < res.getCurrentNumPois(); i++) {
                const item = res.getPoi(i);
                searchArr.push({
                  label: item.address + item.title,
                  value: item.address + item.title,
                  point: item.point,
                });
              }
              dataSource.value = searchArr;
            }
          },
        }); //调用search方法,根据检索词searchText发起检索
        local.search(searchText);
      };
      // 防抖函数包装一下,防止频繁执行
      const debounceSearch = useDebounceFn(onSearch, 500);
      function handleSelect(value, option) {
        dataSource.value = [];

        positionState.address = option.value; //记录详细地址,含建筑物名
        const { lat, lng } = option.point;
        positionState.latitude = lat; //记录当前选中地址坐标
        positionState.longitude = lng; //记录当前选中地址坐标
        positionState.map.clearOverlays(); //清除地图上所有覆盖物
        let myIcon = new BMap.Icon(icon, new BMap.Size(20, 30));
        positionState.marker = new BMap.Marker(option.point, {
          icon: myIcon,
          enableDragging: true,
        }); //根据所选坐标重新创建Marker
        positionState.marker.addEventListener('dragend', function (e) {
          getAddrByPoint(e.point); //拖拽结束后调用逆地址解析函数,e.point为拖拽后的地理坐标
        });
        positionState.map.addOverlay(positionState.marker); //将覆盖物重新添加到地图中
        positionState.map.panTo(option.point); //将地图的中心点更改为选定坐标点
      }

      const generateSN = async () => {
        const data = await generateSNCode();
        setFieldsValue({
          sn: data,
        });
      };

      // 确定选择的位置
      const handleOk = () => {
        visible.value = false;
      };
      // 取消选择位置
      const handleCancel = () => {
        dataSource.value = [];
        for (let key in positionState) {
          positionState[key] = '';
        }
      };
      // 父组件调用更新字段值的方法
      function parentSetFieldsValue(data) {
        const { deviceInfo = {} } = data;
        positionState.longitude = deviceInfo.longitude;
        positionState.latitude = deviceInfo.latitude;
        positionState.address = deviceInfo.address;
        devicePic.value = deviceInfo.avatar;
        setFieldsValue(data);
      }
      // 父组件调用获取字段值的方法
      function parentGetFieldsValue() {
        return getFieldsValue();
      }

      // 父组件调用表单验证
      async function parentValidate() {
        const valid = await validate();
        return valid;
      }

      // 父组件重置图片
      function parentResetDevicePic(deviceInfo) {
        devicePic.value = deviceInfo.avatar;
      }
      // 父组件重置位置
      function parentResetPositionState() {
        for (let key in positionState) {
          positionState[key] = '';
        }
      }
      // 禁用设备类型
      function disabledDeviceType(disabled: boolean) {
        updateSchema({
          field: 'deviceType',
          componentProps: {
            disabled,
          },
        });
      }

      return {
        resetFields,
        positionState,
        register,
        beforeUpload,
        customUpload,
        selectPosition,
        devicePic,
        visible,
        handleOk,
        handleCancel,
        wrapRef,
        labelCol: { style: { width: '100px' } },
        parentSetFieldsValue,
        parentGetFieldsValue,
        parentValidate,
        parentResetDevicePic,
        parentResetPositionState,
        disabledDeviceType,
        nextStep,
        onSearch,
        handleSelect,
        dataSource,
        debounceSearch,
        generateSN,
        loading,
        rules,
        redirectPosition,
        treeData,
        registerModal,
        handleOpenOrgDrawer,
        handleSuccess,
      };
    },
  });
</script>
<style lang="less" scoped>
  .step1-form {
    width: 450px;
    margin: 0 auto;
  }

  :deep(.ant-radio-group) {
    width: 15vw;
  }
</style>