<template>
  <div class="main-content" id="CodeValueTable">
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-pro-table
        id="CodeValueTable-queryTable"
        v-bind="tableProps"
        class="tableHideLastLine"
        :data-source="dataSource"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :pagination="false"
        :expand-icon-column-index="3"
        v-model:expandedRowKeys="expandedRowKeys"
        title=" "
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        :scroll="{
          extra: 24,
          y: true,
        }"
        ref="gridRef"
      >
        <template v-slot:headerCell="{ title, column }">
          {{
            column.dataIndex === 'CODE_VALUE'
              ? headerRuleTitle
              : getLocaleMessage(column.locale, title)
          }}
        </template>
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group v-bind="menuProps" ref="menuRef" id="CodeValueTable-buttonGroup" />
        </template>
      </h-b-pro-table>
    </h-card>
  </div>
</template>

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

export default defineComponent({
  name: 'CodeValueTable',
  props: {
    activeKey: {
      type: String,
      required: true,
    },
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  emits: ['refreshNode'],
  setup(prop) {
    const { t } = useI18n();
    const { getLocaleMessage } = useLocale().value;
    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        ...prop.propsData,
        activeKey: prop.activeKey,
      };
    });
    watch(commonParams, () => {
      refreshTable();
    });

    const headerRuleTitle = ref('');
    let headerRule = '';
    let headerRuleError = '';
    const dataSource = ref([]);
    const expandedRowKeys = ref([]);

    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: false,
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
        };
      },
      operation: {
        dataIndex: 'action',
        title: t('code.common.operate'),
        width: 0,
        show: false,
        customSlot: 'action',
        fixed: 'right',
      },
    });

    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      sortRule: 'default',
      pageName: 'CodeValueTable',
      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: 'CodeValueTable',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });

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

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

    const refreshTable = () => {
      // tableMethods.query();
      getData();
    };
    const componentRef = ref();
    // 码值新建事件
    const createCodeEvent = async (event: any) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/checkInsert',
        method: 'post',
        params: {
          codeSegmentId: commonParams.value.value1,
          codeSegmentParentId: event.objectID ? event.objectID.CODE_SEGMENT_ID : null,
          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) {
        let options = reactive<IModalPageParams>({
          title: t('code.common.add'),
          content: CreateCodeValue,
          componentProps: {
            params: {
              ...event,
              codeSegmentId: commonParams.value.value1,
              rule: headerRule,
              ruleTitle: headerRuleTitle,
              ruleErrorTip: headerRuleError,
              defaultValue: data.data.defaultValue,
            },
            instanceRef: componentRef,
          },
          // 点击确定按钮的回调
          cancelText: t('platform.common.cancel'),
          okText: t('platform.common.save'),
          onOk: okCreate,
          width: 600,
        });
        HModal.page(options);
      } else {
        message.error(data.msg);
      }
    };

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

    // 码值编辑事件
    const EditCodeEvent = async (event: any) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/checkEditValue',
        method: 'post',
        params: {
          codeSegmentId: commonParams.value.value1,
          codeValueSegmentAssociatedId: event.objectID.CODE_SEGMENT_ID || null,
          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) {
        let options = reactive<IModalPageParams>({
          title: t('code.common.edit'),
          content: EditCodeValue,
          componentProps: {
            params: {
              ...event,
              codeSegmentId: commonParams.value.value1,
              rule: headerRule,
              ruleTitle: headerRuleTitle,
              ruleErrorTip: headerRuleError,
              enableEdit: data.data ? data.data : false,
            },
            instanceRef: componentRef,
          },
          cancelText: t('platform.common.cancel'),
          okText: t('platform.common.save'),
          onOk: okEdit,
          width: 600,
        });
        HModal.page(options);
      } else {
        message.error(data.msg);
      }
    };

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

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

    // 下移
    const downValueEvent = (event: any) => {
      if (timer) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          moveCodeApi(event.objectID, '1');
        }, 1000);
      } else {
        moveCodeApi(event.objectID, '1');
        timer = setTimeout(() => {
          clearTimeout(timer);
          timer = null;
        }, 1000);
      }
    };
    // 码值复制事件
    const copyValueEvent = (event: any) => {
      localStorage.setItem(
        commonParams.value.user_id + '_codevalue',
        JSON.stringify(event.objectID),
      );
      message.success(t('code.common.copySuccess'));
    };
    // 码值粘贴事件
    const pasteValueEvent = async (event: any) => {
      const objectID = event.objectID;
      const copys = localStorage.getItem(commonParams.value.user_id + '_codevalue');
      if (!copys || copys === undefined || copys.length === 0) {
        message.warn(t('code.common.pasteWarn'));
        return;
      }
      const temps = JSON.parse(copys);
      const objIds = temps
        .map(item => {
          return item.EID;
        })
        .join(',');
      const codeAssIds = temps
        .map(item => {
          return item.CODE_SEGMENT_ID;
        })
        .join(',');
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/pasteCodeValue',
        method: 'post',
        params: {
          codeSegmentId: commonParams.value.value1,
          objectIds: objIds,
          codeValueSegmentAssociatedId: codeAssIds,
          pid: objectID ? objectID.EID : '',
          parentName: objectID ? objectID.CODE_VALUE : '',
          codeSegmentParentId: objectID ? objectID.CODE_SEGMENT_ID : '',
          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 + '_codevalue');
      if (data.code === 200) {
        message.success(data.msg);
        refreshTable();
      } else {
        message.error(data.msg);
      }
    };
    // 码值删除事件
    const deleteValueEvent = async (event: any) => {
      const idStr =
        event.objectID
          .map(item => {
            return item.EID;
          })
          .join(',') || '';
      const codeSegId =
        event.objectID
          .map(item => {
            return item.CODE_SEGMENT_ID;
          })
          .join(',') || '';
      const schemeId = event.objectID[0].CODE_SCHEME_ID;
      HModal.confirm({
        closable: true,
        icon: createVNode(ExclamationCircleFilled),
        title: t('code.common.deleteTitle'),
        content: t('code.common.deleteOk'),
        class: 'code-deleteWarning-modal',
        onOk() {
          return new Promise(resolve => {
            deleteCodeApi(idStr, codeSegId, schemeId);
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    // 导出
    const exportValueEvent = () => {
      HModal.confirm({
        closable: true,
        icon: createVNode(ExclamationCircleFilled),
        title: t('code.codeValue.valueTable.exportTitle'),
        content: t('code.codeValue.valueTable.exportOk'),
        class: 'export-codeValueTable-modal',
        onOk() {
          return new Promise(resolve => {
            exportCodeApi();
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    const moveCodeApi = async (objectID: string, move: string) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/moveCodeValue',
        method: 'post',
        params: {
          codeValueId: objectID,
          // 码段id
          codeSegmentId: orgId.value,
          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();
      } else {
        message.error(data.msg);
      }
    };

    const importEdit = reactive({
      disabled: true,
    });
    const importValueEvent = async () => {
      importEdit.disabled = true;
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/checkCodeSchemeState',
        method: 'post',
        params: {
          codeSegmentId: 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) {
        let options = reactive<IModalPageParams>({
          title: t('code.codeValue.valueTable.importTitle'),
          content: ImportCodeValue,
          componentProps: {
            params: { codeSegmentId: commonParams.value.value1 },
            instanceRef: componentRef,
          },
          cancelText: t('code.common.cancel'),
          okText: t('code.common.importOk'),
          okButtonProps: importEdit,
          onOk: importCodeEvent,
          width: '50%',
          class: 'import-code-program-modal',
        });
        HModal.page(options);
      } else {
        message.error(data.msg);
      }
    };

    const exportCodeApi = async () => {
      const data = await Http.post<any>({
        url: '/api/codemanagement/codeValue/exportCodeValueData',
        params: {
          connect: 'MYSQL',
          lang: 'zhs',
          codeSegmentId: commonParams.value.value1,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
        responseType: 'blob',
      });
      if (data.code !== 200) {
        message.error(data.msg);
        return;
      }
      const content = data.data;
      const blob = new Blob([content]);
      const date = getNowDate();
      const fileName = date + '.xlsx';
      if ('download' in document.createElement('a')) {
        // // 非IE下载
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      }

      if (data.code === 200) {
        message.success(t('code.common.exportMsg'));
        refreshTable();
      } else {
        message.error(data.msg);
      }
    };

    const importCodeEvent = async (options: any, close: any) => {
      if (options.dataSource.length == 0) {
        message.warn(t('code.codeValue.valueTable.importDataMsg'));
        return;
      }
      if (options.tipDatas.length == 0) {
        message.warn(t('code.codeValue.valueTable.importParseMsg'));
        return;
      }
      if (options.tipDatas.length > 0 && options.tipDatas[0].show === true) {
        message.error(t('code.codeValue.valueTable.importErrorMsg'));
        return;
      }
      const jsonArr = options.dataSource.map(item => {
        const { EID: _, ...iItem } = item;
        return { ...iItem };
      });
      const jsonData = JSON.stringify(jsonArr);
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/saveImportCodeValueData',
        method: 'post',
        params: {
          codeSegmentId: options.componentProps?.params.codeSegmentId,
          importJsonData: jsonData,
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        HModal.confirm({
          icon: createVNode(CheckCircleFilled),
          closable: true,
          title: t('code.common.importSuccess'),
          content: data.msg,
          class: 'code-importSuccess-modal',
        });
        close();
        refreshTable();
      } else {
        message.error(data.msg);
      }
    };

    const deleteCodeApi = async (idStr: string, codeSegId: string, schemeId: string) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/deleteCodeValue',
        method: 'post',
        params: {
          objectIds: idStr,
          codeSchemeId: schemeId,
          codeSegmentId: commonParams.value.value1,
          codeValueSegmentAssociatedId: codeSegId,
          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');
      } else {
        message.error(data.msg);
      }
    };

    const changeImportStatus = (status: boolean) => {
      importEdit.disabled = status;
    };

    onMounted(() => {
      getData();
      bus.on('changeImportStatus', changeImportStatus);
      bus.on('endCodeEvent', endCodeEvent);

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

    // 获取列表数据
    const getData = async () => {
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/getCodeValueList',
        method: 'post',
        params: {
          codeSegmentId: 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) {
        dataSource.value.length = 0;
        const results = changeData(data.data.valueTree);
        dataSource.value = [].concat(results);
        headerRuleTitle.value = data.data.rule;
        headerRule = data.data.ruleRegular;
        headerRuleError = data.data.ruleErrorMsg;
      } else {
        message.error(data.msg);
      }
    };

    const changeData = (data: any) => {
      const tempsData: any[] = [];
      if (data === undefined) {
        return tempsData;
      }
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        const temp = {
          EID: item.eid,
          CODE_SEGMENT_ID: item.codeSegmentId,
          CODE_SCHEME_ID: item.codeSchemeId,
          CODE_VALUE: item.codeValue,
          DESCRIBES: item.describes,
          PID: item.pid,
          PNAME: item.pname,
          LEVEL: item.level,
        };

        if (item.children && item.children.length > 0) {
          const cChildren = changeData(item.children);
          temp['children'] = cChildren;
        }
        tempsData.push(temp);
      }
      return tempsData;
    };

    onUnmounted(() => {
      bus.off('endCodeEvent');
      bus.off('changeImportStatus');
    });

    const getNowDate = () => {
      const date = new Date();
      const Y = date.getFullYear() + '-';
      const M =
        (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '-';
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + '-';
      const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + '-';
      const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();

      return Y + M + D + h + m + s;
    };

    return {
      t,
      getLocaleMessage,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      headerRuleTitle,
      dataSource,
      expandedRowKeys,
      getData,
      newJsFun,
      refreshTable,
      gridRef,
      tableProps,
      refreshCurrentPage,
      createCodeEvent,
      EditCodeEvent,
      copyValueEvent,
      pasteValueEvent,
      deleteValueEvent,
      downValueEvent,
      upValueEvent,
      exportValueEvent,
      importValueEvent,
    };
  },
});
</script>

<style lang="less" scoped>
: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;
}
:deep(.tableHideLastLine .surely-table:last-child .surely-table-cell) {
  border-bottom-color: transparent;
}

.list-table.ant-card {
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
</style>
