<template>
  <div v-if="state.isReload && state.pageType === PageTemplateType.GRID" :class="props.configId ? 'pt-2.5' : ''" style="height: 100%">
    <GridPage
      ref="gridPageRef"
      :platform-grid-config="state.pageConfig"
      :grid-before-request-data="gridBeforeRequestData"
      :grid-before-editor-data-submit="gridBeforeEditorDataSubmit"
    ></GridPage>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, nextTick, watch } from 'vue';
import { useRoute, onBeforeRouteUpdate } from 'vue-router';
import { axios, Environment, OptionComeFromEnum, FormTypeEnum, Tools } from 'platform-core';

import { getPageConfig, PageTemplateType } from './page.ts';
import GridPage from './grid/GridPage.vue';

const gridPageRef = ref();
const props = defineProps({
  configId: { type: String, default: '' },
  gridBeforeRequestData: { type: Function, default: () => {} },
  gridBeforeEditorDataSubmit: { type: Function, default: () => {} },
  gridInitLoadData: { type: Boolean, default: false },
});

const route = useRoute();
const state = reactive({
  isReload: true,
  pageType: '',
  pageConfig: {},
});

watch(
  () => props.configId,
  (newVal, oldVal) => {
    reload();
  },
);

// onBeforeRouteUpdate((to, from, next) => {
//   // if (!Tools.isEmpty(to.query?.id) && !Tools.isEmpty(from.query?.id) && to.query.id !== from.query.id) {
//   //   reload();
//   // }
//   next();
// });

const reload = () => {
  state.isReload = false;
  nextTick(() => {
    state.isReload = true;
    getConfig();
  });
};

