<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <BasicTable @register="registerTable">
    <template #tableTitle>
      <a-button preIcon="ant-design:container-outlined" type="primary" @click="handleSwitchPageType">更换版本</a-button>
      <a-button preIcon="ant-design:question-circle-outlined" type="primary" @click="handleHelp">帮助</a-button>
      <a-popconfirm title="确定从剪切板导入配置?" @confirm="handleImport">
        <a-button preIcon="ant-design:container-outlined" type="primary">导入</a-button>
      </a-popconfirm>
    </template>
    <template #action="{ record }">
      <a class="table-action-link mr-5px" @click="handleConfig(record)">配置</a>
      <a-popconfirm title="确定删除?" @confirm="handleDelete(record)">
        <a class="table-action-link">删除</a>
      </a-popconfirm>
    </template>
    <!-- <template #bodyCell="{ column, record }">
      <slot name="filterCell" v-bind="{ column, record }"></slot>
    </template> -->
  </BasicTable>
  <BasicModal @register="registerConfigModal" @ok="handleUpdate" title="配置文件编辑" defaultFullscreen>
    <CodeEditor class="h-100%" :value="configJSON" @change="editorChangeHandler" />
  </BasicModal>
  <BasicModal @register="registerPageTypeModal" @ok="handleUpdatePageType" title="一键修改模块版本">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  // 本页面是用于配置可配置首页的管理页面，更详细的文档见 /views/vent/home/configurable
  import { ref, provide, reactive, toRaw } from 'vue';
  import { BasicTable } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  // import { getToken } from '/@/utils/auth';
  // import { useGlobSetting } from '/@/hooks/setting';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { list, deleteById, saveOrUpdate } from '/@/api/sys/configurable';
  import { searchFormSchema, columns, formSchema, pageTypeFormSchema } from './configuration.data';
  import { message } from 'ant-design-vue';
  import { BasicModal } from '/@/components/Modal';
  import CodeEditor from '/@/components/CodeEditor/src/CodeEditor.vue';
  import { ModulePresetMap } from './options';
  import _ from 'lodash';
  /** @ts-ignore-next-line */
  import helpContext from './types?raw';
  import { Config } from './types';

  const formData = reactive<any>({});
  const isUpdate = ref(false);
  const deviceType = ref('');
  const formSchemaData = ref(formSchema);
  // const pageType = ref('');
  const configJSON = ref<Config>();

  provide('formSchema', formSchemaData);
  provide('isUpdate', isUpdate);
  provide('formData', formData);
  provide('deviceType', deviceType);

  // const glob = useGlobSetting();
  const [registerConfigModal, configModalCtx] = useModal();
  const [registerPageTypeModal, pageTypeModalCtx] = useModal();

  // 列表页面公共参数、方法
  const { tableContext } = useListPage({
    tableProps: {
      title: '配置列表',
      api: list,
      columns,
      showTableSetting: false,
      // size: 'small',
      // bordered: false,
      formConfig: {
        showAdvancedButton: true,
        // labelWidth: 100,
        labelAlign: 'left',
        labelCol: {
          xs: 24,
          sm: 24,
          md: 24,
          lg: 9,
          xl: 7,
          xxl: 5,
        },
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      striped: true,
      actionColumn: {
        width: 180,
      },
    },
  });

  const [registerForm, { validate }] = useForm({
    schemas: pageTypeFormSchema,
    showActionButtonGroup: false,
  });

  //注册table数据
  const [registerTable, { reload }] = tableContext;

  const saveOrUpdateHandler = async (params) => {
    // 如果是新增或者选择了覆盖配置选项的则初始化配置
    if (!isUpdate.value || params.allowCover) {
      params = {
        ...ModulePresetMap[params.desc],
        ...params,
      };
    }
    try {
      await saveOrUpdate(params, isUpdate.value);
      reload();
      message.success('保存成功');
    } catch (error) {
      message.error('保存失败，请联系管理员');
    }
  };

  function handleHelp() {
    configJSON.value = helpContext as any;
    configModalCtx.openModal();
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteById({ id: record.id }, reload);
  }

  function handleConfig(record) {
    Object.assign(formData, toRaw(record));
    configJSON.value = _.pick(formData, ['deviceType', 'pageType', 'moduleName', 'moduleData', 'showStyle']);
    configModalCtx.openModal();
  }

  /** 更新配置详情 */
  async function handleUpdate() {
    isUpdate.value = true;
    try {
      saveOrUpdateHandler({
        id: formData.id,
        ...configJSON.value,
      })
        .then(() => {
          message.success('保存成功');
        })
        .catch(() => {
          message.error('保存失败，请联系管理员');
        })
        .finally(() => {
          configModalCtx.closeModal();
        });
    } catch (e) {
      message.error(`无效信息：${e}`);
      console.error(e);
    }
  }

  function handleSwitchPageType() {
    pageTypeModalCtx.openModal();
  }

  /** 一件更改某个页面的所有模块版本 */
  async function handleUpdatePageType() {
    try {
      const params = await validate();
      const arr = await list({
        pageType: params.pageType,
      });
      await Promise.all(
        arr.records.map((r) => {
          return saveOrUpdate(
            {
              ...r,
              ...params,
            },
            true
          );
        })
      );
      pageTypeModalCtx.closeModal();
      reload();
    } catch (e) {
      message.error(`错误：${e}`);
      console.error(e);
    }
  }

  /** 从剪切板导入 */
  async function handleImport() {
    try {
      let text = '';
      // 浏览器会阻止用户在不安全的站点使用剪切板
      if (window.navigator.clipboard) {
        text = await window.navigator.clipboard.readText();
      } else {
        text = prompt('请粘贴JSON配置') || '';
      }
      const arr = JSON.parse(text);
      if (!Array.isArray(arr)) {
        throw '剪切板内容格式错误';
      }
      await Promise.all(
        arr.map((r) => {
          return saveOrUpdate(r, false);
        })
      );
      reload();
    } catch (e) {
      message.error(`错误：${e}`);
      console.error(e);
    }
  }

  function editorChangeHandler(val) {
    configJSON.value = JSON.parse(val);
  }
</script>

<style scoped lang="less">
  @ventSpace: zxm;
  @vent-table-no-hover: #00bfff10;

  :deep(.@{ventSpace}-table-cell-row-hover) {
    background: #264d8833 !important;
  }
  :deep(.@{ventSpace}-table-row-selected) {
    background: #268bc522 !important;
  }

  :deep(.@{ventSpace}-table-tbody > tr > td) {
    background-color: #0dc3ff05;
  }
  :deep(.jeecg-basic-table-row__striped) {
    td {
      background-color: @vent-table-no-hover !important;
    }
  }
  :deep(.@{ventSpace}-select-dropdown) {
    .@{ventSpace}-select-item-option-selected,
    .@{ventSpace}-select-item-option-active {
      background-color: #ffffff33 !important;
    }

    .@{ventSpace}-select-item:hover {
      background-color: #ffffff33 !important;
    }
  }
</style>
