<template>
  <!-- 表格，操作按钮和按钮组插槽实现 -->
  <h-card class="list-table">
    <h-b-pro-table
      id="CodeProgramme-queryTable"
      v-bind="tableProps"
      rowKey="EID"
      :needRowIndex="true"
      :show-size="false"
      :showExport="false"
      :animateRows="false"
      :title="t('code.codeProgramme.codeTitle')"
      :row-selection="{
        type: 'checkbox',
        memory: true,
        clickSelectTrigger: 'row',
        unSelectable: true,
      }"
      :scroll="{
        extra: 24,
        y: true,
      }"
      ref="gridRef"
    >
      <template #STATEID="{ record }">
        <h-row align="middle">
          <div v-if="record.STATE_CODE == 'DEACTIVATE'" class="dot error"></div>
          <div v-else-if="record.STATE_CODE == 'ENABLE'" class="dot success"></div>
          <div v-else class="dot create"></div>
          {{ record.STATEID }}
        </h-row>
      </template>
      <!-- 按钮组插槽 -->
      <template #headerContent>
        <h-b-button-group
          :more-item="{
            menuType: 'button',
            type: '',
            extraIcon: 'icp-dropDown',
          }"
          v-bind="menuProps"
          ref="menuRef"
          id="CodeProgramme-buttonGroup"
          customMenuFun
        />
      </template>
      <!-- 行内操作按钮 -->
      <template #action="{}">
        <h-b-button-group
          v-bind="menuPropsTable"
          ref="menuRefTable"
          id="CodeProgramme-buttonGroup-inline"
        />
      </template>
    </h-b-pro-table>
  </h-card>
</template>

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

