<template>
  <div id="FormQuery" class="main-content main-content-padding flex-content">
    <h-card class="margin-right width-fixed has-card-head list-tree">
      <template #title>
        {{ t('FormDesign.common.modelList') }}
      </template>
      <template #extra>
        <!-- <h-button type="primary" icon="icp-add" @click="addCategory">
          {{ t('FormDesign.list.createCategory') }}
        </h-button> -->
        <h-b-button-group
          v-bind="menuProps"
          ref="menuRef"
          id="Template-buttonGroup-inline"
          :checkPermission="false"
          @filterItems="processButtonGroupData"
        />
        <!--  :processButtonGroupData="processButtonGroupData" -->
      </template>
      <h-b-tree
        id="FormQuery-queryTree"
        ref="treeRef"
        :header-title="t('FormDesign.common.modelList')"
        v-bind="treeProps"
        v-model:selectedKeys="treeProps.selectedKeys"
        v-model:expandedKeys="treeProps.expandedKeys"
        :show-line="false"
        :show-header="false"
        :show-tool-bar="false"
        :asyncQuery="false"
        :display-format="displayFormat"
        :fieldNames="{ title: 'text', key: 'value' }"
        :is-scroll-x="true"
        close-icon="PlusSquareOutlined"
        open-icon="MinusSquareOutlined"
        :useUniqueKey="true"
        :use-row-menu="true"
        :check-menu-permission="false"
        :custom-row-menu-show="customRowMenuShow"
        :on-before-right-click="beforeRightClick"
        @select="handleChange"
        @clickRightMenuItem="rightClick"
        queryType="local"
      ></h-b-tree>
    </h-card>
    <template v-if="cardVal">
      <component :is="getComponent()" ref="comRef" :propsData="cardVal"></component>
    </template>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, defineAsyncComponent, onMounted, createVNode } from 'vue';
import { useTree, useButtonGroup } from '@crami/bui-platform';
// import { useCardPane } from '@crami/bui-platform';
import { useI18n } from '@crami/locale';
import { commonApi } from '@remote/icpx-platform/commonApi';

import addNewCategoryVue from './components/AddNewCategoryDialog.vue';
import MoveToCategoryVue from './components/MoveToCategory.vue';
import { HModal, Icon, message } from '@crami/ui';
import { addFormCategory, deleteFormCategory, addModelToCategory } from '@/api/platform/form';
import { IBButtonGroupItem } from '@crami/bui-types';

