Ben Lin
2024-10-16 1b419ccf217dbcace15987f1c0fe26b9e15d1d4b
src/views/tigerprojects/system/lowcode/composition/Config.vue
@@ -1,465 +1,304 @@
<!--
 * @Description: file content
 * @Description: 组合页面中的设置页面
 * @Author: Ben Lin
 * @version: 
 * @Date: 2024-06-24 23:44:31
 * @LastEditors: Ben Lin
 * @LastEditTime: 2024-06-25 21:34:33
 * @LastEditTime: 2024-09-29 16:23:30
-->
<template>
  <Card title="行为配置">
    <BasicForm @register="registerForm">
      <template #[item]="{ field }" v-for="item in crudColSlots" :key="item">
  <Card :title="GetTitle(configType)['configTitle']">
    <BasicForm
      @register="useForms[d]"
      @submit="customSubmitFunc"
      v-for="d in Object.keys(useForms)"
      :key="d"
      v-show="d == configType"
    >
      <template #[item.name]="{ field }" v-for="item in GetCrudColSlots()" :key="item.name">
        <a-button
          v-if="field"
          class="mt-1 ml-1"
          size="small"
          @click="handleSelectItem(item)"
          preIcon="search|svg"
          @click="SelectItemInForm(item.name)"
          :preIcon="item.icon"
        />
        <GeneralModal
          @register="registerItemAdd"
          @success="(d, u) => handleItemSuccess(d, u, item)"
          @register="useModalData[item.name][0]"
          @success="(d, u) => SelectInFormSuccess(d, u, item.name)"
        />
        <GeneralCrudModal @register="useModalsCrudInForm[item.name][0]"></GeneralCrudModal>
      </template>
    </BasicForm>
  </Card>
  <Card
    :title="GetTitle(configType, item)['tableTitle']"
    :bordered="false"
    class="!mt-5"
    v-for="item in OtherTables"
    :key="item"
    v-show="showOtherTable[item]"
  >
    <BasicTable @register="useTables[item][0]" v-if="showOtherTable[item]">
      <template #action="{ record }">
        <TableAction :actions="createActions(record, item)" />
      </template>
    </BasicTable>
    <normalDrawer @register="useDrawers[item][0]" @success="(d, u) => EditSuccess(d, u, item)" />
    <GeneralCrudModal @register="useModalsCrud[item][0]"></GeneralCrudModal>
  </Card>
