import { getCsckSystem } from '@/api/common';
import { FormSchema } from '@/components/Form';
import { isNotEmpty } from '@/utils/is';
import { groupBy } from 'lodash-es';
import { onMounted, ref } from 'vue';

export default (
  formMethods,
  componentProps: FormSchema['componentProps'] = {},
  { currentRow, label = '系统名称/系统版本', actionType }: { currentRow?: any; label?: string; actionType?: string },
) => {
  const options = ref<any[]>([]);

  onMounted(() => {
    formMethods = formMethods?.value ? formMethods.value : formMethods;
    if (currentRow?.systemCode && currentRow?.systemVersion) formMethods.setValues({ system_version: [currentRow.systemCode, currentRow.systemVersion] });

    if (actionType === 'add') {
      getCsckSystem().then(res => {
        const groups = groupBy(res, 'systemCode');
        options.value = Object.keys(groups).map(sysCode => {
          const parent = res.find(item => item['systemCode'] === sysCode);
          return {
            value: parent['systemCode'],
            label: parent['systemName'],
            children: groups[sysCode].map(item => ({
              value: item['systemVersion'],
              label: item['systemVersion'],
            })),
          };
        });
      });
    }
  });

  const formItem: FormSchema[] = [
    {
      field: 'system_version',
      label,
      component: 'Cascader',
      remove: actionType === 'edit',
      componentProps: {
        style: { width: '100%' },
        ...componentProps,
        options,
        on: {
          change: async (value: string[]) => {
            if (isNotEmpty(value) && Array.isArray(value) && value.length === 2) {
              formMethods = formMethods?.value ? formMethods.value : formMethods;
              const [systemCode, systemVersion] = value;
              const instance = await formMethods.getComponentExpose('system_version');
              const nodes = instance.getCheckedNodes();
              if (nodes.length === 1) {
                const { pathLabels } = nodes[0];
                formMethods.setValues({ systemName: pathLabels[0] });
              }
              formMethods.setValues({ systemCode, systemVersion });
            }
          },
        },
      },
      colProps: { span: 24 },
    },
    {
      field: 'systemName',
      label: '系统名称',
      component: 'Input',
      componentProps,
      hidden: actionType === 'add',
    },
    {
      field: 'systemCode',
      label: '系统编号',
      component: 'Input',
      hidden: true,
    },
    {
      field: 'systemVersion',
      label: '系统版本号',
      component: 'Input',
      componentProps,
      hidden: actionType === 'add',
    },
  ];

  return {
    formItem,
  };
};
