import DDComponents from '@/components/DDComponents';
import React, { useMemo, useState } from 'react';
import { Button, Form } from 'antd';

const AuditDetailed = (props) => {
  // const [form] = Form.useForm();
  const { items, form, onValuesChange } = props;
  const data = useMemo(() => {
    let linkedData = {};
    items.forEach((d) => {
      const item = d.props;
      if (item.linked) {
        linkedData = { ...linkedData, [item.id]: item.linked };
      }
    });
    const linkedList =
      items
        ?.map((item) => {
          const linked = item.props.linked;
          return linked ? Object.values(linked).flat() : [];
        })
        .flat() || [];
    return { linkedData, linkedList };
  }, [items]);

  const onFinish = (values) => {
    console.log(values);
  };

  const GetComponent = (item) => {
    const { id, label, bizAlias, required, notUpper } = item.props;
    //判断是否关联项
    if (data.linkedList.findIndex((curId) => curId == id) !== -1) {
      let control = null; //当前空间是否显示的条件 当id为control.id的组件选择的选项值为control.value 时显示
      Object.keys(data.linkedData).forEach((ctlIs) => {
        const linked = data.linkedData[ctlIs];
        Object.keys(linked).forEach((value) => {
          const ids = linked[value];
          if (ids.findIndex((curId) => curId == id) !== -1) {
            control = { id: ctlIs, value };
          }
        });
      });
      let currentValue = form.getFieldValue(control?.id);
      if (currentValue != control?.value) return null;
    }

    let formLabel;
    if (bizAlias !== undefined) {
      formLabel = bizAlias;
    } else {
      try {
        // 判断label是否为JSON数组
        formLabel = JSON.parse(label).join(',');
      } catch (error) {
        formLabel = label;
      }
    }

    // const component = DDComponents({ item });
    // if (!component) return null;
    return (
      <Form.Item
        key={id}
        name={id}
        label={formLabel}
        rules={[{ required: required }]}
      >
        <DDComponents item={item} />
      </Form.Item>
    );
  };

  return (
    <Form
      form={form}
      style={{ minHeight: '80vh', overflowY: 'auto', paddingRight: 20 }}
      layout="vertical"
      autoComplete="off"
      onValuesChange={onValuesChange}
      onFinish={onFinish}
    >
      {items.map((item) => GetComponent(item))}
    </Form>
  );
};

export default AuditDetailed;
