<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTree
      class="w-1/4 m-4 mr-0 overflow-hidden bg-white xl:w-1/5"
      v-if="treeVisible"
      ref="asyncExpandTreeRef"
      :title="treeTitle"
      toolbar
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      loadData
      :actionList="actionList"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'value', title: 'label' }"
      :defaultExpandAll="true"
      @select="handleSelect"
    />
    <BasicTable @register="registerTable" class="flex-1">
      <template #toolbar>
        <div v-for="(item, index) in btnArr" :key="index">
          <a-button :type="item.class" @click="handleClickForm(item.prop)">{{
            item.label
          }}</a-button>
        </div>
      </template>
    </BasicTable>
    <CallModal @success="submitsuccess" @register="registerModal" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, ref, nextTick, unref, h } from 'vue';
  import { useRoute } from 'vue-router';
  import { BasicTable, useTable, BasicColumn } from '@/components/Table';
  import { BasicTree, TreeItem, TreeActionItem, TreeActionType } from '@/components/Tree';
  import { getFormsDesignData, getFormsPageData, delFormsData } from '@/api/formrender/index';
  import { getOutKeyList } from '@/api/formdesign/index';
  // import { searchFormSchema } from './index.data';
  import { PageWrapper } from '@/components/Page';
  import { cloneDeep } from 'lodash-es';
  import { IFormConfig } from '../../form-design/typings/v-form-component';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import CallModal from './CallModal.vue';

  const { createConfirm, createMessage } = useMessage();
  const route = useRoute();
  const btnArr: any = [
    { label: '新增', prop: 'Add', class: 'primary' },
    { label: '编辑', prop: 'Edit', class: 'success' },
    { label: '删除', prop: 'Delete', class: 'error' },
    { label: '详情', prop: 'Details', class: 'default' },
  ];
  const treeTitle: any = ref('树形');
  const treeVisible: any = ref(false);
  const paramsId: any = ref();
  const designData: any = ref();
  const searchValue: any = ref();
  const addParamsArr: any = ref([]);
  const paramsCode = route.query.code;
  const callColumns: BasicColumn[] = [];

  const treeData = ref<TreeItem[]>([]);
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  const actionList: TreeActionItem[] = [];
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, setColumns, getSelectRows, clearSelectedRowKeys }] = useTable({
    title: '表单列表',
    api: getFormsPageData,
    // rowKey: 'f_Id',
    columns: callColumns,
    formConfig: {
      labelWidth: 120,
      // schemas: searchFormSchema,
    },
    rowSelection: {
      type: 'radio',
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    beforeFetch: (data) => {
      // 接口请求前 参数处理
      var temp = {
        id: paramsId.value,
        paginationInputDto: {
          page: data.page,
          rows: data.limit,
          keyWord: data.key,
        },
        queryJson: searchValue.value,
      };
      return temp;
    },
    afterFetch: () => {
      const rel = designData.value;
      let arr: any = [];
      if (rel.primaryKey) {
        rel.db.forEach((val) => {
          let params = {
            dbCode: rel.dbCode,
            tableNames: val.name,
          };
          let chlidKey: any = ref();
          if (val.type === 'chlid') {
            getOutKeyList(params).then((res: Recordable) => {
              if (res[0]) {
                res[0].db_codecolumnsList.forEach((item) => {
                  if (item.isPrimaryKey == 1) {
                    chlidKey.value = item.dbColumnName;
                  }
                });
              }
            });
          }
          rel.formInfo.schemas.forEach((item) => {
            if (
              item.componentProps.dataTable == val.name &&
              rel.primaryKey == item.componentProps.fieldName
            ) {
              arr.push({
                type: val.type,
                field: item.field,
              });
            }
            if (
              val.type == 'chlid' &&
              val.name == item.componentProps.dataTable &&
              chlidKey.value == item.componentProps.fieldName
            ) {
              arr.push({
                type: val.type,
                field: item.field,
              });
            }
          });
        });
      }
      addParamsArr.value = [...new Set(arr)];
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });

  const formConfig = ref<IFormConfig>({
    // 表单配置
    schemas: [],
    layout: 'horizontal',
    labelLayout: 'flex',
    labelWidth: 100,
    labelCol: {},
    wrapperCol: {},
    currentItem: {
      component: '',
      componentProps: {},
    },
    activeKey: 1,
    status: 'Add',
  });

  const handleClickForm = (status) => {
    const config = cloneDeep(formConfig.value);
    const rows = getSelectRows();
    const query: any = ref({
      id: paramsId.value,
      key: designData.value.primaryKey,
      // key: 'f_id',
      keyValue: null,
    });
    const str: any = ref(addParamsArr.value[0].field);
    // const str: any = ref('_input_guid_43');
    addParamsArr.value.forEach((item) => {
      if (item.type == 'main') {
        str.value = item.field;
      }
    });

    if (rows.length > 0) {
      query.value.keyValue = rows[0][str.value];
    }
    switch (status) {
      case 'Add':
        openModal(true, {
          isDetail: false,
          isUpdate: false,
          tab: config.schemas,
          query: query.value,
          addParams: addParamsArr.value,
        });
        break;
      case 'Edit':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据进行编辑');
        }
        openModal(true, {
          isDetail: false,
          isUpdate: true,
          tab: config.schemas,
          record: rows[0],
          query: query.value,
        });
        break;
      case 'Delete':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据进行删除');
        }
        createConfirm({
          iconType: 'info',
          title: '删除',
          content: '确定要删除该条数据？',
          onOk: async () => {
            delFormsData(query.value).then((res) => {
              if (res) {
                createMessage.success('删除成功', 2);
                setTimeout(() => {
                  clearSelectedRowKeys();
                  reload();
                }, 100);
              } else {
                createMessage.error('删除失败', 2);
              }
            });
          },
        });
        break;
      case 'Details':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据查看详情');
        }
        openModal(true, {
          isDetail: true,
          isUpdate: false,
          tab: config.schemas,
          record: rows[0],
          query: query.value,
        });
        break;
      case 'Import':
        break;
      case 'Export':
        break;
      default:
        break;
    }
  };
  function handleSelect(selectedKeys: any, selected: any) {
    const rel = selected.node.dataRef;
    const obj: any = {};
    obj[rel.key] = rel.value;
    searchValue.value = JSON.stringify(obj);
    reload();
  }

  function getPublicForm() {
    let params = {
      code: paramsCode,
    };
    getFormsDesignData(params).then((res: Recordable) => {
      let columnObj = JSON.parse(res.entity.scheme);
      let formObj = JSON.parse(res.formScheme.scheme);
      paramsId.value = res.formScheme.id;

      if (columnObj.table.columns) {
        columnObj.table.columns.forEach((item) => {
          callColumns.push({
            title: item.label,
            dataIndex: item.key,
          });
        });
      }
      callColumns.forEach((item) => {
        formObj.formInfo.schemas.forEach((val) => {
          if (item.dataIndex == val.field && val.componentProps.options) {
            item.customRender = ({ record }) => {
              const text: any = val.componentProps.options.filter(
                (price) => price.value == record[val.field],
              );
              if (text[0]) {
                return h(() => text[0].label);
              }
            };
          }
        });
      });
      setColumns(callColumns);
      reload();
      if (columnObj.left.options.length > 0) {
        treeData.value = columnObj.left.options;
        treeTitle.value = columnObj.left.title;
        treeVisible.value = true;
      } else {
        treeVisible.value = false;
      }
      designData.value = formObj;
      // 展开全部
      nextTick(() => {
        unref(asyncExpandTreeRef)?.expandAll(true);
      });
      formConfig.value.schemas = formObj.formInfo.schemas;
    });
  }
  //弹窗确定后返回调用
  function submitsuccess() {
    reload();
  }

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