export default defineComponent({
  name: 'CodeProgramme',
  components: {},
  props: {
    activeKey: {
      type: String,
      required: true,
    },
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  emits: ['refreshNode', 'checkEvent'],
  setup(prop, { emit }) {
    const { t } = useI18n();
    const value1 = computed(() => {
      return prop.propsData?.value1;
    });
    const title = computed(() => {
      return prop.propsData?.title;
    });
    const initForm = computed(() => {
      return {
        PARENT_ID: { label: title.value, value: value1.value },
      };
    });

    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        listViewName: 'P_SYS_CODE_SCHEME_LISTVIEW',
        menuName: 'P_SYS_CODE_SCHEME_MENU',
        activeKey: prop.activeKey,
      };
    });
    watch(
      () => commonParams.value,
      () => {
        refreshTable();
      },
    );
    const endCodeEvent = () => {
      refreshTable();
      emit('refreshNode');
    };

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

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

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

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

    const [gridRef, tableProps, tableMethods] = useProTable({
      columnExtra: {
        STATEID: {
          customSlot: 'STATEID',
        },
      },
      // 表头数据
      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,
        };
      },

      operation: {
        dataIndex: 'action',
        title: t('code.common.operate'),
        width: 180,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });

    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'CodeProgramme',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: commonParams.value?.menuName,
        },
        method: 'post',
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'CodeProgramme',
      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();
    };

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

    const refreshTable = () => {
      tableMethods.query();
    };
    const checkEvent = event => {
      emit('checkEvent', event);
    };
    // 启用
    const startCodeEvent = (event: any) => {
      const nameStr = event.EID.map(item => {
        return item.ENAME;
      }).join(',');
      const eidStr = event.EID.map(item => {
        return item.EID;
      }).join(',');
      HModal.confirm({
        closable: true,
        icon: createVNode(ExclamationCircleFilled),
        class: 'code-enable-modal',
        title: t('code.common.enableTitle'),
        content: t('code.codeProgramme.startContent', { nameStr: nameStr }),
        onOk() {
          return new Promise(resolve => {
            startCodeApi(eidStr);
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    // 停用
    const stopCodeEvent = async (event: any) => {
      const nameStr = event.EID.map(item => {
        return item.ENAME;
      }).join(',');
      const eidStr = event.EID.map(item => {
        return item.EID;
      }).join(',');
      HModal.confirm({
        closable: true,
        icon: createVNode(ExclamationCircleFilled),
        title: t('code.codeProgramme.stopTitle'),
        class: 'code-stop-modal',
        content: t('code.codeProgramme.stopContent', { nameStr: nameStr }),
        onOk() {
          return new Promise(resolve => {
            stopCodeApi(eidStr);
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };

    const startCodeApi = async (eid: string) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeManagement/enableCodeScheme',
        method: 'post',
        params: {
          connect: 'MYSQL',
          lang: 'zhs',
          objectId: eid,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        refreshTable();
        message.success(data.msg);
      } else {
        message.error(data.msg);
      }
    };

    const stopCodeApi = async (eid: string) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeManagement/disableCodeScheme',
        method: 'post',
        params: {
          connect: 'MYSQL',
          lang: 'zhs',
          objectId: eid,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        refreshTable();
        message.success(data.msg);
      } else {
        message.error(data.msg);
      }
    };

    const CodeSchemeExport = (event: any) => {
      const names = event.EID.map(item => {
        return item.ENAME;
      }).join(',');
      const eids = event.EID.map(item => {
        return item.EID;
      }).join(',');
      HModal.confirm({
        closable: true,
        icon: createVNode(ExclamationCircleFilled),
        title: t('code.codeProgramme.exportTitle'),
        content: t('code.codeProgramme.exportContent', { names: names }),
        class: 'code-programme-export-modal',
        onOk() {
          return new Promise(resolve => {
            exportCodeApi(eids);
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    const exportCodeApi = async (eid: string) => {
      const data = await Http.post<any>({
        url: '/api/codemanagement/codeManagement/exportCodeSchemeData',
        params: {
          connect: 'MYSQL',
          lang: 'zhs',
          objectId: eid,
          companyId: commonParams.value?.companyId,
          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) {
        HModal.confirm({
          icon: createVNode(CheckCircleFilled),
          closable: true,
          title: t('code.common.exportMsg'),
          content: t('code.codeProgramme.exportSchemeMsg'),
          cancelText: ' ',
          class: 'code-importSuccess-modal',
        });
        refreshTable();
      }
    };

    const importEdit = reactive({
      disabled: true,
      loading: false,
    });
    const componentRef = ref();
    const CodeSchemeImport = (event: any) => {
      importEdit.disabled = true;
      let options = reactive<IModalPageParams>({
        title: t('code.codeProgramme.importTitle'),
        content: ImportCodeProgram,
        componentProps: { params: event, 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);
    };

    const importCodeEvent = async (options: any, close: any) => {
      if (options.proDatas.length == 0) {
        message.warn(t('code.codeProgramme.importDataMsg'));
        return;
      }
      if (options.tipDatas.data.length == 0) {
        message.warn(t('code.codeProgramme.importParseMsg'));
        return;
      }
      if (options.tipDatas.success === false) {
        message.error(t('code.codeProgramme.importErrorMsg'));
        return;
      }
      importEdit.loading = true;
      const data = await useHttp({
        url: '/api/codemanagement/codeManagement/saveImportCodeSchemeData',
        method: 'post',
        params: {
          schemeList: options.proDatas.map(item => {
            const { EID: _, ...iItem } = item;
            return { ...iItem };
          }),
          segmentList: options.segDatas.map(item => {
            const { EID: _, ...iItem } = item;
            return { ...iItem };
          }),
          valueList: options.valDatas.map(item => {
            const { EID: _, ...iItem } = item;
            return { ...iItem };
          }),
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value.user_id,
          userGroup: commonParams.value?.userGroup,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        HModal.confirm({
          icon: createVNode(CheckCircleFilled),
          closable: true,
          title: t('code.common.importSuccess'),
          content: t('code.codeProgramme.updateSchemeMsg'),
          class: 'code-importSuccess-modal',
        });
        close();
        refreshTable();
        emit('refreshNode');
      } else {
        message.error(data.msg);
      }
      importEdit.loading = false;
    };

    const deleteCodeSchemeEvent = async (event: any) => {
      const idStr =
        event.eidstr
          .map(item => {
            return item.EID;
          })
          .join(',') || '';
      const data = await useHttp({
        url: '/api/codemanagement/codeManagement/checkCodeSchemeUsed',
        method: 'post',
        params: {
          objectId: idStr,
          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 === '1') {
          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 {
          HModal.confirm({
            closable: true,
            icon: createVNode(CloseCircleFilled),
            title: t('code.common.deleteFail'),
            content: data.data.msg,
            class: 'code-deleteError-modal',
          });
        }
      } else {
        HModal.confirm({
          icon: createVNode(CloseCircleFilled),
          closable: true,
          title: t('code.common.deleteFail'),
          content: data.data.msg,
          class: 'code-deleteError-modal',
        });
      }
    };

    const completeCodeEvent = (event: any) => {
      let options = reactive<IModalPageParams>({
        title: t('code.codeProgramme.importTitle'),
        content: CompleteCodeSegment,
        componentProps: { params: event, instanceRef: componentRef },
        // 点击确定按钮的回调
        cancelText: '',
        okText: '',
        width: 600,
      });
      HModal.page(options);
    };
    const SaveCodeProgram = (event: any) => {
      let options = reactive<IModalPageParams>({
        title: t('code.codeProgramme.otherSave'),
        content: SaveCodePrograme,
        componentProps: {
          params: { ...event },
          instanceRef: componentRef,
        },
        // 点击确定按钮的回调
        cancelText: t('platform.common.cancel'),
        okText: t('platform.common.save'),
        width: 448,
        class: 'save-other-modal',
        onOk: onOk,
      });
      HModal.page(options);
    };

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

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

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

    const deleteCodeApi = async (idStr: string) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeManagement/deleteCodeScheme',
        method: 'post',
        params: {
          objectId: idStr,
          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 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,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      refreshTable,
      gridRef,
      tableProps,
      initForm,
      refreshCurrentPage,
      checkEvent,
      startCodeEvent,
      stopCodeEvent,
      CodeSchemeExport,
      CodeSchemeImport,
      completeCodeEvent,
      SaveCodeProgram,
      deleteCodeSchemeEvent,
      editCodeSechemeEvent,
    };
  },
});
</script>

<style lang="less" scoped>
@import url('./status.less');

: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(.hoteam-b-table-list-toolbar-title) {
  color: #333333;
}
// :deep(.hoteam-b-table-list-toolbar-container) {
//   height: 56px;
//   line-height: 56px;
// }
</style>
