<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="60%"
    @ok="handleSubmit"
    @close="handleClose"
  >
    <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>
        <!-- ="{ model, field }" -->
        <template #detailAddr>
          <a-input
            class="live-drawer"
            v-bind="$attrs"
            v-model:value="detailAddr"
            :allowClear="true"
            placeholder=""
          >
            <template #addonAfter>
              <a-button type="primary" class="mr-10px" @click="handleMapSearch">
                {{ t('common.queryText') }}
              </a-button>
              <a-button @click="handleMapReset"> {{ t('common.resetText') }}</a-button>
            </template>
          </a-input>
        </template>
      </BasicForm>
    </div>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, nextTick, 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,
    uploadLiveVideoApi,
    // LiveSceneDeleteApi,
  } 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 detailAddr = ref('');
      const wrapRef = ref<HTMLDivElement | null>(null);
      interface AddressComponentType {
        city: string;
        district: string;
        province: string;
      }
      interface GeocodesType {
        adcode: string;
        addressComponent: AddressComponentType;
        formattedAddress: string;
        location: {
          lng: string;
          lat: string;
        };
      }
      let map;
      // Lat(120.262337, 30.178285),
      const defaultAddress = reactive({
        address: '山阴路688号恒隆广场B座1217',
        // address: '权晖花园21栋',
        lng: 120.262337,
        lat: 30.178285,
        location: ['33', '3301', '330109'],
        province: '浙江省',
        city: '杭州市',
        district: '萧山区',
      });
      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,
          // },
          required: true,
          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;
            },
          },
        },
        {
          field: 'sceneUrl',
          label: t('routes.scenes.sceneUrl'),
          component: 'ApiSelect',
          required: true,
          colProps: {
            span: 10,
          },
          componentProps: {
            api: getAllSceneApi,
          },
        },

        {
          field: 'location',
          label: '直播间位置',
          component: 'ApiCascader',
          componentProps: {
            api: () => {
              return CascaderData;
            },
            apiParamKey: 'provinceCode',
            dataField: 'children',
            labelField: 'name',
            valueField: 'code',
            // numberToString: true,
            isLeaf: (record) => {
              return !(record.levelType < 3);
            },
            onChange: (data) => {
              console.log('data', data);
              defaultAddress.location = data;
            },
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'detailAddr',
          label: t('routes.scenes.detailAddr'),
          component: 'Input',
          slot: 'detailAddr',
          colProps: {
            span: 10,
          },
        },
        {
          field: 'map',
          label: '地图位置',
          component: 'Input',
          slot: 'map',
          colProps: {
            span: 20,
          },
        },
        {
          field: 'picList',
          label: '直播间图片',
          component: 'Upload',
          componentProps: {
            api: uploadLiveApi,
            maxSize: 5,
            emptyHidePreview: true,
            maxNumber: 15,
            accept: ['image/*'],
            afterFetch: function (data) {
              Reflect.set(data, 'url', data.message.url);
              return data;
            },
          },

          colProps: {
            span: 20,
          },
        },
        {
          field: 'introduceVideo',
          label: '视频',
          component: 'Upload',
          componentProps: {
            api: uploadLiveVideoApi,
            maxSize: 5,
            emptyHidePreview: true,
            maxNumber: 15,
            accept: ['video/*'],
            afterFetch: function (data) {
              Reflect.set(data, 'url', data.message.video);
              return data;
            },
          },

          colProps: {
            span: 20,
          },
        },

        {
          field: 'contractPhone',
          component: 'Input',
          label: t('routes.scenes.contractPhone'),
          required: true,
          helpMessage: ['支持填写400（400-xxx-xxxx）热线、手机号等联系方式'],
        },
      ];
      // updateSchema, validate
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 120,
        schemas: schemas,
        showActionButtonGroup: false,
        baseColProps: { lg: 24, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

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

        initMap();
      });

      async function initMap() {
        await toPromise();
        await nextTick();
        const wrapEl = unref(wrapRef);
        console.log('wrapEl', wrapEl);
        if (!wrapEl) return;

        // center: [this.longitude || 120.262337, this.latitude || 30.178285],
        // const geocoder = new AMap.Geocoder({});

        const AMap = (window as any).AMap;

        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(defaultAddress.address, async function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // result中对应详细地理坐标信息
              console.log('result', result);
              const { geocodes } = result;
              if (geocodes?.length > 0) {
                const { adcode, addressComponent } = geocodes[0] as any as GeocodesType;
                defaultAddress.location = getCodeArray(adcode);

                await updateSchema({
                  field: 'location',
                  componentProps: {
                    displayRenderArray: [
                      addressComponent.province,
                      addressComponent.city,
                      addressComponent.district,
                    ],
                  },
                });
                await setFieldsValue({
                  location: defaultAddress.location,
                  // detailAddr: defaultAddress.address,
                });
                detailAddr.value = defaultAddress.address;
              }
            }
          });
          // const marker = new AMap.Marker({
          //   position: new AMap.LngLat(defaultAddress.lng, defaultAddress.lat),
          //   title: 'lala',
          // });
          // map && map.add(marker);
        });
      }

      function getCodeArray(code: string) {
        const pdCode = code.slice(0, 2);
        const cityCode = code.slice(2, 4);
        return [pdCode, cityCode, code];
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增直播间' : '编辑直播间'));

      async function handleMapSearch() {
        if (detailAddr.value?.length > 0) {
          console.log('detailAddr.value', detailAddr.value);
          const AMap = (window as any).AMap;
          console.log('adcode', defaultAddress.location[2]);
          AMap.plugin('AMap.Geocoder', function () {
            const geocoder = new AMap.Geocoder({
              // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
              city:
                defaultAddress.location[2] ||
                defaultAddress.location[1] ||
                defaultAddress.location[0],
              // adcode: defaultAddress.location[2],
              // citycode: '0571',
            });
            console.log('geocoder', geocoder);
            geocoder.getLocation(detailAddr.value, async function (status, result) {
              if (status === 'complete' && result.info === 'OK') {
                // result中对应详细地理坐标信息
                console.log('result', result);
                const { geocodes } = result;
                if (geocodes?.length > 0) {
                  // map.setCenter([lng, lat]);
                  const { adcode, addressComponent, formattedAddress, location } =
                    geocodes[0] as any as GeocodesType;
                  console.log('location', location);
                  map.setCenter(location);
                  const marker = new AMap.Marker({
                    position: new AMap.LngLat(location.lng, location.lat),
                    title: formattedAddress,
                  });
                  map.add(marker);
                  defaultAddress.location = getCodeArray(adcode);
                  await updateSchema({
                    field: 'location',
                    componentProps: {
                      displayRenderArray: [
                        addressComponent.province,
                        addressComponent.city,
                        addressComponent.district,
                      ],
                    },
                  });
                  await setFieldsValue({
                    location: defaultAddress.location,
                    // detailAddr: defaultAddress.address,
                  });
                  //   detailAddr.value = defaultAddress.address;
                }
              }
            });
          });
        }
      }
      async function handleMapReset() {
        defaultAddress.location = ['33', '3301', '330109'];
        detailAddr.value = '山阴路688号恒隆广场B座1217';
        handleMapSearch();
      }
      async function handleSubmit() {
        try {
          map && map.destroy();
          const values = await validate();
          console.log('values', values);
          resetFields();
          closeDrawer();
        } catch (error) {}
      }
      async function handleClose() {
        map && map.destroy();
        resetFields();
        closeDrawer();
      }

      return {
        detailAddr,
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        wrapRef,
        handleMapSearch,
        handleMapReset,
        handleClose,
        t,
      };
    },
  });
</script>
<style lang="less">
  .live-drawer {
    .ant-input-group-addon {
      padding-right: 0;
      background-color: transparent;
      border: none;

      button {
        font-size: 14px;
      }
    }
  }
</style>
