<template>
  <div
    class="main-content main-content-padding production-permission-content"
    id="ProductionPermission"
  >
    <h-card
      :title="t('permission.productionPermission.objectInformation.title')"
      class="margin-bottom list-table list-table-has-card-head"
    >
      <!-- 客体信息 -->
      <table-show :permissionObjectInfos="permissionObjectInfos"></table-show>
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="ProductionPermission-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('permission.productionPermission.tableParams.tableTitle')"
        :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="ProductionPermission-buttonGroup"
            v-bind="menuProps"
            ref="menuRef"
          />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            id="ProductionPermission-buttonGroup-inline"
            v-bind="menuPropsTable"
            ref="menuRefTable"
          />
        </template>
      </h-b-table>
    </h-card>
    <!-- 新建弹窗 -->
    <h-modal
      v-model:visible="visible"
      :title="t('permission.productionPermission.formParams.formTitle')"
      :cancelText="t('platform.common.cancel')"
      :okText="okText"
      width="886px"
      wrap-class-name="full-modal"
      :confirmLoading="confirmLoading"
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleConfirm"
    >
      <add-object-permission
        ref="componentRef"
        :permissionObjectInfos="permissionObjectInfos"
        :isStatus="isStatus"
        :isSingleData="true"
        :modalParam="modalParam"
        @closeDialog="closeDialog"
        @handleLoading="handleLoading"
      />
    </h-modal>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  toRefs,
  watchEffect,
  reactive,
  provide,
  ref,
  createVNode,
  computed,
} from 'vue';
import { useTable, useButtonGroup } from '@crami/bui-platform';
import { message, HModal } from '@crami/ui';
// import { Table as HBTable } from '@crami/bui';
import { ExclamationCircleFilled } from '@ant-design/icons-vue';
import { useHttp } from '@crami/http';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { getObjectPermissionDisplay } from './components/useMethods';
import TableShow from './components/TableShow.vue';
import AddObjectPermission from './components/AddObjectPermission.vue';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';
export default defineComponent({
  name: 'ProductionPermission',
  components: {
    HModal,
    // HBTable,
    TableShow,
    AddObjectPermission,
  },
  props: {
    /**
     * @param {Array} permissionObjectList 【对接数据】客体信息ids
     * @param {String} viewName 【对接数据】产品侧studio配置，不传值的话走默认
     */
    permissionObjectList: {
      type: Array,
      default: () => [
        {
          // productCode: 'PLM_APP_PLM_ITEM_5d9b846ef60f42e1beb9e12343ac6fa4', // 单体授权，用到productCode作为EID传递给后端获取对象授权列表
          // productCode: '2',
          productCode: '',
        },
      ],
    },
    viewName: {
      type: String,
      default: 'P_SYS_OBJPERMISSION_LISTVIEW',
    },
    menuName: {
      type: String,
      default: '',
    },
  },
  setup(props) {
    const { t } = useI18n();

    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    let { lang, connect, companyId, menuName } = commonParams.value;
    // menuName指定一个值
    menuName = 'P_SYS_OBJPERMISSION_MENU';
    /**
     * 客体信息
     * 描述：顶部信息
     */
    let permissionObjectInfos = ref([]);
    const ids = props.permissionObjectList.map(item => {
      return (item as any).productCode || 'P_SYS_COMPANY_155f6a331e804b69a6fc47e6273699fc';
    });
    getObjectPermissionDisplay(ids)
      .then(data => {
        permissionObjectInfos.value = data.length ? data : [];
      })
      .catch(err => {
        console.log(err);
      });
    /**
     * 对象授权
     * 描述：底部[表格|按钮]部分
     */
    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: props.viewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: '/api/dataperservice/dataPerService/getObjPermissionList',
        method: 'post',
        studioParams: {
          viewName: props.viewName,
          lang,
          connect,
          companyId,
          timeZone: commonParams.value?.TIME_ZONE,
          filter: [
            {
              field: 'PERTYPE',
              value: '2',
              operation: '=',
              andOrFlag: 'AND',
            },
            {
              field: 'PEROBJECT',
              value: ids.length ? ids[0] : '',
              operation: '=',
              andOrFlag: 'AND',
            },
          ],
        },
      },
      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('platform.common.operate'),
        width: 160,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'ProductionPermission',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: props.menuName || menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'ProductionPermission',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    // 处理行内操作按钮
    watchEffect(async () => {
      const rowData = getRowMenu('link');
      load(rowData);
    });
    // 刷新
    const refreshTableList = () => {
      tableMethods.query({}, true);
    };
    // 弹窗数据
    const dialogParams = reactive({
      modalParam: {
        EID: '',
        ENAME: '',
        EXPIRETIME: '',
        PERMISSIONS: '',
        PERSUBJECT: '',
      },
      visible: false,
      okText: t(''),
    });
    let isStatus = ref('add');
    // 新建
    const addObjectPermission = () => {
      dialogParams.visible = true;
      isStatus.value = 'add';
      dialogParams.modalParam = {
        EID: '',
        ENAME: '',
        EXPIRETIME: '',
        PERMISSIONS: '',
        PERSUBJECT: '',
      };
    };
    // 编辑
    const editObjectPermission = () => {
      handleDialogParams({
        status: 'edit',
        okText: t('platform.common.save'),
      });
    };
    // 查看
    const viewObjectPermission = () => {
      handleDialogParams({
        status: 'view',
        okText: t('platform.common.ok'),
      });
    };
    // 删除
    const deleteObjectPermission = () => {
      HModal.confirm({
        closable: true,
        icon: createVNode(ExclamationCircleFilled),
        title: t('platform.common.prompt'),
        content: t('platform.common.deleteMsg'),
        class: 'production-permission-delete-modal',
        onOk() {
          deleteDataPer();
        },
      });
    };
    const deleteDataPer = async () => {
      const res = await useHttp({
        url: '/api/dataperservice/dataPerService/deleteDataPer',
        method: 'post',
        params: {
          eidStrs: [tableMethods.getSelectRows()[0].EID],
          companyId,
          connect,
        },
      });
      if (res.code == 200) {
        message.success(res.msg);
        refreshTableList();
      } else {
        message.error(res.msg);
      }
    };
    // 点击[保存|确定]
    const confirmLoading = ref(false);
    const componentRef = ref({});
    const handleConfirm = () => {
      if (isStatus.value === 'view') {
        dialogParams.visible = false;
      } else {
        (componentRef.value as any).submitForm();
      }
    };
    const closeDialog = visible => {
      dialogParams.visible = visible;
      refreshTableList();
    };
    const handleLoading = loading => {
      confirmLoading.value = loading;
    };
    // 处理弹窗传递数据
    const handleDialogParams = ({ status, okText }) => {
      dialogParams.visible = true;
      dialogParams.modalParam = tableMethods.getSelectRows()[0];
      isStatus.value = status;
      dialogParams.okText = okText;
    };
    // 把isStatus给子组件和孙子组件使用
    provide('isStatus', isStatus);
    return {
      ...toRefs(props),
      // 表格字段
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      gridRef,
      tableProps,
      refreshTableList,
      addObjectPermission,
      editObjectPermission,
      viewObjectPermission,
      deleteObjectPermission,
      // 弹窗字段
      ...toRefs(dialogParams),
      handleConfirm,
      closeDialog,
      handleLoading,
      confirmLoading,
      componentRef,
      isStatus,
      permissionObjectInfos,
      // 多语言
      t,
      commonParams,
    };
  },
});
</script>
<style lang="less" scoped></style>