const getJsonStr = async () => {
  // 两种接收参数的方式，一种是页面嵌套该组件为子组件，将configId传进来，另一种是通过路由将参数传进来。
  const result = await getPageConfig((props.configId ? props.configId : route.query.id) as string);
  if (result) {
    state.pageConfig = eval('(' + result.config + ')');
    state.pageType = result.type;
  }
};
const getSelectOptions = async (configItem) => {
  let options = [];
  if (configItem.fieldIsSelect && configItem.optionComeFrom === OptionComeFromEnum.数据字典) {
    // 数据字典选项值
  } else if (configItem.fieldIsSelect && configItem.optionComeFrom === OptionComeFromEnum.Java接口) {
    // java返回的选项值
  } else if (configItem.fieldIsSelect && configItem.optionComeFrom === OptionComeFromEnum.自定义数组) {
    // 自定义数组
    options = eval('(' + configItem.otherOptionValue + ')');
  } else if (configItem.fieldIsSelect && configItem.optionComeFrom === 'sql') {
    const requestParams = {
      method: 'POST',
      headers: { 'content-type': 'text/plain;charset=utf-8;' },
      data: configItem.otherOptionValue,
      url: Environment.apiContextPath('api/jdbc/fetchDataBySql'),
    };
    const resp = await axios(requestParams);
    options = resp.data;
  }
  return options;
};
const getConfig = async () => {
  const resp = await axios.get(Environment.apiContextPath('api/template/config/fetch/') + (props.configId ? props.configId : route.query.id));
  if (resp && resp.data && resp.data.templateConfig?.templatePageLoadType === 'JSON') {
    getJsonStr();
  } else if (resp && resp.data) {
    const templateConfig = resp.data.templateConfig;
    const templateGrid = resp.data.templateGrid;
    const templateGridFields = resp.data.templateGridFields;

    // 处理分页排序
    const tablePagination = {
      // sortBy: '',
      // descending: true,
      reqPageStart: 0,
      rowsPerPage: 10,
    };
    let defaultSortBy = undefined;
    if (templateGrid.defaultSortBy) {
      try {
        defaultSortBy = eval('(' + templateGrid.defaultSortBy + ')');
      } catch (error) {
        console.error('sortBy eval error!');
      }
      // tablePagination.sortBy = templateGrid.defaultSortBy;
      // tablePagination.descending = templateGrid.descending;
    }
    if (templateGrid.reqPageStart) {
      tablePagination.reqPageStart = templateGrid.reqPageStart;
    }
    if (templateGrid.rowsPerPage) {
      tablePagination.rowsPerPage = templateGrid.rowsPerPage;
    }

    // 处理按钮
    const tableButtons = <any>[];
    let configButton = false;
    if (templateGrid.buttons && templateGrid.buttons.length > 0) {
      templateGrid.buttons.forEach((item) => {
        if (item !== 'config') {
          tableButtons.push(item);
        } else {
          configButton = true;
        }
      });
    }

    // 处理紧凑模式
    const dense = {
      dense: false,
      denseToolbar: false,
      denseHeader: false,
      denseBody: false,
      denseBottom: false,
    };
    if (templateGrid.dense && templateGrid.dense.length > 0) {
      if (
        templateGrid.dense.findIndex((item) => {
          return item === 'dense';
        }) > -1
      ) {
        dense.dense = true;
      }
      if (
        templateGrid.dense.findIndex((item) => {
          return item === 'denseToolbar';
        }) > -1
      ) {
        dense.denseToolbar = true;
      }
      if (
        templateGrid.dense.findIndex((item) => {
          return item === 'denseHeader';
        }) > -1
      ) {
        dense.denseHeader = true;
      }
      if (
        templateGrid.dense.findIndex((item) => {
          return item === 'denseBody';
        }) > -1
      ) {
        dense.denseBody = true;
      }
      if (
        templateGrid.dense.findIndex((item) => {
          return item === 'denseBottom';
        }) > -1
      ) {
        dense.denseBottom = true;
      }
    }

    // 处理字段
    const addFormFields = <any>[];
    const queryFormFields = <any>[];
    const tableColumns = <any>[];
    let addFormField = {};
    let queryFormField = {};
    let tableColumn = {};

    for (let i = 0; i < templateGridFields.length; i++) {
      let item = templateGridFields[i];
      addFormField = {};
      queryFormField = {};
      tableColumn = {};
      const options = await getSelectOptions(item);
      if (item.editorShow) {
        addFormField = { ...addFormField, ...{ label: item.fieldLabel, name: item.fieldName } };
        if (item.editorFormType) {
          if (item.editorFormType === FormTypeEnum.下拉框) {
            addFormField = { ...addFormField, ...{ type: 'w-select' } };
            addFormField = { ...addFormField, ...{ options: options } };
          } else if (item.editorFormType === FormTypeEnum.多选下拉框) {
            addFormField = { ...addFormField, ...{ type: 'w-select' } };
            addFormField = { ...addFormField, ...{ options: options } };
          } else if (item.editorFormType === FormTypeEnum.数字框) {
            if (item.fieldPrecision) {
              addFormField = { ...addFormField, ...{ type: 'w-number', precision: item.fieldPrecision } };
            } else {
              addFormField = { ...addFormField, ...{ type: 'w-number' } };
            }
          } else if (item.editorFormType === FormTypeEnum.日期) {
            addFormField = { ...addFormField, ...{ type: 'w-date' } };
          } else if (item.editorFormType === FormTypeEnum.日期范围) {
            addFormField = { ...addFormField, ...{ type: 'dateRange' } };
          } else {
            addFormField = { ...addFormField, ...{ type: 'w-text' } };
          }
        } else {
          addFormField = { ...addFormField, ...{ type: 'w-text' } };
        }

        if (item.editorDefaultValue) {
          addFormField = { ...addFormField, ...{ defaultValue: item.editorDefaultValue } };
        }
        if (item.editorIsRequired) {
          addFormField = { ...addFormField, ...{ requiredIf: item.editorIsRequired } };
        }
        addFormFields.push(addFormField);
      }
      if (item.queryShow) {
        queryFormField = { ...queryFormField, ...{ label: item.fieldLabel, name: item.fieldName } };
        if (item.queryFormType) {
          if (item.queryFormType === FormTypeEnum.下拉框) {
            queryFormField = { ...queryFormField, ...{ type: 'w-select' } };
            queryFormField = { ...queryFormField, ...{ options: options } };
          } else if (item.queryFormType === FormTypeEnum.多选下拉框) {
            queryFormField = { ...queryFormField, ...{ type: 'w-select' } };
            queryFormField = { ...queryFormField, ...{ options: options } };
          } else if (item.queryFormType === FormTypeEnum.数字框) {
            if (item.fieldPrecision) {
              queryFormField = { ...queryFormField, ...{ type: 'w-number', precision: item.fieldPrecision } };
            } else {
              queryFormField = { ...queryFormField, ...{ type: 'w-number' } };
            }
          } else if (item.queryFormType === FormTypeEnum.日期) {
            queryFormField = { ...queryFormField, ...{ type: 'w-date' } };
          } else if (item.queryFormType === FormTypeEnum.日期范围) {
            queryFormField = { ...queryFormField, ...{ type: 'dateRange' } };
          } else {
            queryFormField = { ...queryFormField, ...{ type: 'w-text' } };
          }
        } else {
          queryFormField = { ...queryFormField, ...{ type: 'w-text' } };
        }
        if (item.queryDefaultValue) {
          queryFormField = { ...queryFormField, ...{ defaultValue: item.queryDefaultValue } };
        }
        if (item.queryIsRequired) {
          queryFormField = { ...queryFormField, ...{ requiredIf: item.queryIsRequired } };
        }
        if (item.queryOperator) {
          queryFormField = { ...queryFormField, ...{ queryOperator: item.queryOperator } };
        }
        queryFormFields.push(queryFormField);
      }
      if (item.tableShow) {
        tableColumn = { ...tableColumn, ...{ label: item.fieldLabel, name: item.fieldName } };
        if (item.tableSort) {
          tableColumn = { ...tableColumn, ...{ sortable: item.tableSort } };
        }
        if (item.tableColumnAlign) {
          tableColumn = { ...tableColumn, ...{ align: item.tableColumnAlign } };
        }
        if (item.tableColumnWidth) {
          tableColumn = { ...tableColumn, ...{ width: item.tableColumnWidth } };
        }
        if (item.fieldIsSelect) {
          tableColumn = {
            ...tableColumn,
            ...{
              format: (val, row) => {
                if (Array.isArray(options) && options.length > 0) {
                  let formatResult = val;
                  options.forEach((option: any) => {
                    if (option.value === val) {
                      formatResult = option.label;
                    }
                  });
                  return formatResult;
                } else {
                  return val;
                }
              },
            },
          };
        }
        tableColumns.push(tableColumn);
      }
    }

    // 根据配置组装数据对象
    state.pageType = templateConfig.templateType;
    state.pageConfig = {
      // templateGridId: templateGrid.id,
      title: templateGrid.title,
      toolbarActions: tableButtons,
      configButton: configButton,
      selection: templateGrid.selection,
      primaryKey: templateGrid.primaryKey,
      foreignKey: templateGrid.foreignKey,
      dataUrl: Environment.apiContextPath(templateGrid.dataUrl),
      fetchDataUrl: Environment.apiContextPath(templateGrid.fetchDataUrl + '?templateGridId=' + templateGrid.id),
      addDataUrl: Environment.apiContextPath(templateGrid.addDataUrl) + '/' + templateGrid.id,
      editDataUrl: Environment.apiContextPath(templateGrid.editDataUrl) + '/' + templateGrid.id + '/' + templateGrid.primaryKey,
      removeDataUrl: Environment.apiContextPath(templateGrid.removeDataUrl) + '/' + templateGrid.id + '/' + templateGrid.primaryKey,
      sortNo: templateGrid.sortNo,
      checkboxSelection: templateGrid.checkboxSelection,
      draggable: templateGrid.draggable,
      autoFetchData: templateGrid.autoFetchData,
      dense: dense.dense,
      denseToolbar: dense.denseToolbar,
      denseHeader: dense.denseHeader,
      denseBody: dense.denseBody,
      denseBottom: dense.denseBottom,
      stickyNum: templateGrid.stickyNum,
      tree: templateGrid.tree,
      treeRelationship: templateGrid.treeRelationship,
      // treeIcon:
      treeDefaultExpandAll: templateGrid.treeDefaultExpandAll,
      treeTickStrategy: templateGrid.treeTickStrategy,
      tickedField: templateGrid.tickedField,
      selectedField: templateGrid.selectedField,
      pageable: templateGrid.pageable,
      pagination: tablePagination,
      queryFormColsNum: templateGrid.queryFormColsNum,
      queryFormRowNum: templateGrid.queryFormRowNum,
      editor: {
        dialog: {
          width: '60%',
        },
        form: {
          colsNum: templateGrid.editorFormColsNum,
          fields: addFormFields,
        },
      },
      queryFormFields: queryFormFields,
      columns: tableColumns,
      sortBy: defaultSortBy,
    };
  }
};

const refresh = () => {
  gridPageRef.value.refresh();
};

onMounted(async () => {
  await getConfig();
  if (props.gridInitLoadData) {
    gridPageRef.value.refresh();
  }
});

defineExpose({
  refresh,
});
</script>
