<template>
  <div class="main-content main-content-padding" id="FileImport">
    <h-card class="margin-bottom list-query-form">
      <!-- //查询表单 -->
      <h-b-form
        id="FileImport-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="FileImport-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('ImpExp.common.ImpList')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        ref="gridRef"
        :scroll="{ extra: 24, y: true }"
        :height="500"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group id="FileImport-buttonGroup" v-bind="menuProps" ref="menuRef" />
        </template>
        <!-- 行内操作按钮 -->
        <template #bodyCell="{ column, record }">
          <!-- 以超链接形式展示配置名称 -->
          <template v-if="column.dataIndex == 'ENAME'">
            <a :title="record.ENAME" @click="inquire(record)">
              {{ record.ENAME }}
            </a>
          </template>
          <!-- UI设计图的启用禁用状态 -->
          <template v-else-if="column.dataIndex === 'STATEID'">
            <template v-if="record.STATEID === t('ImpExp.common.Enable')">
              <h-badge status="success" :text="record.STATEID" />
            </template>
            <template v-else-if="record.STATEID === t('ImpExp.common.Deactivate')">
              <h-badge status="error" :text="record.STATEID" />
            </template>
          </template>
          <!-- 行内操作按钮 -->
          <template v-else-if="column.dataIndex === 'action'">
            <h-b-button-group
              id="FileImport-buttonGroup-inline"
              v-bind="menuPropsTable"
              ref="menuRefTable"
            />
          </template>
          <template v-else-if="column.dataIndex !== 'my-custom-show-index'">
            <span :title="record[column.dataIndex]">{{ record[column.dataIndex] }}</span>
          </template>
        </template>
      </h-b-table>
    </h-card>
  </div>

  <edit-imp-data
    v-if="compile"
    :compile="compile"
    @closeModel="compile = false"
    :selectKey="selectKey"
    :search="search"
    :title="title"
    :val="val"
    :NewObjectType="NewObjectType"
  ></edit-imp-data>
  <template v-if="compile2">
    <imp-guide
      :compile2="compile2"
      @closeModel="compile2 = false"
      :commonParams="commonParams"
    ></imp-guide>
  </template>
  <inquire-data-imp
    :compile="inquireShow"
    @closeModel="inquireShow = false"
    :search="search"
    :selectKey="selectKey"
    :valInquire="valInquire"
  ></inquire-data-imp>
</template>

