<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <BasicTable @register="registerTable">
    <template #tableTitle>
      <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleAdd">新增</a-button>
      <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>
    </template>
    <template #action="{ record }">
      <a class="table-action-link" @click="handleConfig(record)">配置</a>
      <a class="table-action-link" @click="handleEdit(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>
  <DeviceModal @register="registerModal" @save-or-update="saveOrUpdateHandler" :showTab="false" :deviceType="deviceType" />
  <BasicModal @register="registerConfigModal" @ok="handleUpdate" title="配置文件编辑" defaultFullscreen>
    <CodeEditor v-model:value="configJSON" />
  </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 DeviceModal from '../comment/DeviceModal.vue';
  // import { getToken } from '/@/utils/auth';
  // import { useGlobSetting } from '/@/hooks/setting';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { list, deleteById, saveOrUpdate } from './configuration.api';
  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';

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

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

  // const glob = useGlobSetting();
  const [registerModal, { openModal, closeModal }] = useModal();
  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);
      closeModal();
      reload();
      message.success('保存成功');
    } catch (error) {
      message.error('保存失败，请联系管理员');
    }
  };

  /**
   * 新增事件
   */
  function handleAdd() {
    for (let key in formData) {
      delete formData[key];
    }
    isUpdate.value = false;
    openModal(true);
  }

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

  /**
   * 编辑事件
   */
  function handleEdit(record) {
    isUpdate.value = true;
    Object.assign(formData, toRaw(record));
    openModal(true, { formData }, false);
  }

  /**
   * 删除事件
   */
  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,
        ...JSON.parse(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);
    }
  }
</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>
