<template>
  <div class="p-4">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">{{ t('layout.map.addPro') }}</a-button>
      </template>
      <template #isShow="{ record }">
        <!-- gpsNum: {{ record.gpsNum }} -->
        <Switch
          :checked="record.isShow"
          :disabled="record.lat === null && record.lon === null"
          :checkedValue="1"
          :unCheckedValue="0"
          @click="handleUpdateSwitch(record)"
        />
      </template>

      <template #createTime="{ record }">
        <Time :value="record.createTime" mode="date" />
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              // color: 'warning',
              // icon: 'mage:edit-fill',
              label: t('layout.map.projectInfo'),
              tooltip: t('layout.map.projectInfo'),
              onClick: () => handleOpenInfo(record),
            },
            {
              // color: 'warning',
              // icon: 'mage:edit-fill',
              label: t('routes.dashboard.scenes'),
              tooltip: t('routes.dashboard.scenes'),
              onClick: () => handleOpenScene(record),
            },
            {
              // color: 'warning',
              // icon: 'mage:edit-fill',
              label: t('layout.map.mapMode'),
              tooltip: t('layout.map.mapMode'),
              onClick: () => handleOpenMap(record),
            },
            {
              color: 'error',
              // icon: 'mage:edit-fill',
              label: t('common.delText'),
              tooltip: t('common.delText'),
              popConfirm: {
                placement: 'left',
                title: t('common.delConfirm'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AddProjectModal
      @register="registerAddProjectModal"
      @open-map="handleSelectMap"
      @update-gps="(val) => (currentLatLng = val)"
      @reload="reload"
      @cancel="currentLatLng = { lat: null, lng: null }"
      :currentLatLng="currentLatLng"
    />
    <MapSelectModal
      @register="registerMapSelectModal"
      @update="handleMapUpdate"
      :open="isShowMapModal"
      :currentLatLng="currentLatLng"
    />
    <SceneModal @register="registerSceneModal" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, ref } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, FormProps } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Switch } from 'ant-design-vue';
  import { Time } from '/@/components/Time';
  import { useModal } from '/@/components/Modal';

  import { ListApi, MapOptType, DelMapOptApi, AddOptOrUpdateApi } from '/@/api/mapOpt/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  // import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { useGo } from '/@/hooks/web/usePage';
  import { useLocaleStore } from '/@/store/modules/locale';
  import AddProjectModal from './addProjectModal.vue';
  import MapSelectModal from './mapSelectModal.vue';
  import SceneModal from './sceneModal.vue';
  import { useRouter } from 'vue-router';

  const localeStore = useLocaleStore();

  const isJA = computed(() => localeStore.getLocale === 'ja');

  export default defineComponent({
    components: {
      BasicTable,
      AddProjectModal,
      MapSelectModal,
      SceneModal,
      Switch,
      Time,
      TableAction,
    },
    setup() {
      const [registerAddProjectModal, { openModal: openAddProjectModal }] = useModal();
      const [registerMapSelectModal, { openModal: openMapModal }] = useModal();
      const [registerSceneModal, { openModal: openSceneModal }] = useModal();
      const { createMessage } = useMessage();
      const isShowMapModal = ref(false);
      const go = useGo();
      const router = useRouter();
      const { t } = useI18n();
      const columns: BasicColumn[] = [
        {
          title: 'ID',
          dataIndex: 'id',
          ifShow: false,
          fixed: 'left',
          width: 60,
        },
        {
          title: t('layout.map.projectName'),
          dataIndex: 'projectName',
          width: 100,
        },
        {
          title: t('layout.map.createName'),
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: t('routes.staff.createTime'),
          dataIndex: 'createTime',
          slots: { customRender: 'createTime' },
          width: 200,
        },
        // {
        //   title: '求证测试（lat）',
        //   dataIndex: 'lat',
        //   width: 100,
        // },
        // {
        //   title: '求证测试（lon）',
        //   dataIndex: 'lon',
        //   width: 100,
        // },
        {
          title: t('layout.map.homeShow'),
          dataIndex: 'isShow',
          slots: { customRender: 'isShow' },
          width: 100,
        },

        {
          title: t('common.operating'),
          dataIndex: '',
          slots: { customRender: 'action' },
          fixed: 'right',
          align: 'center',
          width: isJA.value ? 200 : 200,
        },
      ];
      const currentLatLng = ref({
        lat: null,
        lng: null,
      });
      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'projectName',
            label: t('layout.map.projectName'),
            component: 'Input',
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
        ],
      };

      const [registerTable, { reload }] = useTable({
        title: t('layout.mapOpt.title'),
        api: ListApi,
        columns: columns,
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        tableSetting: { fullScreen: true },
        showIndexColumn: false,
        rowKey: 'id',
        pagination: { pageSize: 20 },
        ellipsis: false,
        bordered: true,
      });

      function handleCreate() {
        openAddProjectModal(true);
      }
      function handleSelectMap(latLng: { lat: number; lng: number }) {
        isShowMapModal.value = true;

        if (latLng?.lat && latLng?.lng) {
          console.warn('打开地图', latLng);
          openMapModal(true, latLng);
        } else {
          console.warn('打开地图-强刷');
          currentLatLng.value = undefined;
          openMapModal(true);
        }
      }
      function handleMapUpdate(coord: { lat: number; lng: number }) {
        console.log('handleMapUpdate', coord);
        if (coord) {
          currentLatLng.value = coord;
        } else {
          currentLatLng.value = undefined;
        }

        isShowMapModal.value = false;
      }
      async function handleDelete(record: MapOptType) {
        await DelMapOptApi({ id: record.id });
        createMessage.success(t('common.optSuccess'));
        reload();
      }
      async function handleUpdateSwitch(record: MapOptType) {
        const reveseValue = Math.abs(record.isShow - 1);
        record.isShow = reveseValue;
        await AddOptOrUpdateApi(record);
        reload();
      }
      function handleOpenScene(record: MapOptType) {
        console.log('handleOpenScene', record);
        openSceneModal(true, record);
      }
      function handleOpenMap(record: MapOptType) {
        console.log('record', record);
        const routeData = router.resolve({ name: 'Map', query: { projectId: record.id, type: 0 } });
        window.open(routeData.href, '_blank');
      }
      function handleOpenInfo(record: MapOptType) {
        console.log('record', record?.lat, record?.lon);
        if (record?.lat && record?.lon) {
          currentLatLng.value = {
            lat: record.lat,
            lng: record.lon,
          };
        }
        openAddProjectModal(true, record);
      }

      return {
        registerTable,
        createMessage,
        t,
        go,
        registerAddProjectModal,
        handleCreate,
        registerMapSelectModal,
        handleSelectMap,
        handleMapUpdate,
        currentLatLng,
        reload,
        handleDelete,
        handleUpdateSwitch,
        registerSceneModal,
        handleOpenScene,
        handleOpenMap,
        handleOpenInfo,
        isShowMapModal,
      };
    },
  });
</script>
<style scoped>
  :deep(.vben-basic-table-action.left) {
    justify-content: center;
  }
</style>
