<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #areaId="{ model, field }">
        <a-tree-select
          show-search
          style="width: 100%"
          v-model:value="model[field]"
          :tree-data="treeData"
          :field-names="{ label: 'name', value: 'id' }"
          placeholder="请选择"
          allow-clear
          multiple
        />
      </template>
      <template #userId="{ model, field }">
        <a-tree-select
          show-search
          style="width: 100%"
          v-model:value="model[field]"
          :tree-data="treeData"
          :field-names="{ label: 'name', value: 'id' }"
          placeholder="请选择"
          allow-clear
          multiple
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, reactive, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './data';
  import { getDeptList } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';
  import { addCheckPoint, editCheckPoint, getSingleCheckPoint } from '@/api/firegrid/index';
  import { EventBus } from '@/utils/eventBus';

  const { createMessage } = useMessage();
  defineOptions({ name: 'DeptModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const treeData: any = ref([]);
  onMounted(() => {
    getTreeList();
  });
  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const position: any = reactive({});
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      getDetail(data.id);
      setFieldsValue({
        ...data.record,
      });
    } else {
      position.lat = data.lat;
      position.lng = data.lng;
    }
  });
  const getDetail = async (id) => {
    getSingleCheckPoint({ id }).then((res) => {
      setFieldsValue({
        ...res,
      });
    });
  };
  const getTreeList = async () => {
    getDeptList().then((res) => {
      treeData.value = res;
    });
  };

  const getTitle = computed(() => (!unref(isUpdate) ? '新增打卡点' : '编辑打卡点'));
  async function handleSubmit() {
    try {
      const values = await validate();
      let query: any = values;
      // 调用接口
      if (!unref(isUpdate)) {
        query.lat = position.lat;
        query.lng = position.lng;
        const data = await addCheckPoint(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          EventBus.emit('addCheckPoint', '');
          return createMessage.success('新增成功');
        } else {
          return createMessage.error('新增失败');
        }
      } else {
        const data = await editCheckPoint(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success');
          return createMessage.success('编辑成功');
        } else {
          return createMessage.error('编辑失败');
        }
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
