<template>
  <div class="main-content main-content-padding" id="FileExport">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        id="fileList-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
      ></h-b-form>
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="FileExport-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('ImpExp.common.expList')"
        :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="FileExport-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 === 'STATE'">
            <template v-if="record.STATE === t('ImpExp.common.Enable')">
              <h-badge status="success" :text="record.STATE" />
            </template>
            <template v-else-if="record.STATE === t('ImpExp.common.Deactivate')">
              <h-badge status="error" :text="record.STATE" />
            </template>
          </template>
          <!-- 行内操作按钮 -->
          <template v-else-if="column.dataIndex === 'action'">
            <h-b-button-group
              id="FileExport-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-exp-data
    :title="title"
    :compile="compile"
    @closeModel="compile = false"
    :search="search"
    :selectKey="selectKey"
    :val="val"
    :NewObjectType="NewObjectType"
  ></edit-exp-data>
  <exp-guide
    :expCompile="expCompile"
    @expCompiles="expCompile = false"
    :searchParams="searchParams"
    :pageParams="pageParams"
  ></exp-guide>
  <inquire-data
    :compile="inquireShow"
    @closeModel="inquireShow = false"
    :search="search"
    :selectKey="selectKey"
    :valInquire="valInquire"
  ></inquire-data>
</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 EditExpData from '../Compnent/EditExpData.vue';
import InquireData from '../Compnent/InquireData.vue';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useHttp } from '@crami/http';
import { deleteRuleAPI, editDataAPI } from '@/api/platform/ImpExp/Export';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'FileExport',
  components: { EditExpData, InquireData },
  setup() {
    const { t } = useI18n();
    const pageParams = ref();
    // 设置下拉框选中事件
    const handleChange = (value: string) => {
      console.log(`selected ${value}`);
    };

    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        listViewName: 'P_SYS_EXPORT_RULE_LISTVIEW',
        menuName: 'P_SYS_EXPORT_RULE_MENU',
      };
    });
    // console.log(commonParams);
    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',
              },
              // 此处更改只在dev使用，不同步到tcl
              // 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 && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        pageParams.value = params;
        return {
          ...params,
        };
      },
      operation: {
        dataIndex: 'action',
        title: t('ImpExp.common.operation'),
        width: 120,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });

    const searchParams = ref();
    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      searchParams.value = params;
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'FileExport',
      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: 'FileExport',
      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) => {
      useHttp({
        url: '/api/exportservice/exportMaintain/alterState',
        method: 'post',
        params: {
          eids: event,
          state: 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 title = ref();
    const selectKey = ref();
    const compile = ref<boolean>(false);
    const val = ref();
    // 编辑
    const edit = () => {
      title.value = t('ImpExp.common.Edit');
      compile.value = true;
      selectKey.value = tableMethods.getSelectedKeys()[0];

      editDataAPI({
        companyId: commonParams.value.companyId,
        connect: commonParams.value.connect,
        lang: commonParams.value.lang,
        objectID: selectKey.value,
      }).then(res => {
        // console.log(res);
        val.value = res.data.data;
      });
    };

    const NewObjectType = ref();
    // 新增
    const create = data => {
      title.value = t('ImpExp.common.Added');
      compile.value = true;
      // console.log(data);
      NewObjectType.value = data.ObjectType;
    };
    // 删除
    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 expCompile = ref<boolean>(false);
    // 导出
    const exportGridData = data => {
      HModal.confirm({
        icon: false,
        title: t('ImpExp.common.ExpConfirm'),
        content: t('ImpExp.common.ExpDatas'),
        onOk() {
          return new Promise((resolve, reject) => {
            // console.log(data);
            localStorage.setItem('data', JSON.stringify(data));
            expCompile.value = true;
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };
    const inquireShow = ref<boolean>(false);
    const valInquire = ref();
    // 查询
    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,
      }).then(res => {
        // console.log(res);
        valInquire.value = res.data.data;
      });
    };

    return {
      inquire,
      inquireShow,
      t,
      deleteRule,
      exportGridData,
      expCompile,
      searchParams,
      pageParams,
      NewObjectType,
      compile,
      title,
      commonParams,
      search,
      selectKey,
      val,
      valInquire,
      StartState,
      StopState,
      edit,
      create,

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

      refreshCurrentPage,
      refreshTable,

      gridRef,
      tableProps,

      handleChange,
    };
  },
});
</script>
<style lang="less" scoped></style>
