<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="isEditMode ? t('layout.map.projectInfo') : t('layout.map.addPro')"
    :minHeight="380"
    :width="550"
    destroyOnClose
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="p-20px">
      <BasicForm @register="registerForm">
        <template #isShow="{ model, field }">
          <!-- isDefaultSelect:{{ isDefaultSelect }}<br />
          disabled:
          {{ isDefaultSelect === 1 ? !currentLatLng.lat && !currentLatLng.lng : !model['gpsNum']
          }}<br /> -->

          <Switch
            :checked="model[field]"
            :disabled="
              isDefaultSelect === 1 ? !currentLatLng.lat && !currentLatLng.lng : !model['gpsNum']
            "
            @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 | null;
          lng: number | null;
        }>,
        default: () => {
          return {
            lat: null,
            lng: null,
          };
        },
      },
    },
    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: {
            ellipsis: true,
            allowClear: false,
            onChange: function (value: number) {
              isDefaultSelect.value = value;
              console.log('onChange');
            },
            onSelect: function (value: number) {
              emit('update-gps', { lat: null, lng: null });
              if (value === 1) {
                const allData = getFieldsValue();
                setFieldsValue({
                  ...allData,
                  gpsNum: '',
                });
                console.log('清-gpsNum');
              }
            },
            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').map((item: any) => {
                if (item.title && item.title.length > 22) {
                  item.title = String(item.title).substring(0, 22) + '...';
                }
                return item;
              });

              console.log('data.list', data);

              return data;
            },
            resultField: 'list',
            labelField: 'title',
            valueField: 'num',
            showSearch: true,
            optionFilterProp: 'label',
            immediate: true,
            listHeight: 160,
            allowClear: true,
            ellipsis: 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,
            },
          },
          colProps: {
            span: 24,
          },
          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?.lat && props.currentLatLng?.lng
          ? `${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 || null,
          lon: props.currentLatLng?.lng || null,
          alt: 0,
        };
        if (!isEditMode.value) {
          delete pro.id;
        }
        if (!pro.lat && !pro.lon) {
          console.log('没有地理信息');
          pro.isShow = 0;
        }
        //@ts-ignore
        if (pro.tempSlect === 2 && !pro.gpsNum) {
          pro.lat = null;
          pro.lon = null;
          pro.isShow = 0;
        }
        console.log('save', pro);
        await AddOptOrUpdateApi(pro);
        closeModal();
        resetFields();
        isDefaultSelect.value = 1;
        emit('reload');
        setTimeout(() => {
          console.warn('强制重置GPS');
          emit('update-gps', { lat: null, lng: null });
        }, 300);
      };

      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>
