<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="isAdding ? t('layout.map.selectScene') : t('routes.dashboard.scenesList')"
    @ok="handleSubmit"
    :width="850"
    submitOnReset
    @cancel="handleCancel"
    :closeFunc="handlecloseFunc"
  >
    <BasicTable @register="registerTable" v-if="!isAdding">
      <template #toolbar>
        <a-button type="primary" @click="handleAddScene">{{ t('layout.map.addScene') }}</a-button>
      </template>
      <template #sceneSource="{ record }">
        <span v-if="Number(record.sceneSource) === 3">{{ t('routes.scenes.4dkj') }}</span>
        <span v-else-if="Number(record.sceneSource) === 4">{{
          t('layout.map.sceneSource.4')
        }}</span>
        <span v-else-if="Number(record.sceneSource) === 5">{{
          t('layout.map.sceneSource.5')
        }}</span>
        <span v-else>{{ t('routes.scenes.4dkk') }}</span>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: t('layout.map.view'),
              tooltip: t('layout.map.view'),
              disabled: !record.webSite,
              onClick: () => handleSceneOpen(record),
            },
            {
              color: 'error',
              // icon: 'mage:edit-fill',
              label: t('layout.map.remove'),
              tooltip: t('layout.map.remove'),
              popConfirm: {
                title: t('layout.map.removeConfirm'),
                confirm: () => handleSceneDel(record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>

    <BasicTable
      @register="registerEditTable"
      v-else
      rowKey="num"
      :rowSelection="{
        type: 'checkbox',
        getCheckboxProps: (record) => ({
          disabled: isExistIds.includes(record.num),
          key: record.num,
        }),
      }"
    >
      <template #sceneSource="{ record }">
        <span v-if="Number(record.sceneSource) === 3">{{ t('routes.scenes.4dkj') }}</span>
        <span v-else-if="Number(record.sceneSource) === 4">{{
          t('layout.map.sceneSource.4')
        }}</span>
        <span v-else-if="Number(record.sceneSource) === 5">{{
          t('layout.map.sceneSource.5')
        }}</span>
        <span v-else>{{ t('routes.scenes.4dkk') }}</span>
      </template>
      <template #centerFooter> </template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { ListApi } from '/@/api/scene/list';
  import { AddSceneApi, DelSceneApi, ListAllGpsApi } from '/@/api/mapOpt/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { FormProps } from '/@/components/Form';

  import { BasicTable, useTable, BasicColumn, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useLocaleStore } from '/@/store/modules/locale';

  // import { disableCache } from '@iconify/iconify';
  const localeStore = useLocaleStore();
  const { t } = useI18n();

  export default defineComponent({
    components: { BasicModal, BasicTable, TableAction },
    props: {
      currentLatLng: {
        type: Object as PropType<{
          lat: number;
          lng: number;
        }>,
      },
    },
    emits: ['register', 'success', 'open-map', 'reload', 'cancel'],
    setup(props, { emit }) {
      // const { createMessage } = useMessage();
      const projectId = ref('');
      const isAdding = ref(false);
      const isExistIds = ref([]);
      const { createMessage } = useMessage();
      const isJA = computed(() => localeStore.getLocale === 'ja');
      const location = computed(() =>
        props.currentLatLng ? `${props.currentLatLng?.lat}, ${props.currentLatLng?.lng}` : '',
      );

      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'searchKey',
            label: t('routes.scenes.sceneName'),
            component: 'Input',
            colProps: {
              span: 10,
            },
          },
        ],
      };

      const columns: BasicColumn[] = [
        {
          title: 'ID',
          dataIndex: 'id',
          ifShow: false,
          fixed: 'left',
          width: 60,
        },
        {
          title: t('routes.scenes.sceneName'),
          dataIndex: 'sceneName',
          ellipsis: false,
          width: 80,
        },
        {
          title: t('routes.scenes.num'),
          dataIndex: 'num',
          width: 100,
        },
        {
          title: t('routes.devices.cameraType'),
          dataIndex: 'sceneSource',
          slots: { customRender: 'sceneSource' },
          width: 100,
        },
        {
          title: t('routes.scenes.snCode'),
          dataIndex: 'snCode',
          width: 100,
        },
        {
          title: t('common.operating'),
          dataIndex: '',
          slots: { customRender: 'action' },
          fixed: 'right',
          align: 'center',
          width: 150,
        },
      ];
      const [registerTable, { reload, getDataSource }] = useTable({
        // title: t('routes.dashboard.scenesList'),
        api: ListApi,
        columns: columns,
        resizeHeightOffset: 300,
        useSearchForm: false,
        showTableSetting: false,
        tableSetting: { fullScreen: true },
        showIndexColumn: false,
        rowKey: 'id',
        pagination: { pageSize: 10 },
        ellipsis: false,
        bordered: true,
        immediate: false,
        searchInfo: {
          projectId: projectId,
        },
      });

      const [registerEditTable, { getSelectRowKeys }] = useTable({
        // title: t('layout.map.selectScene'),
        api: ListAllGpsApi,
        columns: columns.filter((item) => item.title !== t('common.operating')),
        formConfig: searchForm,
        resizeHeightOffset: 300,
        useSearchForm: true,
        showTableSetting: false,
        tableSetting: { fullScreen: true },
        showIndexColumn: false,
        rowKey: 'num',
        pagination: { pageSize: 10 },
        ellipsis: false,
        bordered: true,
        searchInfo: {
          // status: -2,
          // isLaser: 1,
        },
      });

      function onDataReceive(data) {
        console.log('Data Received', data.id);
        projectId.value = data.id;

        reload();
      }
      const handleSubmit = async () => {
        if (isAdding.value) {
          const ids = getSelectRowKeys();
          console.log('handleSubmit', ids);
          if (ids.length > 0) {
            await AddSceneApi({
              projectId: Number(projectId.value),
              numList: ids,
            });
            isAdding.value = false;
            setTimeout(reload, 300);
          } else {
            createMessage.destroy();
            createMessage.error(t('modal.atLeastOne'));
          }
        } else {
          // debugger;
          closeModal();
        }
      };

      const handleCancel = async () => {
        emit('cancel');
      };
      const handleSceneDel = async (record: any) => {
        console.log('record', record.num);
        await DelSceneApi({
          projectId: Number(projectId.value),
          numList: [record.num],
        });
        reload();
      };
      const handlecloseFunc = () => {
        if (isAdding.value) {
          isAdding.value = false;
          isExistIds.value = [];
          setTimeout(reload, 500);
          return Promise.resolve(false);
        } else {
          return Promise.resolve(true);
        }
      };
      const handleSceneOpen = (record: any) => {
        const link = record.webSite + `&lang=${isJA.value ? 'ja' : 'zh'}`;
        console.log('record', link);
        window.open(link, '_blank');
      };
      const handleAddScene = () => {
        isAdding.value = true;
        const list = getDataSource();
        console.log('list', list);
        if (list.length > 0) {
          isExistIds.value = list.reduce((p, c) => p.concat(c['num']), []);
          console.log('isExistIds', isExistIds.value);
        }
      };

      return {
        t,
        register,
        handleSubmit,
        closeModal,
        location,
        handleCancel,
        registerTable,
        registerEditTable,
        isAdding,
        handleSceneDel,
        handlecloseFunc,
        handleSceneOpen,
        handleAddScene,
        isExistIds,
      };
    },
  });
</script>

<style scoped>
  :deep(.vben-basic-table-action.left) {
    justify-content: center;
  }
</style>
