<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="isEditMode ? t('layout.map.projectInfo') : t('layout.map.addPro')"
    :minHeight="380"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="p-20px">
      <BasicForm @register="registerForm">
        <template #isShow="{ model, field }">
          <!-- gpsNum: {{ model[field] }} {{ currentLatLng }} -->
          <Switch :checked="model[field]" :disabled="!currentLatLng" @change="handleUpdateSwitch" />
        </template>
        <template #location>
          <div class="map-select">
            <a-input v-model:value="location" allow-clear disabled />
            <a-button type="default" @click="handleOpenMap">{{
              t('layout.map.mapSearch')
            }}</a-button>
          </div>
        </template>
      </BasicForm>
    </div>
    <template #centerFooter> </template>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { AddOptOrUpdateApi, ListAllGpsApi } from '/@/api/mapOpt/list';
  import { uniqBy } from 'lodash-es';
  import { useLocaleStore } from '/@/store/modules/locale';
  import { Switch } from 'ant-design-vue';
  const localeStore = useLocaleStore();
  const isJA = computed(() => localeStore.getLocale === 'ja');
  const { t } = useI18n();

  export default defineComponent({
    components: { BasicModal, BasicForm, Switch },
    props: {
      currentLatLng: {
        type: Object as PropType<{
          lat: number;
          lng: number;
        }>,
      },
    },
    emits: ['register', 'success', 'open-map', 'reload', 'cancel', 'update-gps'],
    setup(props, { emit }) {
      // const { createMessage } = useMessage();
      const isEditMode = ref(false);
      const locationEdit = ref('');
      const isDefaultSelect = ref(1);

      // const customEditSelect: FormSchema = {
      //   field: 'sceneID',
      //   label: '选择场景',
      //   component: 'Input',
      // };
      const schemas: FormSchema[] = [
        {
          field: 'id',
          label: 'Id',
          component: 'Input',
          ifShow: false,
        },
        {
          field: 'projectName',
          label: t('layout.map.projectName'),
          component: 'Input',
          required: true,
          componentProps: {
            maxLength: 100,
          },
          colProps: {
            span: 24,
          },
        },
        // {
        //   field: 'projectSn',
        //   label: t('layout.map.projectSn'),
        //   required: true,
        //   component: 'Input',
        //   componentProps: {
        //     maxLength: 100,
        //   },
        //   colProps: {
        //     span: 24,
        //   },
        // },
        {
          field: 'tempSlect',
          label: t('layout.map.geoLocation'),
          component: 'Select',
          defaultValue: 1,
          componentProps: {
            allowClear: false,
            onChange: function (value: number) {
              isDefaultSelect.value = value;
            },
            options: [
              {
                label: t('layout.map.geoLocation.opt1'),
                value: 1,
              },
              {
                label: t('layout.map.geoLocation.opt2'),
                value: 2,
              },
            ],
          },
          colProps: {
            span: 24,
          },
        },
        {
          field: 'location',
          label: t('layout.map.location'),
          component: 'Input',
          required: false,
          slot: 'location',
          colProps: {
            span: 24,
          },
          ifShow: () => {
            return isDefaultSelect.value === 1;
          },
        },
        {
          field: 'gpsNum',
          label: t('layout.map.selectScene'),
          component: 'ApiSelect',
          componentProps: {
            api: async (params) => {
              const data = await ListAllGpsApi(params);
              data.list = uniqBy(data.list, 'num');
              return data;
            },
            resultField: 'list',
            labelField: 'title',
            valueField: 'num',
            showSearch: true,
            optionFilterProp: 'label',
            immediate: true,
            listHeight: 160,
            allowClear: true,
            onSelect: (_, item) => {
              const { lat, lon } = item;
              console.log('选择场景', _, lat, lon);
              if (lat && lon) {
                emit('update-gps', {
                  lat: lat,
                  lng: lon,
                });
              }
            },
            params: {
              pageNum: 1,
              // type: 1,
              searchKey: '',
              pageSize: 5000,
            },
          },
          ifShow: () => {
            return isDefaultSelect.value === 2;
          },
        },
        {
          field: 'isShow',
          label: t('layout.map.homeShow'),
          component: 'Switch',
          defaultValue: true,
          slot: 'isShow',
          colProps: {
            span: 24,
          },
        },
      ];

      const location = computed(() =>
        props.currentLatLng ? `${props.currentLatLng?.lat}, ${props.currentLatLng?.lng}` : '',
      );
      const googleKey = computed(() => import.meta.env.VITE_GOOGLE_KEY);

      const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
        schemas: schemas,
        labelWidth: isJA.value ? 130 : 100,
        showActionButtonGroup: false,

        actionColOptions: {
          span: 24,
        },
        // submitFunc: handleSubmit,
      });
      const [register, { closeModal }] = useModalInner((data) => {
        resetFields();
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        if (data.gpsNum) {
          isDefaultSelect.value = 2;
        } else {
          isDefaultSelect.value = 1;
        }
        const allData = {
          ...data,
          tempSlect: isDefaultSelect.value,
          isShow: Boolean(data.isShow),
        };
        console.log('Data Received', allData);
        setFieldsValue(allData);
        isEditMode.value = true;
      }
      const handleSubmit = async () => {
        const data = await validate();
        const allValue = getFieldsValue();
        const pro = {
          ...allValue,
          id: allValue.id,
          isShow: Number(data.isShow),
          projectName: data.projectName,
          projectSn: data.projectSn,
          lat: props.currentLatLng?.lat,
          lon: props.currentLatLng?.lng,
          alt: 0,
        };
        if (!isEditMode.value) {
          delete pro.id;
        }
        if (!pro.lat && !pro.lon) {
          console.log('没有地理信息');
          pro.isShow = 0;
        }
        console.log('save', pro);
        await AddOptOrUpdateApi(pro);
        closeModal();
        resetFields();
        isDefaultSelect.value = 1;
        emit('reload');
      };

      const handleCancel = async () => {
        resetFields();
        isDefaultSelect.value = 1;
        emit('cancel');
      };
      const handleOpenMap = () => {
        if (props.currentLatLng?.lat && props.currentLatLng?.lng) {
          emit('open-map', props.currentLatLng);
        } else {
          emit('open-map');
        }
      };
      const handleUpdateSwitch = (value: boolean) => {
        console.log('value', value);
        const allValue = getFieldsValue();
        setFieldsValue({
          ...allValue,
          isShow: value,
        });
      };

      return {
        t,
        register,
        schemas,
        handleSubmit,
        closeModal,
        registerForm,
        location,
        handleCancel,
        googleKey,
        locationEdit,
        isEditMode,
        handleOpenMap,
        isDefaultSelect,
        handleUpdateSwitch,
      };
    },
  });
</script>
<style lang="less" scoped>
  .map-select {
    display: flex;
    flex-direction: row;
    gap: 0 20px;
  }
</style>
