<template>
  <div class="main-content-item-right width-computed">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
        id="Dict-queryForm"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :title="t('dictManage.dict.tableTitle')"
        :showExport="false"
        :animateRows="false"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        ref="gridRef"
        id="Dict-querytable"
        :scroll="{
          extra: 24,
          y: true,
        }"
        :height="500"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group v-bind="menuProps" ref="menuRef" id="Root-buttonGroup" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            id="Root-buttonGroup-inline"
          />
        </template>
        <template #dictState="{ text }">
          <template v-if="text === '启用'">
            <h-badge status="success" :text="text" />
          </template>
          <template v-else>
            <h-badge status="error" :text="text" />
          </template>
        </template>
      </h-b-table>
    </h-card>
    <dict-detail ref="dictDeatil"></dict-detail>
  </div>
</template>

<script lang="ts">
import { useTable, useButtonGroup, useForm } from '@crami/bui-platform';
import {
  computed,
  defineComponent,
  watchEffect,
  ref,
  onMounted,
  getCurrentInstance,
  watch,
} from 'vue';
import { message, HModal } from '@crami/ui';
import { getInfo, ICP_CONFIG, usePageParams } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import { usePageParams } from '@/utils/usePageData'; */
// import {  saveLineData, editLineData  } from './commonApi';
import DictDetail from './DictDetail.vue';
import DictValue from './DictValue.vue';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';
export default defineComponent({
  name: 'Dict',
  components: { DictDetail },
  props: {
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(_) {
    const { t } = useI18n();
    const pageParams: any = usePageParams();
    const commonParams = computed(() => {
      return { ...getInfo(ICP_CONFIG), ...pageParams.value };
    });
    const initForm = computed(() => {
      return {
        PEID: _.propsData?.value1,
        APPLICATION_ID: _.propsData?.parentValue1,
      };
    });

    const [formRef, props, methods] = useForm(
      {
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form_view',
            mode: 'search',
            name: commonParams.value?.listView,
          },
          method: commonApi().studioCache.getMetaInfo.method,
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
              },
              column: 3,
              // layout: 'vertical',
              // labelCol: { span: 8 }, //标签
              // wrapperCol: { span: 20 },
              // title: '查询',
              //   initialValue: {这里设置查询条件初始值},
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    const onFinish = data => {
      // 处理data数据
      console.log(data);
      const formData = formRef.value.getFilterData();
      search(formData);
    };

    const beforeRequest = (type, params: any) => {
      if (type == 'column') {
        if (params && params.data && typeof params.data == 'object') {
          params.data = JSON.stringify(params.data);
        }
      }
      const PEID = params.filter?.find(item => item.field == 'PEID');

      return {
        ...params,
        filter: PEID
          ? params.filter
          : (params.filter || []).concat({
              andOrFlag: 'AND',
              field: 'PEID',
              operation: '=',
              value: _.propsData?.value1,
            }),
      };
    };

    const [gridRef, tableProps, tableMethods] = useTable({
      // 表头数据
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: commonParams.value?.listView,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: commonParams.value?.listView,
        },
      },
      beforeRequest: beforeRequest,
      operation: {
        dataIndex: 'action',
        title: t('platform.common.operate'),
        width: 160,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
      columnExtra: {
        DIC_STATUS: {
          customSlot: 'dictState',
        },
      },
    });

    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'Dict',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: commonParams.value?.menuName,
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'Dict',
      moreItem: {
        trigger: ['click'],
      },
      items: [],
    });
    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        refreshTable();
        HModal.destroyAll();
      } else {
        if (undefined == event?.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };

    //处理行内操作按钮
    watchEffect(async () => {
      const rowData = getRowMenu('link');
      load(rowData);
    });

    const dictDeatil: any = ref('');
    const openDictDetail = () => {
      if (gridRef.value?.getSelectRowsIds().length != 1) {
        message.warning(t('dictManage.dict.selectWaringMsg'));
        return;
      }
      dictDeatil.value?.show({
        rows: gridRef.value?.getSelectedRows(),
      });
    };
    let appContext;
    onMounted(() => {
      appContext = getCurrentInstance()?.appContext;
    });

    // 打开枚举管理
    const openDictValue = () => {
      if (gridRef.value?.getSelectRowsIds().length != 1) {
        message.warning(t('dictManage.dict.selectWaringMsg'));
        return;
      }

      let dictValueOptions = {
        title: t('dictManage.dict.tableChildTitle'),
        content: DictValue,
        okText: t('platform.common.ok'),
        cancelText: t('platform.common.cancel'),
        class: 'platform-dict-custom',
        componentProps: {
          rows: gridRef.value?.getSelectedRows(),
          propsData: _.propsData,
        },
        width: '886px',
        bodyStyle: {
          // paddingBottom: '40px',
        },
        appContext,
      };
      HModal.page(dictValueOptions);
    };

    const refreshTable = () => {
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };
    // 重置
    const onReset = () => {
      search([]);
    };

    const refreshCurrentPage = () => {
      const params = formRef.value?.getFilterData();
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, false);
    };

    watch(
      () => _.propsData,
      () => {
        refreshTable();
      },
      { deep: true },
    );

    return {
      t,
      onFinish,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,

      gridRef,
      tableProps,
      openDictDetail,
      openDictValue,
      dictDeatil,
      refreshTable,
      initForm,
      onReset,
      refreshCurrentPage,
      commonParams,
    };
  },
});
</script>