<script lang="ts">
import { defineComponent, watchEffect, computed, ref, createVNode } from 'vue';
import { useTable, useForm, useButtonGroup } from '@crami/bui-platform';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
import { message, HModal, HMessage, Icon } from '@crami/ui';
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import ImpGuide from '../Compnent/ImpGuide.vue';
import EditImpData from '../Compnent/EditImpData.vue';
import InquireDataImp from '../Compnent/InquireDataImp.vue';
import { editDataAPI } from '@/api/platform/ImpExp/Import';
import { deleteRuleAPI } from '@/api/platform/ImpExp/Export';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'FileImport',
  components: { ImpGuide, EditImpData, InquireDataImp },
  setup() {
    const { t } = useI18n();
    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        listViewName: 'P_SYS_IMPORT_RULE_LISTVIEW',
        menuName: 'P_SYS_IMPORT_RULE_MENU',
      };
    });
    const [formRef, props, methods] = useForm(
      {
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            ...{
              type: 'form_view',
              mode: 'search',
              name: commonParams.value?.listViewName,
            },
          },
          method: commonApi().studioCache.getMetaInfo.method,
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
                // actionButtonGroupPosition: 'top',
              },
              // layout: 'vertical',
              column: 2,
              // labelCol: { span: 20 }, //标签
              // wrapperCol: { span: 20 },
              // initialValue: {这里设置查询条件初始值},
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );
    const onFinish = () => {
      // 处理data数据
      const formData = formRef.value.getFilterData();
      search(formData);
    };
    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?.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) {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
        };
      },
      operation: {
        dataIndex: 'action',
        title: t('ImpExp.common.operation'),
        width: 120,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });

    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'FileImport',
      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: 'FileImport',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    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 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);
    };

    // 启用停用的接口
    const AlterState = (event, num) => {
      console.log(event, num);
      useHttp({
        url: '/api/importservice/importMaintain/editStateByIds',
        method: 'post',
        params: {
          EIDStr: event,
          stateId: num,
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
        },
      }).then(res => {
        if (res.code == 200) {
          message.success(res.msg);
          search([]);
        } else {
          message.warning(res.msg);
        }
      });
    };
    // 启用
    const StartState = () => {
      // 获取要修改的数据条数
      const selectKeys = tableMethods.getSelectedKeys();
      HModal.confirm({
        icon: false,
        title: t('ImpExp.common.EnebleConfirm'),
        // content: `确定启用${selectKeys.length}条数据吗?`,
        content: t('ImpExp.common.confirm') + selectKeys.length + t('ImpExp.common.datas'),
        onOk() {
          return new Promise((resolve, reject) => {
            AlterState(selectKeys, 1);
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    // 停用
    const StopState = () => {
      // 获取要修改的数据条数
      const selectKeys = tableMethods.getSelectedKeys();
      HModal.confirm({
        icon: false,
        title: t('ImpExp.common.DeactivateConfirm'),
        // content: `确定停用${selectKeys.length}条数据吗?`,
        content: t('ImpExp.common.confirm2') + selectKeys.length + t('ImpExp.common.datas'),
        onOk() {
          return new Promise((resolve, reject) => {
            AlterState(selectKeys, 0);
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    const compile2 = ref<boolean>(false);

    const NewObjectType = ref();
    // 新增
    const create = data => {
      title.value = t('ImpExp.common.Added');
      compile.value = true;
      // console.log(data);
      NewObjectType.value = data.ObjectType;
    };
    // 传递给子组件的数据
    const title = ref();
    const compile = ref<boolean>(false);
    const selectKey = ref();
    const val = ref();
    // 编辑
    const edit = e => {
      selectKey.value = tableMethods.getSelectedKeys();
      title.value = t('ImpExp.common.Edit');
      compile.value = true;
      // console.log(e);
      editDataAPI({
        companyId: commonParams.value.companyId,
        connect: commonParams.value.connect,
        lang: commonParams.value.lang,
        objectID: selectKey.value[0],
      }).then(res => {
        // console.log(res);
        val.value = res.data.data;
      });
    };
    // 删除
    const deleteRule = () => {
      const selectKeys = tableMethods.getSelectedKeys();
      HModal.confirm({
        title: t('ImpExp.common.delComfirm'),
        closable: true,
        class: 'self-warning-modal',
        icon: createVNode(Icon, {
          name: 'icp-exclamation-circle-filled',
          size: 24,
          style: {
            float: 'left',
            marginRight: '8px',
          },
        }),
        content: t('ImpExp.common.confirm3') + selectKeys.length + t('ImpExp.common.datas'),
        okText: t('ImpExp.common.notarize'),
        cancelText: t('ImpExp.common.Cancel'),
        onOk() {
          return new Promise((resolve, reject) => {
            deleteRuleAPI({
              companyId: commonParams.value.companyId,
              connect: commonParams.value.connect,
              lang: commonParams.value.lang,
              eidstr: selectKeys,
            }).then(res => {
              if (res.code == 200) {
                message.success(t('ImpExp.common.delSucceed'));
                tableMethods.query();
              } else if (res.code == 500) {
                message.warning(res.msg);
              }
            });
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };

    const valInquire = ref();
    // 查看
    const inquireShow = ref<boolean>(false);
    const inquire = data => {
      inquireShow.value = true;
      // console.log(data.EID);
      editDataAPI({
        companyId: commonParams.value.companyId,
        connect: commonParams.value.connect,
        lang: commonParams.value.lang,
        objectID: data.EID,
        // userId: commonParams.value.userId,
      }).then(res => {
        // console.log(res);
        valInquire.value = res.data.data;
      });
    };

    return {
      t,
      inquireShow,
      inquire,
      deleteRule,
      StartState,
      StopState,
      create,
      edit,
      compile2,
      NewObjectType,

      onFinish,
      onReset,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,

      refreshCurrentPage,
      refreshTable,

      gridRef,
      tableProps,

      title,
      compile,
      commonParams,
      selectKey,
      search,
      val,
      valInquire,
    };
  },
});
</script>
<style lang="less" scoped></style>
