<template>
  <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
    <div class="w-full">
      <BasicTable @register="registerTable" ref="tableRef" isMenuTable>
        <template #toolbar v-if="menuCode">
          <a-button @click="handleRefresh" v-auth="`${menuCode}:refresh`" type="primary">{{
            t('刷新')
          }}</a-button>
          <a-button v-auth="`${menuCode}:qrcode`" type="primary" @click="handleOpenCode">{{
            t('对外二维码')
          }}</a-button>
          <a-button v-auth="`${menuCode}:link`" type="primary" @click="handleOpenLink">{{
            t('对外链接')
          }}</a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <TableAction
              :actions="[
                {
                  label: '查看',
                  auth: `${menuCode}:view`,
                  onClick: handleView.bind(null, record),
                },
                {
                  label: '删除',
                  auth: `${menuCode}:delete`,
                  color: 'error',
                  onClick: handleDelete.bind(null, record),
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </div>
    <a-modal
      v-model:visible="linkVisible"
      title="调查问卷对外链接"
      :bodyStyle="{
        height: '200px',
        display: 'flex',
        'align-items': 'center',
        'justify-content': 'center',
      }"
      :footer="null"
    >
      <p>{{ `${link}/link` }}</p>
    </a-modal>
    <a-modal v-model:visible="codeVisible" title="调查问卷二维码" :footer="null">
      <QrCode :value="`${link}/qrcode`" :width="200" v-if="link" class="text-center" />
    </a-modal>
    <PreviewModal @register="registerModal" :isDesignPreview="false" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicColumn, BasicTable, FormSchema, TableAction, useTable } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { onMounted, ref, unref, computed, createVNode } from 'vue';
  import { useRouter } from 'vue-router';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { QuestionnaireConfig } from '/@/model/generator/generatorConfig';
  import { ColumnConfig } from '/@/model/generator/listConfig';
  import { deleteQnExecute, getQnExecuteList } from '/@/api/questionnaire/template';
  import { getQuestionnaireInfo } from '/@/api/questionnaire/design';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { useGlobSetting } from '/@/hooks/setting';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { Modal } from 'ant-design-vue';
  import { useTitle } from '@vueuse/core';
  import { QrCode } from '/@/components/Qrcode/index';
  import PreviewModal from '../design/components/PreviewModal.vue';
  import { getAppEnvConfig } from '/@/utils/env';

  const { setTitle } = useTabs();
  const { title } = useGlobSetting();
  const { currentRoute } = useRouter();
  const { path } = unref(currentRoute);
  const { filterColumnAuth } = usePermission();

  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '关键字',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入关键字',
      },
    },
    {
      field: 'create_date',
      label: '提交时间',
      component: 'RangePicker',
      colProps: { span: 8 },
      componentProps: {
        format: 'YYYY-MM-DD',
      },
    },
  ];

  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);

  let columns: BasicColumn[] = []; //列表配置
  const formWidth = ref<number>(800); // 弹窗、抽屉宽度
  const pkField = ref<string>(''); //主表主键
  const tableRef = ref();

  const menuId = ref('');
  const menuName = ref('');
  const menuCode = ref('');
  const listTitle = ref('');
  const formJson = ref();

  const linkVisible = ref(false);
  const codeVisible = ref(false);

  const paths = path.split('/');
  menuId.value = paths.length > 0 ? paths[paths.length - 1] : '';
  const filterColumns = ref<BasicColumn[]>([]);
  const link = computed(() => {
    return `${getAppEnvConfig().VITE_GLOB_QN_LINK_URL}/#/questionnaireForm/${menuId.value}`;
  });
  const [registerModal, { openModal }] = useModal();

  const [registerTable, { reload, setProps }] = useTable({
    title: '',
    columns,
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      fieldMapToTime: [['create_date', ['startTime', 'endTime'], 'YYYY-MM-DD', true]],
      showResetButton: false,
    },
    beforeFetch: (pageParams) => {
      const newParams = {
        id: menuId.value,
        ...pageParams,
        order: pageParams.order,
        field: pageParams.field,
      };
      return newParams;
    },
    afterFetch: () => {},
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 100,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
  });

  function handleRefresh() {
    reload();
  }

  function handleView(record: Recordable) {
    openModal(true, { formJson: formJson.value, dataId: record.id, id: menuId.value });
  }

  async function handleDelete(record: Recordable) {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      onOk() {
        deleteQnExecute({ id: menuId.value, dataId: record[pkField.value] }).then((_) => {
          handleSuccess();
          notification.success({
            message: t('提示'),
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }

  function handleSuccess() {
    reload();
  }

  function handleOpenLink() {
    linkVisible.value = true;
  }
  function handleOpenCode() {
    codeVisible.value = true;
  }

  onMounted(async () => {
    const data = await getQuestionnaireInfo(menuId.value as string);
    const configJson = JSON.parse(data.content) as QuestionnaireConfig;
    formJson.value = configJson.formJson;
    menuName.value = configJson.menuConfig.name;
    menuCode.value = configJson.menuConfig.code;
    //设置Tab标题
    setTitle(menuName.value);
    //设置浏览器标题
    useTitle(` ${menuName.value} - ${title} `);

    listTitle.value = menuName.value;

    const mainTable = configJson.tableStructureConfigs?.find((item) => item.isMain);
    pkField.value = mainTable?.pkField || 'id';

    //构建表单Props
    formWidth.value = configJson.formJson.config.formWidth || 800;
    columns = ConvertColumnConfigToBasicColumn(configJson.columnConfigs);
    filterColumns.value = filterColumnAuth(columns);
    //重新设定table组件props
    setProps({
      api: getQnExecuteList,
      title: listTitle.value,
      rowKey: pkField.value,
      columns: filterColumns.value,
    });
    reload();
  });

  function ConvertColumnConfigToBasicColumn(columnConfigs: ColumnConfig[]): BasicColumn[] {
    return columnConfigs.map((config) => {
      const column: BasicColumn = {
        dataIndex: config.columnName,
        title: config.label,
        sorter: true,
      };
      if (config.alignType) column.align = config.alignType as any;
      if (!config.autoWidth && config.columnWidth) column.width = Number(config.columnWidth);
      if (config.componentProps?.datasourceType === 'staticData') {
        column.customRender = ({ record }) => {
          const staticOptions = config.componentProps?.staticOptions;
          if (config.componentType === 'checkbox') {
            const valArr = record[config.columnName]?.split(',');
            return staticOptions
              .filter((x) => valArr.includes(x.value))
              ?.map((x) => x.label)
              .toString();
          }
          return staticOptions.filter((x) => x.value == record[config.columnName])[0]?.label;
        };
      }
      return column;
    });
  }
</script>
