<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="m-2 mr-0 w-1/4 xl:w-1/4 bg-white tree">
      <BasicTree
        ref="querysTreeRef"
        title="查询字段"
        checkable
        :treeData="props.queryTree"
        :checkedKeys="props.queryCheckedKeys"
        :defaultExpandAll="true"
        :fieldNames="{ key: 'key', title: 'label' }"
        @check="handleCheck"
      />
    </div>
    <BasicTable @register="queryTable" class="m-2 mr-0 w-3/8 xl:w-3/8 overflow-hidden">
      <template #toolbar>
        <div class="l-panel--item" size="mini">
          <a-radio-group
            v-model:value="config.queryType"
            size="mini"
            @change="radioChange"
            button-style="solid"
          >
            <a-radio-button :value="1">风格一</a-radio-button>
            <a-radio-button :value="2">风格二</a-radio-button>
          </a-radio-group>
        </div>
      </template>
    </BasicTable>
    <div class="m-2 mr-0 w-3/8 xl:w-3/8 overflow-hidden">
      <img style="width: 100%" :src="`/mars/img/onlineform/query${config.queryType}.jpg`" />
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, inject, defineProps, PropType, watch, onMounted, unref, nextTick } from 'vue';
  import { BasicTable, useTable } from '@/components/Table';
  import { PageWrapper } from '@/components/Page';
  import { BasicTree, TreeActionType } from '@/components/Tree';

  import { querys } from './config.data';

  // 定义props,树目录
  const props = defineProps({
    queryTree: {
      type: Object,
      default: () => ({}), // 设置默认值为一个空对象
    },
    queryCheckedKeys: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
  });

  // config
  const config: any = inject('formConfig');
  const querysData = ref(config.table.querys);
  // 展开全部
  const querysTreeRef = ref<Nullable<TreeActionType>>(null);

  const [queryTable, { reload }] = useTable({
    // canResize: 'true',
    // showIndexColumn: 'false',
    rowKey: 'key',
    dataSource: querysData,
    columns: querys(),
    bordered: true,
    pagination: false,
  });

  // 单选框的变动
  function radioChange(event) {
    config.queryType = event.target.value;
  }

  // 树的选择变动
  function handleCheck(keys) {
    querysData.value = props.queryTree[0].children.filter((item) => {
      return keys.includes(item.key);
    });
    config.table.querys = querysData.value;
    reload();
  }

  watch(
    () => config.table.querys,
    () => {
      querysData.value = config.table.querys;
    },
  );

  function fetch() {
    // 展开全部
    nextTick(() => {
      unref(querysTreeRef)?.expandAll(true);
      unref(querysTreeRef)?.setCheckedKeys(props.queryCheckedKeys);
    });
  }

  onMounted(() => {
    fetch();
  });
</script>

<style lang="less" scoped>
  .tree {
    overflow: auto;
    height: calc(100vh - 120px);
  }
</style>
