<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="60%"
    @ok="handleSubmit"
  >
    <div class="entry-x">
      <BasicForm @register="registerForm">
        <template #map>
          <!-- <Card style="width: 300px; height: 300px"> -->
          <div ref="wrapRef" style="width: 100%; height: 400px"></div>
          <!-- </Card> -->
        </template>
      </BasicForm>
    </div>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, nextTick, onMounted, reactive } from 'vue';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form/index';
  // import { Card } from 'ant-design-vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  // import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { brandTypeListApi, uploadLiveApi, getAllSceneApi } from '/@/api/scene/live';
  import { data as CascaderData } from '/@/utils/cascaderData';

  import { useScript } from '/@/hooks/web/useScript';
  const A_MAP_URL = 'https://webapi.amap.com/maps?v=2.0&key=e661b00bdf2c44cccf71ef6070ef41b8';
  // const A_MAP_URL = 'https://webapi.amap.com/maps?v=2.0&key=5a2d384532ae531bf99bd8487c4f03d2';
  // const A_MAP_URL = 'https://webapi.amap.com/maps?v=1.4.10&key=e661b00bdf2c44cccf71ef6070ef41b8';

  //webapi.amap.com/maps?v=1.4.10&key=e661b00bdf2c44cccf71ef6070ef41b8

  // Card
  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup() {
      const isUpdate = ref(true);
      const wrapRef = ref<HTMLDivElement | null>(null);
      const defaultAddress = reactive({
        address: '山阴路688号恒隆广场B座1217',
        longt: '山阴路688号恒隆广场B座1217',
      });
      console.log('defaultAddress', defaultAddress);
      const { toPromise } = useScript({ src: A_MAP_URL });

      const { t } = useI18n();
      // const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'type',
          label: t('routes.scenes.liveType'),
          component: 'ApiSelect',
          // colProps: {
          //   xl: 5,
          //   xxl: 5,
          // },
          componentProps: {
            api: brandTypeListApi,
            resultField: 'list',
            labelField: 'name',
            valueField: 'id',
            params: {
              page: 1,
              limit: 1000,
            },
          },
        },
        {
          field: 'name',
          component: 'Input',
          label: t('routes.scenes.liveName'),

          required: true,
        },
        {
          field: 'appListPicUrl',
          label: t('routes.scenes.appListPicUrl'),
          component: 'Upload',
          helpMessage: '推荐大小：400 * 400 像素',
          required: true,
          colProps: {
            span: 10,
          },
          componentProps: {
            api: uploadLiveApi,
            maxgoodsNumber: 1,
            afterFetch: function (data) {
              Reflect.set(data, 'url', data.message.url);
              return data;
            },
            onChange: async () => {
              await validateFields(['wapBannerUrl']);
            },
          },
        },
        {
          field: 'sceneUrl',
          label: t('routes.scenes.sceneUrl'),
          component: 'ApiSelect',
          required: true,
          colProps: {
            span: 10,
          },
          componentProps: {
            api: getAllSceneApi,
          },
        },
        // :fieldNames="{ label: 'name', value: 'code', children: 'children' }"
        {
          field: 'location',
          label: '直播间位置',
          component: 'ApiCascader',
          labelWidth: 100,
          componentProps: {
            api: () => {
              return CascaderData;
            },
            apiParamKey: 'provinceCode',
            dataField: 'children',
            labelField: 'name',
            valueField: 'code',
            isLeaf: (record) => {
              return !(record.levelType < 3);
            },
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'map',
          label: '地图位置',
          component: 'Input',
          labelWidth: 100,
          slot: 'map',
          colProps: {
            span: 20,
          },
        },
      ];
      // updateSchema, validate
      const [registerForm, { resetFields, setFieldsValue, validateFields }] = useForm({
        labelWidth: 120,
        schemas: schemas,
        showActionButtonGroup: false,
        baseColProps: { lg: 24, md: 24 },
      });
      // closeDrawer;
      const [registerDrawer, { setDrawerProps }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          console.log('data.record', data);

          setFieldsValue({
            ...data.record,
          });
        }
        initMap();
        // updateSchema({
        //   field: 'parentId',
        //   componentProps: {
        //     treeData,
        //   },
        // });
      });

      async function initMap() {
        await toPromise();
        await nextTick();
        const wrapEl = unref(wrapRef);
        console.log('wrapEl', wrapEl);
        if (!wrapEl) return;
        const AMap = (window as any).AMap;
        console.log('AMap', AMap);
        // center: [this.longitude || 120.262337, this.latitude || 30.178285],
        // const geocoder = new AMap.Geocoder({});
        const map = new AMap.Map(wrapEl, {
          zoom: 18,
          center: [120.262337, 30.178285],
          viewMode: '3D',
          resizeEnable: true,
          floorControl: true,
          showIndoorMap: true,
        });
        AMap.plugin('AMap.Geocoder', function () {
          var geocoder = new AMap.Geocoder({
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
            city: '010',
          });

          geocoder.getLocation('北京市海淀区苏州街', function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // result中对应详细地理坐标信息
              console.log('result', result);
            }
          });
        });

        const marker = new AMap.Marker({
          position: new AMap.LngLat(120.262337, 30.178285),
          title: 'lala',
        });
        map.add(marker);
      }
      onMounted(() => {
        initMap();
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增直播间' : '编辑直播间'));

      async function handleSubmit() {}

      return { registerDrawer, registerForm, getTitle, handleSubmit, wrapRef };
    },
  });
</script>
