<template>
  <div class="l-auto-window">
    <el-tabs v-model="pageActiveName" :stretch="true">
      <el-tab-pane :label="$t('布局设置')" name="tab01">
        <webcodeLayout />
      </el-tab-pane>
      <el-tab-pane v-if="config.layoutType == 2" :label="$t('左侧树形设置')" name="tab05">
        <webcodeLefttree :colslist="colslist" />
      </el-tab-pane>
      <el-tab-pane :label="$t('列表设置')" name="tab02">
        <webcodeColumns :columnsTree="columnsTree" :columnsCheckedKeys="columnsCheckedKeys" />
      </el-tab-pane>
      <el-tab-pane :label="$t('查询设置')" name="tab03">
        <webcodeQuery :queryTree="queryTree" :queryCheckedKeys="queryCheckedKeys" />
      </el-tab-pane>
      <el-tab-pane :label="$t('按钮设置')" name="tab04">
        <webcodeBtns :btnsTree="btnsTree" :btnsCheckedKeys="btnsCheckedKeys" />
      </el-tab-pane>
      <el-tab-pane :label="$t('地图设置')" name="tab05">
        <webcodeMaps />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
  import { ref, provide, defineExpose, watch, defineProps } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import WebcodeLayout from './config/layout.vue';
  import webcodeLefttree from './config/leftTree.vue';
  import webcodeColumns from './config/columns.vue';
  import webcodeQuery from './config/query.vue';
  import webcodeBtns from './config/btns.vue';
  import webcodeMaps from './config/maps.vue';
  import { functionGetPreviewForm, functionGetSchemeInfoEntity } from '@/api/demo/formScheme';

  // 定义props
  const props = defineProps({
    modalFormVerison: {
      type: Object,
      default: () => ({}), // 设置默认值为一个空对象
    },
    editData: {
      type: Object,
      default: () => ({}),
    },
    isEdit: {
      type: Boolean,
      default: () => false,
    },
    formVerison_now: {
      type: String,
      default: () => '',
    },
  });

  watch(
    () => props.modalFormVerison,
    (newVal, oldVal) => {
      if (newVal != oldVal) {
        if (typeof newVal == 'string') {
          validateSteps(newVal);
        }
      }
    },
  );

  // 初始数据
  let pageActiveName = 'tab01';
  // 左侧树形设置tree
  const colslist = ref([]);
  // 列表设置tree
  const columnsTree = ref([
    {
      label: '全选',
      children: [],
    },
  ]);
  // 列表设置Checked
  const columnsCheckedKeys: any = ref([]);
  // 查询设置tree
  const queryTree: any = ref([
    {
      label: '全选',
      children: [],
    },
  ]);
  // 查询设置Checked
  const queryCheckedKeys: any = ref([]);
  // 按钮设置tree
  const btnsTree: any = ref([]);
  // 按钮设置Checked
  const btnsCheckedKeys: any = ref([]);

  const notInColumns = [
    'Divider',
    'InputGuid',
    'MapGeom',
    'Upload',
    'slot',
    'Grid',
    'StrengthMeter',
    'Button',
    'Card',
    'FileUpload',
    'ImageUpload',
    'VideoUpload',
    'Tabs',
  ];

  const config_backups: any = {
    layoutType: 1,
    queryType: 1,
    left: {
      title: '左侧树形',
      colField: '',
      dataType: '1',
      dataIdKey: '',
      dataPIdKey: '',
      dataValueKey: '',
      dataLabelKey: '',
      colNames: [], // 数据源字段列表
      options: [], // 静态数据
      dataCode: '',
    },
    table: {
      isPage: true,
      columns: [],
      querys: [],
      btns: [],
      maps: {
        width: 50,
        chooseLayer: '',
        layerFields: {},
        isShowMap: false,
        isAllowAddPolygon: false,
        isAllowEditPolygon: false,
        isEnablePostionJump: false,
      },
      sidx: '',
      isDESC: false,
    },
    btns: [
      {
        label: '新增',
        id: 'Add',
        prop: 'Add',
        icon: 'ant-design:plus-outlined',
        isRowBtn: false,
        class: 'primary',
        sort: 0,
      },
      {
        label: '导入',
        id: 'Import',
        prop: 'Import',
        icon: 'ant-design:upload-outlined',
        isRowBtn: false,
        class: 'success',
        sort: 1,
      },
      {
        label: '导出',
        id: 'Export',
        prop: 'Export',
        icon: 'ant-design:download-outlined',
        isRowBtn: false,
        class: 'primary',
        sort: 2,
      },
      {
        label: '编辑',
        id: 'Edit',
        prop: 'Edit',
        icon: 'ant-design:edit-outlined',
        isRowBtn: true,
        class: 'success',
        sort: 3,
      },
      {
        label: '删除',
        id: 'Delete',
        prop: 'Delete',
        icon: 'ant-design:delete-outlined',
        isRowBtn: true,
        class: 'error',
        sort: 4,
      },
      {
        label: '详情',
        id: 'Details',
        prop: 'Details',
        icon: 'ant-design:align-center-outlined',
        isRowBtn: true,
        class: 'default',
        sort: 5,
      },
    ],
  };
  const config: any = ref();
  config.value = cloneDeep(config_backups);

  const formScheme: any = ref('');

  // 表单验证
  async function validateSteps(formVerison) {
    if (!formVerison) {
      return;
    }
    console.log('subbbb', formVerison);
    // 选中的历史记录表单
    let keyValue = typeof formVerison === 'string' ? formVerison : formVerison.value;
    let query: any = { keyValue: keyValue };
    const scheme: any = await functionGetPreviewForm(query);
    formScheme.value = JSON.parse(scheme.scheme);
    const columns: any = [];
    console.log('formScheme', formScheme.value);
    if (formScheme.value.formInfo.tabList && formScheme.value.formInfo.tabList.length > 1) {
      const arr: any = [];
      formScheme.value.formInfo.tabList.forEach((item, index) => {
        item.schemas.forEach((val) => {
          if (val.columns && val.component === 'Grid' && val.type === 'subTable') {
            val.columns.forEach((col) => {
              col.children.forEach((chil) => {
                arr.push(chil);
              });
            });
          } else if (val.component && val.component !== 'Grid') {
            arr.push(val);
          }
        });
      });
      formScheme.value.formInfo.schemas = arr;
    }
    if (formScheme.value.formInfo.tabList && formScheme.value.formInfo.tabList.length == 1) {
      const arr: any = [];
      formScheme.value.formInfo.tabList[0].schemas.forEach((item) => {
        if (item.columns && item.component === 'Grid' && item.type === 'subTable') {
          item.columns.forEach((col) => {
            col.children.forEach((chil) => {
              arr.push(chil);
            });
          });
        } else if (item.component && item.component !== 'Grid') {
          arr.push(item);
        }
      });
      formScheme.value.formInfo.schemas = arr;
    }
    // delete formScheme.value.formInfo.tabList;
    formScheme.value.formInfo.schemas.forEach((tab: any) => {
      if (!notInColumns.includes(tab.component)) {
        columns.push(tab);
      }
    });

    // 左侧树形设置
    colslist.value = columns.map((t) => {
      return { value: t.field, label: t.label };
    });

    // 列表设置-树
    columnsTree.value[0].children = [];
    columns.map((t) => {
      let temp: any = {
        key: t.field,
        label: t.label,
        value: t.label,
        width: 120,
        align: 'left',
        isMinWidth: false,
        component: t.component,
      };
      columnsTree.value[0].children.push(temp);
    });

    // 查询设置-树
    queryTree.value[0].children = [];
    queryTree.value[0].children = columns
      .filter(
        (t) =>
          !['Upload', 'Uploadimg', 'Password', 'Timerange', 'Datetimerange'].includes(t.component),
      )
      .map((t) => {
        // if (t.componentProps.options) {
        //   return {
        //     key: t.field,
        //     label: t.label,
        //     type: t.component,
        //     options: t.componentProps.options,
        //     componentProps: t.componentProps,
        //   };
        // } else {
        //   return {
        //     key: t.field,
        //     label: t.label,
        //     type: t.component,
        //     componentProps: t.componentProps,
        //   };
        // }
        return {
          key: t.field,
          label: t.label,
          type: t.component,
          componentProps: t.componentProps,
        };
      });

    // 常用按钮-树
    let query2: any = { id: scheme.schemeInfoId };
    const schemeInfo: any = await functionGetSchemeInfoEntity(query2);
    if (schemeInfo.formType === 1) {
      // 如果是视图表单就关闭部分按钮
      btnsTree.value = config.value.btns.filter((t) =>
        ['Import', 'Export', 'Details'].includes(t.id),
      );
    } else {
      btnsTree.value = config.value.btns;
    }

    // 编辑时的先前内容
    if (props.isEdit) {
      if (
        (typeof props.editData.record.formVerison == 'string'
          ? props.editData.record.formVerison
          : props.editData.record.formVerison.value) === props.formVerison_now
      ) {
        const editDataScheme = JSON.parse(props.editData.record.scheme);

        // 布局
        config.value.layoutType = editDataScheme.layoutType;
        // 查询设置-风格
        config.value.queryType = editDataScheme.queryType;
        // 左边树
        config.value.left = editDataScheme.left;
        // 常用按钮-树
        btnsTree.value.forEach((tree1, index) => {
          editDataScheme.table.btns.forEach((tree2) => {
            if (tree1.id === tree2.id) {
              btnsTree.value[index] = tree2;
            }
          });
        });
        // 列表设置-表
        config.value.table.columns = editDataScheme.table.columns;
        // 查询设置-表
        config.value.table.querys = editDataScheme.table.querys;
        // 常用按钮-表
        config.value.table.btns = editDataScheme.table.btns;
        // 地图设置-表（顺序：表单发布的值、表单设定的值、表单发布默认值）
        config.value.table.maps =
          editDataScheme.table.maps ||
          getDesignMapsGeom(formScheme.value.formInfo.schemas) ||
          cloneDeep(config_backups).table.maps;

        setCheckedKeys();
      } else {
        defaultConfig();
        setCheckedKeys();
      }
    } else {
      defaultConfig();
      setCheckedKeys();
    }

    pageActiveName = 'tab01';
  }

  function defaultConfig() {
    // 布局
    config.value.layoutType = 1;
    // 左侧-父子树：默认为[]
    colslist.value = [];
    // 常用按钮-树
    btnsTree.value = cloneDeep(config_backups).btns;
    // 列表设置-表
    config.value.table.columns = columnsTree.value[0].children;
    // 查询设置-表
    config.value.table.querys = queryTree.value[0].children;
    // 常用按钮-表
    config.value.table.btns = btnsTree.value;
    // 地图设置
    config.value.table.maps =
      getDesignMapsGeom(formScheme.value.formInfo.schemas) || cloneDeep(config_backups).table.maps;
  }

  function setCheckedKeys() {
    // 列表设置-树-选项
    columnsCheckedKeys.value = [];
    config.value.table.columns.forEach((t: any) => {
      columnsCheckedKeys.value.push(t.key);
    });
    // 查询设置-树-选项
    queryCheckedKeys.value = [];
    config.value.table.querys.forEach((t: any) => {
      queryCheckedKeys.value.push(t.key);
    });
    // 常用按钮-树-选项
    btnsCheckedKeys.value = [];
    config.value.table.btns.forEach((t: any) => {
      btnsCheckedKeys.value.push(t.id);
    });
  }

  // 获取设计的MapGeom的设定值
  function getDesignMapsGeom(schemas) {
    let mapData = null;
    schemas.forEach((e) => {
      if (mapData) {
        return mapData;
      }
      if (e.component == 'MapGeom') {
        mapData = e.mapSetData;
      } else if (e.component == 'Grid') {
        e.columns.forEach((item) => {
          mapData = getDesignMapsGeom(item.children);
        });
      }
    });
    return mapData;
  }

  provide('formConfig', config.value);

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