export default defineComponent({
  name: 'FormQuery',
  setup: () => {
    // 多语言
    const { t } = useI18n();
    const searchValue = ref<string>('');

    // 左侧的应用仓库
    const cardVal = ref<string>('');

    //控制显示内容
    const displayFormat = function (data: any) {
      return data.text;
    };
    //获取显示内容
    const treeViewName = ref('P_SYS_CUSTORM_DATA_TREE_Menu');
    const contextMenu = ref([]);
    const [treeRef, treeProps, treeMethods] = useTree({
      //immediate:false,
      pageName: 'FormQuery',
      contextMenuApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          // type: 'tree',
          type: 'menuv2',
          name: treeViewName.value,
        },
      },
      treeDataApi: {
        url: '/api/system/modelForm/getFormCateTree',
        method: 'post',
        params: {
          lang: localStorage.getItem('lang') || 'zhs',
          connect: localStorage.getItem('connect'),
          companyId: localStorage.getItem('companyId'),
        },
      },
      treeChildrenDataApi: {
        url: '/api/system/modelForm/getFormCateChildren',
        method: 'post',
        params: commonApi().system.getGetTreeChildDataList.params,
      },

      immediate: false,
      beforeRequest: (params: any) => {
        return {
          ...params,
          treeViewName: treeViewName.value,
        };
      },
      beforeRequestChildren: (params: any, node: any) => {
        return {
          ...params,
          objectId: node.value,
        };
      },
      afterRequest: (data: any) => {
        // 树节点是否为叶子结点处理
        data.forEach(element => {
          element.isLeaf = !element.cate;
          element.children?.forEach(item => {
            item.isLeaf = !item.cate;
          });
        });
        return data;
      },
    });

    const [menuRef, menuProps, { getData }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 1,
      pageName: 'FormQuery',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: treeViewName.value, // commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });

    const processButtonGroupData = () => {
      const data: Array<IBButtonGroupItem> = [];
      const buttonData = getData();
      buttonData?.map(item => {
        if (item.name == 'addCategory') {
          data.push(item);
        }
      });
      return data;
    };
    const customRowMenuShow = function (node: any) {
      return true;
    };

    const handleChange = (selectedKeys, data) => {
      if (selectedKeys?.length <= 0) return;
      const node = data?.node?.dataRef;
      if (!node || node.cate) {
        cardVal.value = '';
        return;
      }
      cardVal.value = node.value;
    };
    // 获取当前页面组件，通过defineAsyncComponent的方式引入
    const selectType = ref();
    const getComponent = () => {
      if (cardVal.value) {
        const link = defineAsyncComponent(() => import('./FormQueryTable.vue'));
        return link;
      }
      return '';
    };
    // 根据数据显示不同操作按钮
    const beforeRightClick = function (data: any, node) {
      // TODO: any 数据类型定义
      console.log('beforeRightClick', data, node);
      const selectKeys = treeMethods.getSelectedKeys();
      if (!selectKeys || selectKeys.length <= 0 || cardVal.value != node.value) {
        treeMethods.setSelectedData([node.value]);
      }
      if (node.cate) {
        data.items = data.items.filter(
          item => item.name == 'editCategory' || item.name == 'deleteCategory',
        );
      } else {
        data.items = data.items.filter(item => item.name == 'moveToCategory');
      }
      return data;
    };
    const rightClick = (item: any, node: any) => {
      console.log('点击了右键rightClick', item, node);
    };
    const addCategory = (data?) => {
      // 新建分类、编辑分类
      console.log('addCategory', data);
      const node = data?.resultData[0];
      const pageConfig = {
        title: node ? t('FormDesign.list.editCategory') : t('FormDesign.list.createCategory'),
        content: addNewCategoryVue,
        componentProps: {
          categoryId: node?.value,
          name: node?.text,
        },
        width: 620,
        onOk: doAddCategory,
      };
      HModal.page(pageConfig);
    };
    // 添加分类
    const doAddCategory = (page, resolve) => {
      page
        .validate()
        .then(() => {
          const tempParams = page.getFormData();
          //  调用添加分类接口、编辑分类保存
          addFormCategory(tempParams.name, tempParams.categoryId).then(res => {
            if (res.code == 200) {
              treeMethods.refresh().then(() => {
                treeMethods.defaultHandle();
              });
              resolve(true);
            } else {
              message.error(res.msg);
            }
          });
        })
        .catch(err => {
          if (err?.errorFields?.length != 0) {
            // reject(true);
            console.info('---validate', err);
          } else {
            resolve(true);
          }
        });
    };
    const deleteCategory = data => {
      // 删除分类
      console.log('删除分类 deleteCategory', data);

      console.log('addCategory', data);
      const node = data?.resultData[0];
      HModal.confirm({
        closable: true,
        icon: createVNode(Icon, {
          name: 'icp-exclamation-circle-filled',
          size: 24,
          style: {
            float: 'left',
            marginRight: '8px',
          },
        }),
        title: t('FormDesign.common.deleteTitle'),
        content: t('FormDesign.common.deleteMsg2', { count: node?.text }),
        onOk() {
          return new Promise((resolve, reject) => {
            deleteFormCategory(node.value).then(data => {
              if (data.code == 200) {
                message.success(data.msg);
                treeMethods.refresh().then(() => {
                  treeMethods.defaultHandle();
                });
              } else {
                message.error(data.msg);
              }
              resolve(true);
            });
          }).catch(err => console.log('Oops errors!', err));
        },
      });
    };
    const doMoveTo = (page, resolve) => {
      page
        .validate()
        .then(() => {
          const temp = page.getFormData();
          //  调用移动到某分类的接口
          addModelToCategory(temp.categoryId, temp.objectType).then(res => {
            if (res.code == 200) {
              treeMethods.refresh().then(() => {
                treeMethods.defaultHandle();
              });
              resolve(true);
            } else {
              message.error(res.msg);
            }
          });
        })
        .catch(err => {
          if (err?.errorFields?.length != 0) {
            console.info('---validate', err);
          } else {
            resolve(true);
          }
        });
    };
    // 移动到某分类
    const moveToCategory = data => {
      // 移动到分类
      console.log('移动到分类 moveToCategory', data);
      console.log('addCategory', data);
      const node = data?.resultData[0];
      const pageConfig = {
        title: t('FormDesign.list.moveTo'),
        content: MoveToCategoryVue,
        componentProps: {
          objectType: node?.value,
        },
        width: 600,
        onOk: doMoveTo,
      };
      HModal.page(pageConfig);
    };

    onMounted(() => {
      // getTreePageData();
      treeMethods.refresh().then(() => {
        treeMethods.defaultHandle();
      });
    });
    return {
      t,
      searchValue,

      menuRef,
      menuProps,
      processButtonGroupData,

      cardVal,
      handleChange,
      getComponent,
      selectType,
      treeRef,
      treeProps,
      treeMethods,
      contextMenu,
      displayFormat,
      beforeRightClick,
      customRowMenuShow,
      rightClick,
      addCategory,
      deleteCategory,
      moveToCategory,
    };
  },
});
</script>
<style lang="less" scoped>
.left-list-card {
  :deep(.ant-card-body) {
    overflow: auto;
  }
}
</style>
