<template>
  <div class="main-content" id="CodeSegmentTable">
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-pro-table
        id="CodeSegmentTable-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        title=" "
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        :scroll="{
          extra: 24,
          y: true,
        }"
        ref="gridRef"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group v-bind="menuProps" ref="menuRef" id="CodeSegmentTable-buttonGroup" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            id="CodeSegmentTable-buttonGroup-inline"
          />
        </template>
      </h-b-pro-table>
    </h-card>
  </div>
</template>

<script lang="ts">
import { useProTable, useButtonGroup } from '@crami/bui-platform';
import {
  computed,
  defineComponent,
  watchEffect,
  watch,
  ref,
  reactive,
  onUnmounted,
  createVNode,
  onMounted,
} from 'vue';
import { message, HModal } from '@crami/ui';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '@/utils/bus'; */
import { getInfo, ICP_CONFIG, bus, registerComponents } from '@remote/icpx-platform/utils';
import type { IModalPageParams } from '@crami/ui-types';
import CreateCodeSegment from '../components/CreateCodeSegment.vue';
import EditCodeSegment from '../components/EditCodeSegment.vue';
import CompleteCodeSegment from '../components/CompleteCodeSegment.vue';
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { ExclamationCircleFilled } from '@ant-design/icons-vue';
import { useI18n } from '@crami/locale';
/* import { registerComponents } from '@/utils/componentUtils'; */

