<template>
  <div class="panel-box">
    <BasicForm @register="registerForm" />
    <div class="map-box">
      <Map @mapReady="Ready" />
      <TopToolBar @toolCallBack="toolCallBack" />
    </div>
    <div class="btn-box">
      <a-button @click="handleCancel"> 取消</a-button>
      <a-button @click="handleSubmit" type="primary"> 确定</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { dangerSourceForm } from './dangerSourceForm.data';
  import Map from '/@/views/lifeline/Map/index.vue';
  import { ref, unref, onMounted } from 'vue';
  import TopToolBar from '../../../Map/topToolBar.vue';
  import { addData } from '../../../api/emergencyLinkage/dangerSourceApi';
  import { useMessage } from '/@/hooks/web/useMessage';

  const emit = defineEmits(['getShowTable', 'success']);
  const props = defineProps({
    isEdict: {
      type: Boolean,
      default: false,
    },
    record: {
      type: Object,
      default: {} as any,
    },
  });
  const mapReady = ref<boolean>(false);

  const [registerForm, { validateFields, setFieldsValue, getFieldsValue }] = useForm({
    labelWidth: 130,
    schemas: dangerSourceForm,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 8,
    },
  });
  function handleCancel() {
    emit('getShowTable', true);
  }
  async function handleSubmit() {
    // 这里是自己写的按钮，确认提交前需要做表单验证
    const { createMessage } = useMessage();
    try {
      const values = await validateFields();
      addData(values).then(() => {
        emit('getShowTable', true);
        emit('success');
        createMessage.success(`${unref(props.isEdict) ? '编辑' : '新增'}成功`);
      });
    } finally {
    }
    emit('getShowTable', true);
  }
  function Ready(param: boolean) {
    mapReady.value = param;
  }
  function toolCallBack(data: any) {
    let fieldsList = getFieldsValue();
    fieldsList.latitude = data.point.latitude?.toFixed(2) || '';
    fieldsList.longitude = data.point.longitude?.toFixed(2) || '';
    setFieldsValue(fieldsList);
  }
  onMounted(() => {
    if (props.isEdict) {
      setFieldsValue(props.record);
    }
  });
</script>
<style lang="less" scoped>
  .panel-box {
    width: 100%;
    height: 100%;
    background-color: white;
    padding: 20px 30px;

    .map-box {
      width: 660px;
      height: 300px;
      border: 1px;
      position: fixed;
      right: 60px;
      bottom: 36%;
    }

    .btn-box {
      text-align: center;
      position: fixed;
      bottom: 15%;
      left: 50%;

      :deep(.ant-btn) {
        margin: 0 20px;
      }
    }
  }
</style>