</template>
<script lang="ts" setup>
  import { Ref, inject, nextTick, onMounted, ref, unref, watch } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { Ref, inject, nextTick, onMounted, ref, toRef, toRefs, unref, watch } from 'vue';
  import { BasicForm } from '/@/components/Form/index';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { Card } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import GeneralModal from '/@/views/components/GeneralModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import GeneralCrudModal from '/@/views/components/GeneralCrudModal.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { GetEnum, getEntity } from '/@/api/tigerapi/system';
  import { useLocale } from '/@/locales/useLocale';
  import { isNullOrEmpty } from '/@/utils/is';
  import { isFunction, isNullOrUnDef } from '/@/utils/is';
  import { EntityCustFunctionType } from '/@/api/tigerapi/model/basModel';
  import { editRecord } from '../data';
  import { useDrawer } from '/@/components/Drawer';
  import normalDrawer from '../normalDrawer.vue';
  import { useModal } from '/@/components/Modal';
  const { t } = useI18n();
  const { getLocale } = useLocale();
  const emit = defineEmits(['success', 'register']);
  const [registerItemAdd, { openModal: openItemModal }] = useModal();
  const Prod_Code = inject('prodCode') as Ref<string>;
  const ACT_ID = inject('actionCode') as Ref<string>;
  const Cust_Code = inject('custCode') as Ref<string>;
  const crudColSlots = ref<any>([
    'scanadd',
    'assyadd',
    'testadd',
    'auditadd',
    'printadd',
    'pkgadd',
  const props = defineProps({
    configType: { type: String },
  });
  const configType = toRef(props, 'configType');
  const showOtherTable = ref<any>({}); //显示表格布尔对象
  const objParams = inject('objParams') as Ref<any>;
  const custImport = ref<any[]>([]);
  const EntityCustFunction = ref([
    {
      GetCrudForm(type: string | undefined) {},
      GetCrudColSlots(val, id) {},
      OpenSelectItem(openItemModal: Fn, ...args) {},
      GetSelectSuccess(d, u, ...args) {},
      GetUseModals() {},
      GetUseTables(data: Ref<Recordable[]>, ...args) {},
      GetTitle(type: string | undefined) {},
      nodeChange(params: {
        resetFields: any;
        setFieldsValue: any;
        objParams: Ref<any>;
        selectedNodes: Ref<any[]>;
      }) {},
      SubmitFunc(values: Recordable<any>, type: string, emit) {},
    } as EntityCustFunctionType,
  ]);
  /* 动态import实体名.ts的自定义方法 */
  try {
    custImport.value = await import(`../entityts/${objParams.value['Name']}.ts`);
  } catch (e) {}
  const [
    {
      GetCrudForm,
      GetCrudColSlots,
      nodeChange,
      OpenSelectItem,
      GetSelectSuccess,
      GetTitle,
      SubmitFunc,
      GetUseModals,
      GetUseTables,
      GetUseForm,
      CustFunc,
      GetUseCrudModals,
      ActionItem,
    },
  ] = isNullOrUnDef(custImport.value['default'])
    ? EntityCustFunction.value
    : custImport.value['default']();
  const isNormal = (type: number) => type === 0;
  const isScan = (type: number) => type === 1;
  const isAssy = (type: number) => type === 2;
  const isTest = (type: number) => type === 3;
  const isAudit = (type: number) => type === 4;
  const isPrint = (type: number) => type === 5;
  const isPackage = (type: number) => type === 6;
  const formSchema: FormSchema[] = [
    {
      field: 'PROD_CODE',
      label: '产品编码',
      component: 'Input',
      dynamicDisabled: ({ values }) => {
        return true;
      },
      colProps: { span: 12 },
    },
    {
      field: 'ID',
      label: 'ID',
      component: 'Input',
      show: false,
    },
    {
      field: 'CUST_CODE',
      label: '客户编码',
      component: 'Input',
      dynamicDisabled: ({ values }) => {
        return true;
      },
      colProps: { span: 12 },
    },
    {
      field: 'ACT_TYPE',
      label: '行为类型',
      component: 'ApiSelect',
      colProps: { span: 12 },
      defaultValue: 0,
      componentProps: {
        api: GetEnum,
        params: { name: 'MES_PROD_ACTION+ACT_TYPEs' },
        resultField: 'Data',
        labelField: unref(getLocale) == 'zh_CN' ? 'Desc' : 'Name',
        valueField: 'Value',
        // onChange: (e, v) => {
        //   alert(e)
        //   console.log('ApiSelect====>:', e, v);
        // },
      },
    },
    {
      field: 'IS_ACTIVE',
      label: '是否启用',
      required: true,
      component: 'Select',
      colProps: { span: 12 },
      componentProps: {
        options: [
          {
            label: '是',
            value: 'Y',
            key: 'Y',
          },
          {
            label: '否',
            value: 'N',
            key: 'N',
          },
        ],
      },
    },
    {
      field: 'RULE_CODE',
      label: '扫码验证',
      component: 'Input',
      colProps: { span: 10 },
      ifShow: ({ values }) => isScan(values.ACT_TYPE),
    },
    {
      field: '0',
      label: '1',
      defaultValue: '',
      component: 'Input',
      colProps: { span: 2, pull: 1 },
      ifShow: ({ values }) => isScan(values.ACT_TYPE),
      colSlot: 'scanadd',
    },
    {
      field: 'ITEM_CODE',
      label: '组装上料',
      colProps: { span: 10 },
      component: 'Input',
      ifShow: ({ values }) => isAssy(values.ACT_TYPE),
    },
    {
      field: '00',
      label: '1',
      defaultValue: '',
      component: 'Input',
      colProps: { span: 2, pull: 1 },
      ifShow: ({ values }) => isAssy(values.ACT_TYPE),
      colSlot: 'assyadd',
    },
    {
      field: 'TEST_CODE',
      label: '产品测试',
      colProps: { span: 10 },
      component: 'Input',
      ifShow: ({ values }) => isTest(values.ACT_TYPE),
    },
    {
      field: 'test0',
      label: '1',
      defaultValue: '',
      component: 'Input',
      colProps: { span: 2, pull: 1 },
      ifShow: ({ values }) => isTest(values.ACT_TYPE),
      colSlot: 'testadd',
    },
    {
      field: 'SAPL_CODE',
      label: '产品抽检',
      colProps: { span: 10 },
      component: 'Input',
      ifShow: ({ values }) => isAudit(values.ACT_TYPE),
    },
    {
      field: 'audit0',
      label: '1',
      defaultValue: '',
      component: 'Input',
      colProps: { span: 2, pull: 1 },
      ifShow: ({ values }) => isAudit(values.ACT_TYPE),
      colSlot: 'auditadd',
    },
    {
      field: 'LABEL_CODE',
      label: '标签打印',
      colProps: { span: 10 },
      component: 'Input',
      ifShow: ({ values }) => isPrint(values.ACT_TYPE),
    },
    {
      field: 'print0',
      label: '1',
      defaultValue: '',
      component: 'Input',
      colProps: { span: 2, pull: 1 },
      ifShow: ({ values }) => isPrint(values.ACT_TYPE),
      colSlot: 'printadd',
    },
    {
      field: 'pkgRULE_CODE',
      label: '包装规则',
      colProps: { span: 10 },
      component: 'Input',
      ifShow: ({ values }) => isPackage(values.ACT_TYPE),
    },
    {
      field: 'pkg0',
      label: '1',
      defaultValue: '',
      component: 'Input',
      colProps: { span: 2, pull: 1 },
      ifShow: ({ values }) => isPackage(values.ACT_TYPE),
      colSlot: 'pkgadd',
    },
    {
      field: 'REMARK',
      label: '备注',
      component: 'Input',
      colProps: { span: 12 },
    },
  ];
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    actionColOptions: {
      offset: 8,
      span: 24,
    },
    wrapperCol: {
      span: 15,
    },
    showActionButtonGroup: true,
    submitButtonOptions: {
      text: '提交',
    },
  const useModalData = ref(GetUseModals());
  const data = ref({});
  const useTables = ref(GetUseTables(data, emit));
  const useForms = ref(GetUseForm());
  const useDrawers = ref({});
  const useModalsCrud = ref({});
  const useModalsCrudInForm = ref(GetUseCrudModals());
  const OtherTables = ref(objParams.value['OtherTableName']);
  /* 循环自定义表格名列表,初始化显示表格布尔对象 */
  objParams.value['OtherTableName'].forEach((x) => {
    showOtherTable.value[x] = false;
    useDrawers.value[x] = useDrawer();
    useModalsCrud.value[x] = useModal();
  });
  /* 注入选中节点数据 */
  const selectedNodes = inject('selectedNodes') as Ref<any>;
  watch(
  () => ACT_ID.value,
  (newVal, oldVal) => {
    () => selectedNodes.value,
    (newVal, oldVal) => {
      nextTick(() => {
        getActType();
        if (newVal != oldVal) {
          /* 节点切换事件 */
          nodeChange({ useForms, objParams, selectedNodes: newVal }).then((result) => {
            const setProps = useForms.value[newVal[0].type][1].setProps;
            showOtherTable.value = result.isShow;
            setProps({
              schemas: [],
            });
            setProps({
              schemas: GetCrudForm(newVal[0].type),
            });
            /* 显示其他表格 */
            const name = result['name'];
            if (showOtherTable.value[name]) {
              showOtherTable.value[name] = false;
              data.value[name] = result[name];
              data.value['Action'] = result['Action'];
              useTables.value = GetUseTables(data, emit);
              setTimeout(() => {
                showOtherTable.value[name] = true;
              }, 10);
              setTimeout(() => {
                if (!isNullOrUnDef(name)) {
                  // useTables.value[name][1].setProps({
                  //   dataSource: [],
                  // });
                  // useTables.value[name][1].setProps({
                  //   dataSource: data.value[name],
                  // });
                  useTables.value[name][1].reload();
                }
              }, 1000);
            }
          });
        }
      });
  },
  { deep: true, immediate: true },
);
    },
    { deep: true, immediate: true },
  );
  onMounted(() => {
    getActType();
    /* 节点切换事件 */
    const nodes = selectedNodes.value;
    nodeChange({ useForms, objParams, selectedNodes: nodes }).then((result) => {
      showOtherTable.value = result.isShow;
      data.value[configType.value as string] = result[configType.value as string];
      useTables.value = GetUseTables(data, emit);
      if (showOtherTable.value[result['name']]) {
        data.value[result['name']] = result[result['name']];
        // useTables.value[result['name']][1].setProps({
        //   dataSource: [],
        // });
        // useTables.value[result['name']][1].setProps({
        //   dataSource: result[result['name']],
        // });
        if (!isNullOrUnDef(result['name'])) {
          useTables.value[result['name']][1].reload();
        }
      }
    });
  });
  function getActType() {
    resetFields();
    let sqlcmd = ' 1=1 ';
    if (!isNullOrEmpty(Prod_Code.value)) {
      sqlcmd += `And PROD_CODE = '${Prod_Code.value}'`;
    }
    if (!isNullOrEmpty(Cust_Code.value)) {
      sqlcmd += `And CUST_CODE = '${Cust_Code.value}'`;
    }
    if (!isNullOrEmpty(ACT_ID.value)) {
      sqlcmd += `And ACT_ID = '${ACT_ID.value}'`;
    }
    getEntity({
      sqlcmd: sqlcmd,
      entityName: 'MES_PROD_ACTION',
    }).then((res) => {
      setFieldsValue({
        PROD_CODE: Prod_Code.value,
        ACT_TYPE: res.Data.Items[0].ACT_TYPE
  /**
   * @description: 自定义提交方法
   * @param {*} values
   * @return {*}
   */
  async function customSubmitFunc(values) {
    try {
      SubmitFunc(values, configType.value, emit);
      // values.AUTH_PROD = useUserStore().getUserInfo.prodCode;
      // values.FACTORY = useUserStore().getUserInfo.prodCode;
      // const apiAction = SaveEntity(values, true, 'MES_PROD_ACTION');
      // apiAction.then((action) => {
      //   if (action.IsSuccessed) {
      //     emit('success');
      //   }
      // });
    } catch (e) {}
  }
  /**
   * @description: 生成列表中操作项的按钮
   * @param {*} record
   * @return {*}
   */
  function createActions(record, name) {
    const params = {
      record,
      isUpdate: true,
      entityName: name,
      formJson: GetCrudForm(name),
      ifSave: objParams.value['ifSave'],
      // cType,
      // dtlSlots,
      // formSchemas,
      // useModalData,
      // useFormData,
      crudColSlots: objParams.value['crudColSlots'][name],
    };
    const actionItem = [
      {
        icon: 'clarity:note-edit-line',
        onClick: editRecord.bind(null, useDrawers.value[name][1].openDrawer, params),
        name: undefined,
      },
    ];
    return ActionItem(
      params,
      actionItem,
      useModalsCrud.value[name][1].openModal,
      useTables.value[name][1].reload(),
      objParams.value['CODE'],
    );
  }
  /**
   * @description: 新增编辑返回成功方法
   * @param {*} d
   * @param {*} u
   * @return {*}
   */
  function EditSuccess(d, u, item) {
    if (CustFunc && isFunction(CustFunc)) {
      CustFunc({
        ctype: item,
        values: d,
        data: data,
      }).then(() => {
        /* 显示其他表格 */
        if (showOtherTable.value[item]) {
          showOtherTable.value[item] = false;
          setTimeout(() => {
            showOtherTable.value[item] = true;
          }, 10);
          useTables.value = GetUseTables(data, emit);
          setTimeout(() => {
            useTables.value[item][1].reload();
            useForms.value[configType.value as string][1].resetFields();
            useForms.value[configType.value as string][1].setFieldsValue(
              data.value[configType.value as string][0],
            );
          }, 10);
        }
      });
    });
    }
    useTables.value[item][1].reload();
  }
  async function handleSubmit() {
    // try {
    //   const values = await validate();
    //   setDrawerProps({ confirmLoading: true });
    //   // TODO custom api
    //   //保存工单
    //   if (!unref(isUpdate)) {
    //     values.STATUS = 0;
    //   }
    //   values.AUTH_PROD = useUserStore().getUserInfo.prodCode;
    //   values.FACTORY = useUserStore().getUserInfo.prodCode;
    //   const apiAction = SaveEntity(values, unref(isUpdate), 'BIZ_MES_WO');
    //   apiAction.then((action) => {
    //     if (action.IsSuccessed) {
    //       closeDrawer();
    //       emit('success');
    //     }
    //   });
    // } finally {
    //   setDrawerProps({ confirmLoading: false });
    // }
  }
  const itemCodeModalCfg = {
    title: '物料列表',
    schemas: [
      {
        field: 'ITEM_CODE',
        component: 'Input',
        label: '物料编码',
        colProps: {
          span: 12,
        },
      },
    ],
    ItemColumns: [
      {
        title: t('物料编码'),
        dataIndex: 'ITEM_CODE',
        resizable: true,
        sorter: true,
        width: 200,
      },
      {
        title: t('物料名称'),
        dataIndex: 'ITEM_NAME',
        resizable: true,
        sorter: true,
        width: 180,
      },
    ],
    tableName: 'BAS_ITEM',
    rowKey: 'ITEM_CODE',
    searchInfo: { TABLE_NAME: 'BAS_ITEM' },
  };
  const ruleModalCfg = {
    title: '规则列表',
    schemas: [
      {
        field: 'RULE_CODE',
        component: 'Input',
        label: '规则编码',
        colProps: {
          span: 12,
        },
      },
    ],
    ItemColumns: [
      {
        title: t('规则编码'),
        dataIndex: 'RULE_CODE',
        resizable: true,
        sorter: true,
        width: 200,
      },
      {
        title: t('规则名称'),
        dataIndex: 'RULE_NAME',
        resizable: true,
        sorter: true,
        width: 180,
      },
    ],
    tableName: 'BAS_CODE_RULE',
    rowKey: 'RULE_CODE',
    searchInfo: { TABLE_NAME: 'BAS_CODE_RULE' },
  };
  const printModalCfg = {
    title: '打印模板列表',
    schemas: [
      {
        field: 'LABEL_CODE',
        component: 'Input',
        label: '模板编码',
        colProps: {
          span: 12,
        },
      },
    ],
    ItemColumns: [
      {
        title: t('模板编码'),
        dataIndex: 'LABEL_CODE',
        resizable: true,
        sorter: true,
        width: 200,
      },
      {
        title: t('模板名称'),
        dataIndex: 'LABEL_NAME',
        resizable: true,
        sorter: true,
        width: 180,
      },
    ],
    tableName: 'BAS_LABEL_TEMP',
    rowKey: 'LABEL_CODE',
    searchInfo: { TABLE_NAME: 'BAS_LABEL_TEMP' },
  };
  const pkgModalCfg = {
    title: '包装规则列表',
    schemas: [
      {
        field: 'RULE_CODE',
        component: 'Input',
        label: '包装规则编码',
        colProps: {
          span: 12,
        },
      },
    ],
    ItemColumns: [
      {
        title: t('包装规则编码'),
        dataIndex: 'RULE_CODE',
        resizable: true,
        sorter: true,
        width: 200,
      },
      {
        title: t('包装规则名称'),
        dataIndex: 'RULE_NAME',
        resizable: true,
        sorter: true,
        width: 180,
      },
    ],
    tableName: 'BAS_PKG_RULE',
    rowKey: 'RULE_CODE',
    searchInfo: { TABLE_NAME: 'BAS_PKG_RULE' },
  };
  /**
   * @description: 点击打开弹出选择列表框
   * @param {*} item
   * @return {*}
   */
  function handleSelectItem(item) {
    let config = {};
    switch (item) {
      case 'scanadd':
        config = ruleModalCfg;
        break;
      case 'assyadd':
        config = itemCodeModalCfg;
        break;
      case 'testadd':
        config = itemCodeModalCfg;
        break;
      case 'printadd':
        config = printModalCfg;
        break;
      case 'pkgadd':
        config = pkgModalCfg;
        break;
    }
    openItemModal(true, config);
  function SelectItemInForm(item) {
    const record = useForms.value[configType.value][1].getFieldsValue();
    OpenSelectItem(
      useModalData.value[item][1].openModal,
      item,
      useModalsCrudInForm.value[item][1].openModal,
      record,
      objParams.value['CODE'],
    );
  }
  /**
@@ -469,30 +308,27 @@
   * @param {*} item
   * @return {*}
   */
  function handleItemSuccess(d, u, item) {
    let value = {};
    switch (item) {
      case 'scanadd':
        value = {
          RULE_CODE: d.values['val'],
        };
        break;
      case 'assyadd':
        value = {
          ITEM_CODE: d.values['val'],
        };
        break;
      case 'printadd':
        value = {
          LABEL_CODE: d.values['val'],
        };
        break;
      case 'pkgadd':
        value = {
          pkgRULE_CODE: d.values['val'],
        };
        break;
    }
    setFieldsValue(value);
  function SelectInFormSuccess(d, u, item) {
    GetSelectSuccess(d, u, item).then((result) => {
      useForms.value[configType.value][1].setFieldsValue(result['value']);
      if (!isNullOrUnDef(data.value[configType.value as string])) {
        data.value[configType.value as string].map((x) => {
          Object.getOwnPropertyNames(result['value']).forEach((key) => {
            x[key] = result['value'][key];
          });
        });
      }
      showOtherTable.value = result['isShow'];
      data.value[result.name] = result['data'];
      /* 重新useTable,否则数据不刷新 */
      useTables.value = GetUseTables(data, emit);
      if (showOtherTable.value[result.name]) {
        showOtherTable.value[result.name] = false;
        setTimeout(() => {
          showOtherTable.value[result.name] = true;
        }, 10);
        useTables.value[result.name][1].reload();
      }
    });
  }
</script>