export default defineComponent({
  name: 'CodeSegmentTable',
  components: {},
  props: {
    activeKey: {
      type: String,
      required: true,
    },
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  emits: ['refreshNode', 'checkEvent'],
  setup(prop, { emit }) {
    const { t } = useI18n();
    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        ...prop.propsData,
        activeKey: prop.activeKey,
      };
    });

    watch(commonParams, () => {
      refreshTable();
    });
    const [gridRef, tableProps, tableMethods] = useProTable({
      // 表头数据
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: commonParams.value?.listViewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: commonParams.value?.listViewName,
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
          filter: [
            {
              andOrFlag: 'AND',
              field: 'CODE_SCHEME_ID',
              operation: '=',
              value: commonParams.value.value1,
            },
          ],
        };
      },
      operation: {
        dataIndex: 'action',
        title: t('code.common.operate'),
        width: 150,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });

    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      sortRule: 'default',
      pageName: 'CodeSegmentTable',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: commonParams.value?.menuName,
        },
        method: 'post',
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'CodeSegmentTable',
      items: [],

      moreItem: {
        trigger: ['click'],
      },
    });
    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        refreshTable();
        emit('refreshNode', commonParams.value.value1);
        HModal.destroyAll();
      } else {
        if (undefined == event || undefined == event.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };
    //页面刷新操作按钮
    const refreshCurrentPage = () => {
      tableMethods.query({}, false);
    };

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

    const refreshTable = () => {
      tableMethods.query();
    };
    const endCodeEvent = () => {
      refreshTable();
      emit('refreshNode', commonParams.value.value1);
    };
    bus.on('endCodeEvent', endCodeEvent);
    onUnmounted(() => {
      bus.off('endCodeEvent');
    });

    const componentRef = ref();
    const CreateCodeEvent = async (event: any) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeManagement/checkCodeSchemeState',
        method: 'post',
        params: {
          objectId: commonParams.value.value1,
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        let options = reactive<IModalPageParams>({
          title: t('code.common.add'),
          content: CreateCodeSegment,
          componentProps: {
            params: { ...event, codeSchemeId: commonParams.value.value1 },
            instanceRef: componentRef,
          },
          class: 'testaabbcc',
          cancelText: t('platform.common.cancel'),
          okText: t('platform.common.save'),
          width: 600,
          onOk: onOk,
        });
        HModal.page(options);
      } else {
        message.error(data.msg);
      }
    };

    const onOk = (expose, resolve) => {
      expose.ok();
    };

    const EditCodeEvent = async (event: any) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/checkCodeSegmentState',
        method: 'post',
        params: {
          codeSchemeId: commonParams.value.value1,
          objectId: event.objectID.EID,
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        let options = reactive<IModalPageParams>({
          title: t('code.common.edit'),
          content: EditCodeSegment,
          componentProps: {
            params: {
              ...event,
              codeSchemeId: commonParams.value.value1,
              isEdit: data.data.stateID === 'YES',
            },
            instanceRef: componentRef,
          },
          // 点击确定按钮的回调
          cancelText: t('platform.common.cancel'),
          okText: t('platform.common.save'),
          width: 600,
          onOk: okEdit,
        });
        HModal.page(options);
      } else {
        message.error(data.msg);
      }
    };

    const okEdit = (expose, resolve) => {
      expose.onFinish();
    };

    let timer = null;
    // 上移
    const MoveupCodeSegment = (event: any) => {
      if (timer) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          moveCodeApi(event.objectID.EID, '0');
        }, 1000);
      } else {
        timer = setTimeout(() => {
          moveCodeApi(event.objectID.EID, '0');
        }, 1000);
      }
    };

    // 下移
    const MovedownCodeSegment = (event: any) => {
      if (timer) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          moveCodeApi(event.objectID.EID, '1');
        }, 1000);
      } else {
        timer = setTimeout(() => {
          moveCodeApi(event.objectID.EID, '1');
        }, 1000);
      }
    };

    const CompleteCodeEvent = async (event: any) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/getSegmentById',
        method: 'post',
        params: {
          objectId: event.objectID,
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value?.user_id,
          codeSchemeId: commonParams.value?.value1,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });

      if (data.code === 200) {
        let options = reactive<IModalPageParams>({
          title: t('code.codeSegment.segmentTable.completeTitle'),
          content: CompleteCodeSegment,
          componentProps: { params: event, stateData: data.data, instanceRef: componentRef },
          // 点击确定按钮的回调
          cancelText: t('platform.common.cancel'),
          okText: t('platform.common.save'),
          width: 600,
          onOk: onComplete,
          onCancel: cancelComplete,
        });
        HModal.page(options);
      } else {
        message.error(data.msg);
      }
    };

    const onComplete = (expose, resolve) => {
      expose.onFinish();
    };

    const cancelComplete = (expose, resolve) => {
      expose.cancelEvent();
    };

    const CopyCodeSegment = (event: any) => {
      const temps = event.objectID.map(item => {
        return item.EID;
      });
      localStorage.setItem(commonParams.value.user_id + '_codeseg', JSON.stringify(temps));
      message.success(t('code.common.copySuccess'));
    };

    const PasteCodeSegment = async () => {
      const copys = localStorage.getItem(commonParams.value.user_id + '_codeseg');
      if (!copys || copys === undefined || copys.length === 0) {
        message.warn(t('code.common.pasteWarn'));
        return;
      }
      const temps = JSON.parse(copys);
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/saveAsCodeSegment',
        method: 'post',
        params: {
          codeSchemeId: commonParams.value.value1,
          objectIds: temps.join(','),
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      localStorage.removeItem(commonParams.value.user_id + '_codeseg');
      if (data.code === 200) {
        message.success(data.msg);
        refreshTable();
        emit('refreshNode', commonParams.value.value1);
      } else {
        message.error(data.msg);
      }
    };

    const DeleteCodeSegment = async (event: any) => {
      const idStr =
        event.eidstr
          .map(item => {
            return item.EID;
          })
          .join(',') || '';
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/checkDelete',
        method: 'post',
        params: {
          objectId: idStr,
          codeSchemeId: commonParams.value.value1,
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        if (data.data.code === '0') {
          message.error(data.data.msg);
        } else {
          HModal.confirm({
            closable: true,
            icon: createVNode(ExclamationCircleFilled),
            title: t('code.common.deleteTitle'),
            content: data.data.msg,
            class: 'code-deleteWarning-modal',
            onOk() {
              return new Promise(resolve => {
                deleteCodeApi(idStr);
                resolve(true);
              }).catch(() => console.log('Oops errors!'));
            },
          });
        }
      } else {
        message.error(data.msg);
      }
    };

    const checkEvent = (event: any) => {
      emit('checkEvent', { ...event, schemeId: commonParams.value.value1 });
    };

    const moveCodeApi = async (objectID: string, move: string) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/moveCodeSegment',
        method: 'post',
        params: {
          objectId: objectID,
          move,
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        message.success(data.msg);
        refreshTable();
        emit('refreshNode', commonParams.value.value1);
      } else {
        message.error(data.msg);
      }
    };

    const deleteCodeApi = async (idStr: string) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/deleteCodeSegment',
        method: 'post',
        params: {
          objectId: idStr,
          codeSchemeId: commonParams.value.value1,
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        message.success(data.msg);
        refreshTable();
        emit('refreshNode', commonParams.value.value1);
      } else {
        message.error(data.msg);
      }
    };

    onMounted(() => {
      const modules = import.meta.glob('./../components/*.vue');
      registerComponents(modules);
    });

    return {
      t,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      refreshTable,
      gridRef,
      tableProps,
      //   injectCreateCode,
      tableMethods,
      refreshCurrentPage,
      commonParams,
      CreateCodeEvent,
      EditCodeEvent,
      MoveupCodeSegment,
      MovedownCodeSegment,
      CompleteCodeEvent,
      CopyCodeSegment,
      PasteCodeSegment,
      DeleteCodeSegment,
      checkEvent,
    };
  },
});
</script>

<style scoped lang="less">
:deep(.hoteam-b-table-list-toolbar-container) {
  border-bottom: none;
}
:deep(.ant-pagination-item) {
  border-radius: 3px;
}
:deep(.ant-pagination-prev .ant-pagination-item-link, .ant-pagination-next
    .ant-pagination-item-link) {
  border-radius: 3px;
}
.list-table.ant-card {
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
</style>
