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, onValuesChange } = props;

  const behavior = useMemo(() => {
    let data = {};
    items.forEach((d) => {
      const item = d.props;
      if (item.behaviorLinkage) {
        const key = item.id;
        const options = item.options.map((o) => {
          let data;
          try {
            data = JSON.parse(o);
          } catch (error) {
            data = { key: o, value: o };
          }
          return data;
        });
        item.behaviorLinkage.forEach((b) => {
          const value = b.value;
          b.targets.forEach((t) => {
            data[t.fieldId] = {
              key,
              value: options.find((o) => o.key == value)?.value,
            };
          });
        });
      }
    });

    return data;
  }, [items]);

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

  const GetComponent = (item) => {
    const { id, label, bizAlias, required, notUpper } = item.props;
    // 判断是否属于关联项
    if (behavior[id]) {
      const { key, value } = behavior[id];
      let currentValue = form.getFieldValue(key);
      try {
        currentValue = JSON.parse(currentValue);
      } catch (error) {}
      // 判断是否需要渲染
      if (currentValue instanceof Array) {
        if (currentValue?.indexOf(value) == -1) return null;
      } else {
        if (currentValue != 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;
